1 /*
   2  * Copyright (c) 1997, 2024, 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 "compiler/compiler_globals.hpp"
  27 #include "interp_masm_x86.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/interpreterRuntime.hpp"
  30 #include "logging/log.hpp"
  31 #include "oops/arrayOop.hpp"
  32 #include "oops/markWord.hpp"
  33 #include "oops/methodData.hpp"
  34 #include "oops/method.hpp"
  35 #include "oops/resolvedFieldEntry.hpp"
  36 #include "oops/resolvedIndyEntry.hpp"
  37 #include "oops/resolvedMethodEntry.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "prims/jvmtiThreadState.hpp"
  40 #include "runtime/basicLock.hpp"
  41 #include "runtime/frame.inline.hpp"
  42 #include "runtime/javaThread.hpp"
  43 #include "runtime/safepointMechanism.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "utilities/powerOfTwo.hpp"
  46 
  47 // Implementation of InterpreterMacroAssembler
  48 
  49 void InterpreterMacroAssembler::jump_to_entry(address entry) {
  50   assert(entry, "Entry must have been generated by now");
  51   jump(RuntimeAddress(entry));
  52 }
  53 
  54 void InterpreterMacroAssembler::profile_obj_type(Register obj, const Address& mdo_addr) {
  55   Label update, next, none;
  56 
  57 #ifdef _LP64
  58   assert_different_registers(obj, rscratch1, mdo_addr.base(), mdo_addr.index());
  59 #else
  60   assert_different_registers(obj, mdo_addr.base(), mdo_addr.index());
  61 #endif
  62 
  63   interp_verify_oop(obj, atos);
  64 
  65   testptr(obj, obj);
  66   jccb(Assembler::notZero, update);
  67   testptr(mdo_addr, TypeEntries::null_seen);
  68   jccb(Assembler::notZero, next); // null already seen. Nothing to do anymore.
  69   // atomic update to prevent overwriting Klass* with 0
  70   lock();
  71   orptr(mdo_addr, TypeEntries::null_seen);
  72   jmpb(next);
  73 
  74   bind(update);
  75   load_klass(obj, obj, rscratch1);
  76 #ifdef _LP64
  77   mov(rscratch1, obj);
  78 #endif
  79 
  80   xorptr(obj, mdo_addr);
  81   testptr(obj, TypeEntries::type_klass_mask);
  82   jccb(Assembler::zero, next); // klass seen before, nothing to
  83                                // do. The unknown bit may have been
  84                                // set already but no need to check.
  85 
  86   testptr(obj, TypeEntries::type_unknown);
  87   jccb(Assembler::notZero, next); // already unknown. Nothing to do anymore.
  88 
  89   cmpptr(mdo_addr, 0);
  90   jccb(Assembler::equal, none);
  91   cmpptr(mdo_addr, TypeEntries::null_seen);
  92   jccb(Assembler::equal, none);
  93 #ifdef _LP64
  94   // There is a chance that the checks above (re-reading profiling
  95   // data from memory) fail if another thread has just set the
  96   // profiling to this obj's klass
  97   mov(obj, rscratch1);
  98   xorptr(obj, mdo_addr);
  99   testptr(obj, TypeEntries::type_klass_mask);
 100   jccb(Assembler::zero, next);
 101 #endif
 102 
 103   // different than before. Cannot keep accurate profile.
 104   orptr(mdo_addr, TypeEntries::type_unknown);
 105   jmpb(next);
 106 
 107   bind(none);
 108   // first time here. Set profile type.
 109   movptr(mdo_addr, obj);
 110 #ifdef ASSERT
 111   andptr(obj, TypeEntries::type_klass_mask);
 112   verify_klass_ptr(obj);
 113 #endif
 114 
 115   bind(next);
 116 }
 117 
 118 void InterpreterMacroAssembler::profile_arguments_type(Register mdp, Register callee, Register tmp, bool is_virtual) {
 119   if (!ProfileInterpreter) {
 120     return;
 121   }
 122 
 123   if (MethodData::profile_arguments() || MethodData::profile_return()) {
 124     Label profile_continue;
 125 
 126     test_method_data_pointer(mdp, profile_continue);
 127 
 128     int off_to_start = is_virtual ? in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
 129 
 130     cmpb(Address(mdp, in_bytes(DataLayout::tag_offset()) - off_to_start), is_virtual ? DataLayout::virtual_call_type_data_tag : DataLayout::call_type_data_tag);
 131     jcc(Assembler::notEqual, profile_continue);
 132 
 133     if (MethodData::profile_arguments()) {
 134       Label done;
 135       int off_to_args = in_bytes(TypeEntriesAtCall::args_data_offset());
 136       addptr(mdp, off_to_args);
 137 
 138       for (int i = 0; i < TypeProfileArgsLimit; i++) {
 139         if (i > 0 || MethodData::profile_return()) {
 140           // If return value type is profiled we may have no argument to profile
 141           movptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args));
 142           subl(tmp, i*TypeStackSlotEntries::per_arg_count());
 143           cmpl(tmp, TypeStackSlotEntries::per_arg_count());
 144           jcc(Assembler::less, done);
 145         }
 146         movptr(tmp, Address(callee, Method::const_offset()));
 147         load_unsigned_short(tmp, Address(tmp, ConstMethod::size_of_parameters_offset()));
 148         // stack offset o (zero based) from the start of the argument
 149         // list, for n arguments translates into offset n - o - 1 from
 150         // the end of the argument list
 151         subptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::stack_slot_offset(i))-off_to_args));
 152         subl(tmp, 1);
 153         Address arg_addr = argument_address(tmp);
 154         movptr(tmp, arg_addr);
 155 
 156         Address mdo_arg_addr(mdp, in_bytes(TypeEntriesAtCall::argument_type_offset(i))-off_to_args);
 157         profile_obj_type(tmp, mdo_arg_addr);
 158 
 159         int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
 160         addptr(mdp, to_add);
 161         off_to_args += to_add;
 162       }
 163 
 164       if (MethodData::profile_return()) {
 165         movptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args));
 166         subl(tmp, TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
 167       }
 168 
 169       bind(done);
 170 
 171       if (MethodData::profile_return()) {
 172         // We're right after the type profile for the last
 173         // argument. tmp is the number of cells left in the
 174         // CallTypeData/VirtualCallTypeData to reach its end. Non null
 175         // if there's a return to profile.
 176         assert(ReturnTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(), "can't move past ret type");
 177         shll(tmp, log2i_exact((int)DataLayout::cell_size));
 178         addptr(mdp, tmp);
 179       }
 180       movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp);
 181     } else {
 182       assert(MethodData::profile_return(), "either profile call args or call ret");
 183       update_mdp_by_constant(mdp, in_bytes(TypeEntriesAtCall::return_only_size()));
 184     }
 185 
 186     // mdp points right after the end of the
 187     // CallTypeData/VirtualCallTypeData, right after the cells for the
 188     // return value type if there's one
 189 
 190     bind(profile_continue);
 191   }
 192 }
 193 
 194 void InterpreterMacroAssembler::profile_return_type(Register mdp, Register ret, Register tmp) {
 195   assert_different_registers(mdp, ret, tmp, _bcp_register);
 196   if (ProfileInterpreter && MethodData::profile_return()) {
 197     Label profile_continue;
 198 
 199     test_method_data_pointer(mdp, profile_continue);
 200 
 201     if (MethodData::profile_return_jsr292_only()) {
 202       assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
 203 
 204       // If we don't profile all invoke bytecodes we must make sure
 205       // it's a bytecode we indeed profile. We can't go back to the
 206       // beginning of the ProfileData we intend to update to check its
 207       // type because we're right after it and we don't known its
 208       // length
 209       Label do_profile;
 210       cmpb(Address(_bcp_register, 0), Bytecodes::_invokedynamic);
 211       jcc(Assembler::equal, do_profile);
 212       cmpb(Address(_bcp_register, 0), Bytecodes::_invokehandle);
 213       jcc(Assembler::equal, do_profile);
 214       get_method(tmp);
 215       cmpw(Address(tmp, Method::intrinsic_id_offset()), static_cast<int>(vmIntrinsics::_compiledLambdaForm));
 216       jcc(Assembler::notEqual, profile_continue);
 217 
 218       bind(do_profile);
 219     }
 220 
 221     Address mdo_ret_addr(mdp, -in_bytes(ReturnTypeEntry::size()));
 222     mov(tmp, ret);
 223     profile_obj_type(tmp, mdo_ret_addr);
 224 
 225     bind(profile_continue);
 226   }
 227 }
 228 
 229 void InterpreterMacroAssembler::profile_parameters_type(Register mdp, Register tmp1, Register tmp2) {
 230   if (ProfileInterpreter && MethodData::profile_parameters()) {
 231     Label profile_continue;
 232 
 233     test_method_data_pointer(mdp, profile_continue);
 234 
 235     // Load the offset of the area within the MDO used for
 236     // parameters. If it's negative we're not profiling any parameters
 237     movl(tmp1, Address(mdp, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset())));
 238     testl(tmp1, tmp1);
 239     jcc(Assembler::negative, profile_continue);
 240 
 241     // Compute a pointer to the area for parameters from the offset
 242     // and move the pointer to the slot for the last
 243     // parameters. Collect profiling from last parameter down.
 244     // mdo start + parameters offset + array length - 1
 245     addptr(mdp, tmp1);
 246     movptr(tmp1, Address(mdp, ArrayData::array_len_offset()));
 247     decrement(tmp1, TypeStackSlotEntries::per_arg_count());
 248 
 249     Label loop;
 250     bind(loop);
 251 
 252     int off_base = in_bytes(ParametersTypeData::stack_slot_offset(0));
 253     int type_base = in_bytes(ParametersTypeData::type_offset(0));
 254     Address::ScaleFactor per_arg_scale = Address::times(DataLayout::cell_size);
 255     Address arg_off(mdp, tmp1, per_arg_scale, off_base);
 256     Address arg_type(mdp, tmp1, per_arg_scale, type_base);
 257 
 258     // load offset on the stack from the slot for this parameter
 259     movptr(tmp2, arg_off);
 260     negptr(tmp2);
 261     // read the parameter from the local area
 262     movptr(tmp2, Address(_locals_register, tmp2, Interpreter::stackElementScale()));
 263 
 264     // profile the parameter
 265     profile_obj_type(tmp2, arg_type);
 266 
 267     // go to next parameter
 268     decrement(tmp1, TypeStackSlotEntries::per_arg_count());
 269     jcc(Assembler::positive, loop);
 270 
 271     bind(profile_continue);
 272   }
 273 }
 274 
 275 void InterpreterMacroAssembler::call_VM_leaf_base(address entry_point,
 276                                                   int number_of_arguments) {
 277   // interpreter specific
 278   //
 279   // Note: No need to save/restore bcp & locals registers
 280   //       since these are callee saved registers and no blocking/
 281   //       GC can happen in leaf calls.
 282   // Further Note: DO NOT save/restore bcp/locals. If a caller has
 283   // already saved them so that it can use rsi/rdi as temporaries
 284   // then a save/restore here will DESTROY the copy the caller
 285   // saved! There used to be a save_bcp() that only happened in
 286   // the ASSERT path (no restore_bcp). Which caused bizarre failures
 287   // when jvm built with ASSERTs.
 288 #ifdef ASSERT
 289   {
 290     Label L;
 291     cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 292     jcc(Assembler::equal, L);
 293     stop("InterpreterMacroAssembler::call_VM_leaf_base:"
 294          " last_sp != null");
 295     bind(L);
 296   }
 297 #endif
 298   // super call
 299   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
 300   // interpreter specific
 301   // LP64: Used to ASSERT that r13/r14 were equal to frame's bcp/locals
 302   // but since they may not have been saved (and we don't want to
 303   // save them here (see note above) the assert is invalid.
 304 }
 305 
 306 void InterpreterMacroAssembler::call_VM_base(Register oop_result,
 307                                              Register java_thread,
 308                                              Register last_java_sp,
 309                                              address  entry_point,
 310                                              int      number_of_arguments,
 311                                              bool     check_exceptions) {
 312   // interpreter specific
 313   //
 314   // Note: Could avoid restoring locals ptr (callee saved) - however doesn't
 315   //       really make a difference for these runtime calls, since they are
 316   //       slow anyway. Btw., bcp must be saved/restored since it may change
 317   //       due to GC.
 318   NOT_LP64(assert(java_thread == noreg , "not expecting a precomputed java thread");)
 319   save_bcp();
 320 #ifdef ASSERT
 321   {
 322     Label L;
 323     cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 324     jcc(Assembler::equal, L);
 325     stop("InterpreterMacroAssembler::call_VM_base:"
 326          " last_sp isn't null");
 327     bind(L);
 328   }
 329 #endif /* ASSERT */
 330   // super call
 331   MacroAssembler::call_VM_base(oop_result, noreg, last_java_sp,
 332                                entry_point, number_of_arguments,
 333                                check_exceptions);
 334   // interpreter specific
 335   restore_bcp();
 336   restore_locals();
 337 }
 338 
 339 #ifdef _LP64
 340 void InterpreterMacroAssembler::call_VM_preemptable(Register oop_result,
 341                                                     address entry_point,
 342                                                     Register arg_1) {
 343   assert(arg_1 == c_rarg1, "");
 344   Label resume_pc, not_preempted;
 345 
 346 #ifdef ASSERT
 347   {
 348     Label L;
 349     cmpptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
 350     jcc(Assembler::equal, L);
 351     stop("Should not have alternate return address set");
 352     bind(L);
 353   }
 354 #endif /* ASSERT */
 355 
 356   push_cont_fastpath();
 357 
 358   // Make VM call. In case of preemption set last_pc to the one we want to resume to.
 359   lea(rscratch1, resume_pc);
 360   push(rscratch1);
 361   MacroAssembler::call_VM_helper(oop_result, entry_point, 1, false /*check_exceptions*/);
 362   pop(rscratch1);
 363 
 364   pop_cont_fastpath();
 365 
 366   // Check if preempted.
 367   movptr(rscratch1, Address(r15_thread, JavaThread::preempt_alternate_return_offset()));
 368   cmpptr(rscratch1, NULL_WORD);
 369   jccb(Assembler::zero, not_preempted);
 370   movptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
 371   jmp(rscratch1);
 372 
 373   // In case of preemption, this is where we will resume once we finally acquire the monitor.
 374   bind(resume_pc);
 375   restore_after_resume(false /* is_native */);
 376 
 377   bind(not_preempted);
 378 }
 379 
 380 void InterpreterMacroAssembler::restore_after_resume(bool is_native) {
 381   lea(rscratch1, ExternalAddress(Interpreter::cont_resume_interpreter_adapter()));
 382   call(rscratch1);
 383   if (is_native) {
 384     // On resume we need to set up stack as expected.
 385     push(dtos);
 386     push(ltos);
 387   }
 388 }
 389 #else
 390 void InterpreterMacroAssembler::call_VM_preemptable(Register oop_result,
 391                          address entry_point,
 392                          Register arg_1) {
 393   MacroAssembler::call_VM(oop_result, entry_point, arg_1);
 394 }
 395 #endif  // _LP64
 396 
 397 void InterpreterMacroAssembler::check_and_handle_popframe(Register java_thread) {
 398   if (JvmtiExport::can_pop_frame()) {
 399     Label L;
 400     // Initiate popframe handling only if it is not already being
 401     // processed.  If the flag has the popframe_processing bit set, it
 402     // means that this code is called *during* popframe handling - we
 403     // don't want to reenter.
 404     // This method is only called just after the call into the vm in
 405     // call_VM_base, so the arg registers are available.
 406     Register pop_cond = NOT_LP64(java_thread) // Not clear if any other register is available on 32 bit
 407                         LP64_ONLY(c_rarg0);
 408     movl(pop_cond, Address(java_thread, JavaThread::popframe_condition_offset()));
 409     testl(pop_cond, JavaThread::popframe_pending_bit);
 410     jcc(Assembler::zero, L);
 411     testl(pop_cond, JavaThread::popframe_processing_bit);
 412     jcc(Assembler::notZero, L);
 413     // Call Interpreter::remove_activation_preserving_args_entry() to get the
 414     // address of the same-named entrypoint in the generated interpreter code.
 415     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry));
 416     jmp(rax);
 417     bind(L);
 418     NOT_LP64(get_thread(java_thread);)
 419   }
 420 }
 421 
 422 void InterpreterMacroAssembler::load_earlyret_value(TosState state) {
 423   Register thread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
 424   NOT_LP64(get_thread(thread);)
 425   movptr(rcx, Address(thread, JavaThread::jvmti_thread_state_offset()));
 426   const Address tos_addr(rcx, JvmtiThreadState::earlyret_tos_offset());
 427   const Address oop_addr(rcx, JvmtiThreadState::earlyret_oop_offset());
 428   const Address val_addr(rcx, JvmtiThreadState::earlyret_value_offset());
 429 #ifdef _LP64
 430   switch (state) {
 431     case atos: movptr(rax, oop_addr);
 432                movptr(oop_addr, NULL_WORD);
 433                interp_verify_oop(rax, state);         break;
 434     case ltos: movptr(rax, val_addr);                 break;
 435     case btos:                                   // fall through
 436     case ztos:                                   // fall through
 437     case ctos:                                   // fall through
 438     case stos:                                   // fall through
 439     case itos: movl(rax, val_addr);                 break;
 440     case ftos: load_float(val_addr);                break;
 441     case dtos: load_double(val_addr);               break;
 442     case vtos: /* nothing to do */                  break;
 443     default  : ShouldNotReachHere();
 444   }
 445   // Clean up tos value in the thread object
 446   movl(tos_addr, ilgl);
 447   movl(val_addr, NULL_WORD);
 448 #else
 449   const Address val_addr1(rcx, JvmtiThreadState::earlyret_value_offset()
 450                              + in_ByteSize(wordSize));
 451   switch (state) {
 452     case atos: movptr(rax, oop_addr);
 453                movptr(oop_addr, NULL_WORD);
 454                interp_verify_oop(rax, state);         break;
 455     case ltos:
 456                movl(rdx, val_addr1);               // fall through
 457     case btos:                                     // fall through
 458     case ztos:                                     // fall through
 459     case ctos:                                     // fall through
 460     case stos:                                     // fall through
 461     case itos: movl(rax, val_addr);                   break;
 462     case ftos: load_float(val_addr);                  break;
 463     case dtos: load_double(val_addr);                 break;
 464     case vtos: /* nothing to do */                    break;
 465     default  : ShouldNotReachHere();
 466   }
 467 #endif // _LP64
 468   // Clean up tos value in the thread object
 469   movl(tos_addr, ilgl);
 470   movptr(val_addr, NULL_WORD);
 471   NOT_LP64(movptr(val_addr1, NULL_WORD);)
 472 }
 473 
 474 
 475 void InterpreterMacroAssembler::check_and_handle_earlyret(Register java_thread) {
 476   if (JvmtiExport::can_force_early_return()) {
 477     Label L;
 478     Register tmp = LP64_ONLY(c_rarg0) NOT_LP64(java_thread);
 479     Register rthread = LP64_ONLY(r15_thread) NOT_LP64(java_thread);
 480 
 481     movptr(tmp, Address(rthread, JavaThread::jvmti_thread_state_offset()));
 482     testptr(tmp, tmp);
 483     jcc(Assembler::zero, L); // if (thread->jvmti_thread_state() == nullptr) exit;
 484 
 485     // Initiate earlyret handling only if it is not already being processed.
 486     // If the flag has the earlyret_processing bit set, it means that this code
 487     // is called *during* earlyret handling - we don't want to reenter.
 488     movl(tmp, Address(tmp, JvmtiThreadState::earlyret_state_offset()));
 489     cmpl(tmp, JvmtiThreadState::earlyret_pending);
 490     jcc(Assembler::notEqual, L);
 491 
 492     // Call Interpreter::remove_activation_early_entry() to get the address of the
 493     // same-named entrypoint in the generated interpreter code.
 494     NOT_LP64(get_thread(java_thread);)
 495     movptr(tmp, Address(rthread, JavaThread::jvmti_thread_state_offset()));
 496 #ifdef _LP64
 497     movl(tmp, Address(tmp, JvmtiThreadState::earlyret_tos_offset()));
 498     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), tmp);
 499 #else
 500     pushl(Address(tmp, JvmtiThreadState::earlyret_tos_offset()));
 501     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), 1);
 502 #endif // _LP64
 503     jmp(rax);
 504     bind(L);
 505     NOT_LP64(get_thread(java_thread);)
 506   }
 507 }
 508 
 509 void InterpreterMacroAssembler::get_unsigned_2_byte_index_at_bcp(Register reg, int bcp_offset) {
 510   assert(bcp_offset >= 0, "bcp is still pointing to start of bytecode");
 511   load_unsigned_short(reg, Address(_bcp_register, bcp_offset));
 512   bswapl(reg);
 513   shrl(reg, 16);
 514 }
 515 
 516 void InterpreterMacroAssembler::get_cache_index_at_bcp(Register index,
 517                                                        int bcp_offset,
 518                                                        size_t index_size) {
 519   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
 520   if (index_size == sizeof(u2)) {
 521     load_unsigned_short(index, Address(_bcp_register, bcp_offset));
 522   } else if (index_size == sizeof(u4)) {
 523     movl(index, Address(_bcp_register, bcp_offset));
 524   } else if (index_size == sizeof(u1)) {
 525     load_unsigned_byte(index, Address(_bcp_register, bcp_offset));
 526   } else {
 527     ShouldNotReachHere();
 528   }
 529 }
 530 
 531 // Load object from cpool->resolved_references(index)
 532 void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result,
 533                                                                  Register index,
 534                                                                  Register tmp) {
 535   assert_different_registers(result, index);
 536 
 537   get_constant_pool(result);
 538   // load pointer for resolved_references[] objArray
 539   movptr(result, Address(result, ConstantPool::cache_offset()));
 540   movptr(result, Address(result, ConstantPoolCache::resolved_references_offset()));
 541   resolve_oop_handle(result, tmp);
 542   load_heap_oop(result, Address(result, index,
 543                                 UseCompressedOops ? Address::times_4 : Address::times_ptr,
 544                                 arrayOopDesc::base_offset_in_bytes(T_OBJECT)), tmp);
 545 }
 546 
 547 // load cpool->resolved_klass_at(index)
 548 void InterpreterMacroAssembler::load_resolved_klass_at_index(Register klass,
 549                                                              Register cpool,
 550                                                              Register index) {
 551   assert_different_registers(cpool, index);
 552 
 553   movw(index, Address(cpool, index, Address::times_ptr, sizeof(ConstantPool)));
 554   Register resolved_klasses = cpool;
 555   movptr(resolved_klasses, Address(cpool, ConstantPool::resolved_klasses_offset()));
 556   movptr(klass, Address(resolved_klasses, index, Address::times_ptr, Array<Klass*>::base_offset_in_bytes()));
 557 }
 558 
 559 // Generate a subtype check: branch to ok_is_subtype if sub_klass is a
 560 // subtype of super_klass.
 561 //
 562 // Args:
 563 //      rax: superklass
 564 //      Rsub_klass: subklass
 565 //
 566 // Kills:
 567 //      rcx, rdi
 568 void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass,
 569                                                   Label& ok_is_subtype) {
 570   assert(Rsub_klass != rax, "rax holds superklass");
 571   LP64_ONLY(assert(Rsub_klass != r14, "r14 holds locals");)
 572   LP64_ONLY(assert(Rsub_klass != r13, "r13 holds bcp");)
 573   assert(Rsub_klass != rcx, "rcx holds 2ndary super array length");
 574   assert(Rsub_klass != rdi, "rdi holds 2ndary super array scan ptr");
 575 
 576   // Profile the not-null value's klass.
 577   profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, reloads rdi
 578 
 579   // Do the check.
 580   check_klass_subtype(Rsub_klass, rax, rcx, ok_is_subtype); // blows rcx
 581 }
 582 
 583 
 584 #ifndef _LP64
 585 void InterpreterMacroAssembler::f2ieee() {
 586   if (IEEEPrecision) {
 587     fstp_s(Address(rsp, 0));
 588     fld_s(Address(rsp, 0));
 589   }
 590 }
 591 
 592 
 593 void InterpreterMacroAssembler::d2ieee() {
 594   if (IEEEPrecision) {
 595     fstp_d(Address(rsp, 0));
 596     fld_d(Address(rsp, 0));
 597   }
 598 }
 599 #endif // _LP64
 600 
 601 // Java Expression Stack
 602 
 603 void InterpreterMacroAssembler::pop_ptr(Register r) {
 604   pop(r);
 605 }
 606 
 607 void InterpreterMacroAssembler::push_ptr(Register r) {
 608   push(r);
 609 }
 610 
 611 void InterpreterMacroAssembler::push_i(Register r) {
 612   push(r);
 613 }
 614 
 615 void InterpreterMacroAssembler::push_i_or_ptr(Register r) {
 616   push(r);
 617 }
 618 
 619 void InterpreterMacroAssembler::push_f(XMMRegister r) {
 620   subptr(rsp, wordSize);
 621   movflt(Address(rsp, 0), r);
 622 }
 623 
 624 void InterpreterMacroAssembler::pop_f(XMMRegister r) {
 625   movflt(r, Address(rsp, 0));
 626   addptr(rsp, wordSize);
 627 }
 628 
 629 void InterpreterMacroAssembler::push_d(XMMRegister r) {
 630   subptr(rsp, 2 * wordSize);
 631   movdbl(Address(rsp, 0), r);
 632 }
 633 
 634 void InterpreterMacroAssembler::pop_d(XMMRegister r) {
 635   movdbl(r, Address(rsp, 0));
 636   addptr(rsp, 2 * Interpreter::stackElementSize);
 637 }
 638 
 639 #ifdef _LP64
 640 void InterpreterMacroAssembler::pop_i(Register r) {
 641   // XXX can't use pop currently, upper half non clean
 642   movl(r, Address(rsp, 0));
 643   addptr(rsp, wordSize);
 644 }
 645 
 646 void InterpreterMacroAssembler::pop_l(Register r) {
 647   movq(r, Address(rsp, 0));
 648   addptr(rsp, 2 * Interpreter::stackElementSize);
 649 }
 650 
 651 void InterpreterMacroAssembler::push_l(Register r) {
 652   subptr(rsp, 2 * wordSize);
 653   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(0)), r         );
 654   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(1)), NULL_WORD );
 655 }
 656 
 657 void InterpreterMacroAssembler::pop(TosState state) {
 658   switch (state) {
 659   case atos: pop_ptr();                 break;
 660   case btos:
 661   case ztos:
 662   case ctos:
 663   case stos:
 664   case itos: pop_i();                   break;
 665   case ltos: pop_l();                   break;
 666   case ftos: pop_f(xmm0);               break;
 667   case dtos: pop_d(xmm0);               break;
 668   case vtos: /* nothing to do */        break;
 669   default:   ShouldNotReachHere();
 670   }
 671   interp_verify_oop(rax, state);
 672 }
 673 
 674 void InterpreterMacroAssembler::push(TosState state) {
 675   interp_verify_oop(rax, state);
 676   switch (state) {
 677   case atos: push_ptr();                break;
 678   case btos:
 679   case ztos:
 680   case ctos:
 681   case stos:
 682   case itos: push_i();                  break;
 683   case ltos: push_l();                  break;
 684   case ftos: push_f(xmm0);              break;
 685   case dtos: push_d(xmm0);              break;
 686   case vtos: /* nothing to do */        break;
 687   default  : ShouldNotReachHere();
 688   }
 689 }
 690 #else
 691 void InterpreterMacroAssembler::pop_i(Register r) {
 692   pop(r);
 693 }
 694 
 695 void InterpreterMacroAssembler::pop_l(Register lo, Register hi) {
 696   pop(lo);
 697   pop(hi);
 698 }
 699 
 700 void InterpreterMacroAssembler::pop_f() {
 701   fld_s(Address(rsp, 0));
 702   addptr(rsp, 1 * wordSize);
 703 }
 704 
 705 void InterpreterMacroAssembler::pop_d() {
 706   fld_d(Address(rsp, 0));
 707   addptr(rsp, 2 * wordSize);
 708 }
 709 
 710 
 711 void InterpreterMacroAssembler::pop(TosState state) {
 712   switch (state) {
 713     case atos: pop_ptr(rax);                                 break;
 714     case btos:                                               // fall through
 715     case ztos:                                               // fall through
 716     case ctos:                                               // fall through
 717     case stos:                                               // fall through
 718     case itos: pop_i(rax);                                   break;
 719     case ltos: pop_l(rax, rdx);                              break;
 720     case ftos:
 721       if (UseSSE >= 1) {
 722         pop_f(xmm0);
 723       } else {
 724         pop_f();
 725       }
 726       break;
 727     case dtos:
 728       if (UseSSE >= 2) {
 729         pop_d(xmm0);
 730       } else {
 731         pop_d();
 732       }
 733       break;
 734     case vtos: /* nothing to do */                           break;
 735     default  : ShouldNotReachHere();
 736   }
 737   interp_verify_oop(rax, state);
 738 }
 739 
 740 
 741 void InterpreterMacroAssembler::push_l(Register lo, Register hi) {
 742   push(hi);
 743   push(lo);
 744 }
 745 
 746 void InterpreterMacroAssembler::push_f() {
 747   // Do not schedule for no AGI! Never write beyond rsp!
 748   subptr(rsp, 1 * wordSize);
 749   fstp_s(Address(rsp, 0));
 750 }
 751 
 752 void InterpreterMacroAssembler::push_d() {
 753   // Do not schedule for no AGI! Never write beyond rsp!
 754   subptr(rsp, 2 * wordSize);
 755   fstp_d(Address(rsp, 0));
 756 }
 757 
 758 
 759 void InterpreterMacroAssembler::push(TosState state) {
 760   interp_verify_oop(rax, state);
 761   switch (state) {
 762     case atos: push_ptr(rax); break;
 763     case btos:                                               // fall through
 764     case ztos:                                               // fall through
 765     case ctos:                                               // fall through
 766     case stos:                                               // fall through
 767     case itos: push_i(rax);                                    break;
 768     case ltos: push_l(rax, rdx);                               break;
 769     case ftos:
 770       if (UseSSE >= 1) {
 771         push_f(xmm0);
 772       } else {
 773         push_f();
 774       }
 775       break;
 776     case dtos:
 777       if (UseSSE >= 2) {
 778         push_d(xmm0);
 779       } else {
 780         push_d();
 781       }
 782       break;
 783     case vtos: /* nothing to do */                             break;
 784     default  : ShouldNotReachHere();
 785   }
 786 }
 787 #endif // _LP64
 788 
 789 
 790 // Helpers for swap and dup
 791 void InterpreterMacroAssembler::load_ptr(int n, Register val) {
 792   movptr(val, Address(rsp, Interpreter::expr_offset_in_bytes(n)));
 793 }
 794 
 795 void InterpreterMacroAssembler::store_ptr(int n, Register val) {
 796   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(n)), val);
 797 }
 798 
 799 
 800 void InterpreterMacroAssembler::prepare_to_jump_from_interpreted() {
 801   // set sender sp
 802   lea(_bcp_register, Address(rsp, wordSize));
 803   // record last_sp
 804   mov(rcx, _bcp_register);
 805   subptr(rcx, rbp);
 806   sarptr(rcx, LogBytesPerWord);
 807   movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), rcx);
 808 }
 809 
 810 
 811 // Jump to from_interpreted entry of a call unless single stepping is possible
 812 // in this thread in which case we must call the i2i entry
 813 void InterpreterMacroAssembler::jump_from_interpreted(Register method, Register temp) {
 814   prepare_to_jump_from_interpreted();
 815 
 816   if (JvmtiExport::can_post_interpreter_events()) {
 817     Label run_compiled_code;
 818     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
 819     // compiled code in threads for which the event is enabled.  Check here for
 820     // interp_only_mode if these events CAN be enabled.
 821     // interp_only is an int, on little endian it is sufficient to test the byte only
 822     // Is a cmpl faster?
 823     LP64_ONLY(temp = r15_thread;)
 824     NOT_LP64(get_thread(temp);)
 825     cmpb(Address(temp, JavaThread::interp_only_mode_offset()), 0);
 826     jccb(Assembler::zero, run_compiled_code);
 827     jmp(Address(method, Method::interpreter_entry_offset()));
 828     bind(run_compiled_code);
 829   }
 830 
 831   jmp(Address(method, Method::from_interpreted_offset()));
 832 }
 833 
 834 // The following two routines provide a hook so that an implementation
 835 // can schedule the dispatch in two parts.  x86 does not do this.
 836 void InterpreterMacroAssembler::dispatch_prolog(TosState state, int step) {
 837   // Nothing x86 specific to be done here
 838 }
 839 
 840 void InterpreterMacroAssembler::dispatch_epilog(TosState state, int step) {
 841   dispatch_next(state, step);
 842 }
 843 
 844 void InterpreterMacroAssembler::dispatch_base(TosState state,
 845                                               address* table,
 846                                               bool verifyoop,
 847                                               bool generate_poll) {
 848   verify_FPU(1, state);
 849   if (VerifyActivationFrameSize) {
 850     Label L;
 851     mov(rcx, rbp);
 852     subptr(rcx, rsp);
 853     int32_t min_frame_size =
 854       (frame::link_offset - frame::interpreter_frame_initial_sp_offset) *
 855       wordSize;
 856     cmpptr(rcx, min_frame_size);
 857     jcc(Assembler::greaterEqual, L);
 858     stop("broken stack frame");
 859     bind(L);
 860   }
 861   if (verifyoop) {
 862     interp_verify_oop(rax, state);
 863   }
 864 
 865   address* const safepoint_table = Interpreter::safept_table(state);
 866 #ifdef _LP64
 867   Label no_safepoint, dispatch;
 868   if (table != safepoint_table && generate_poll) {
 869     NOT_PRODUCT(block_comment("Thread-local Safepoint poll"));
 870     testb(Address(r15_thread, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
 871 
 872     jccb(Assembler::zero, no_safepoint);
 873     lea(rscratch1, ExternalAddress((address)safepoint_table));
 874     jmpb(dispatch);
 875   }
 876 
 877   bind(no_safepoint);
 878   lea(rscratch1, ExternalAddress((address)table));
 879   bind(dispatch);
 880   jmp(Address(rscratch1, rbx, Address::times_8));
 881 
 882 #else
 883   Address index(noreg, rbx, Address::times_ptr);
 884   if (table != safepoint_table && generate_poll) {
 885     NOT_PRODUCT(block_comment("Thread-local Safepoint poll"));
 886     Label no_safepoint;
 887     const Register thread = rcx;
 888     get_thread(thread);
 889     testb(Address(thread, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
 890 
 891     jccb(Assembler::zero, no_safepoint);
 892     ArrayAddress dispatch_addr(ExternalAddress((address)safepoint_table), index);
 893     jump(dispatch_addr, noreg);
 894     bind(no_safepoint);
 895   }
 896 
 897   {
 898     ArrayAddress dispatch_addr(ExternalAddress((address)table), index);
 899     jump(dispatch_addr, noreg);
 900   }
 901 #endif // _LP64
 902 }
 903 
 904 void InterpreterMacroAssembler::dispatch_only(TosState state, bool generate_poll) {
 905   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll);
 906 }
 907 
 908 void InterpreterMacroAssembler::dispatch_only_normal(TosState state) {
 909   dispatch_base(state, Interpreter::normal_table(state));
 910 }
 911 
 912 void InterpreterMacroAssembler::dispatch_only_noverify(TosState state) {
 913   dispatch_base(state, Interpreter::normal_table(state), false);
 914 }
 915 
 916 
 917 void InterpreterMacroAssembler::dispatch_next(TosState state, int step, bool generate_poll) {
 918   // load next bytecode (load before advancing _bcp_register to prevent AGI)
 919   load_unsigned_byte(rbx, Address(_bcp_register, step));
 920   // advance _bcp_register
 921   increment(_bcp_register, step);
 922   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll);
 923 }
 924 
 925 void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
 926   // load current bytecode
 927   load_unsigned_byte(rbx, Address(_bcp_register, 0));
 928   dispatch_base(state, table);
 929 }
 930 
 931 void InterpreterMacroAssembler::narrow(Register result) {
 932 
 933   // Get method->_constMethod->_result_type
 934   movptr(rcx, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
 935   movptr(rcx, Address(rcx, Method::const_offset()));
 936   load_unsigned_byte(rcx, Address(rcx, ConstMethod::result_type_offset()));
 937 
 938   Label done, notBool, notByte, notChar;
 939 
 940   // common case first
 941   cmpl(rcx, T_INT);
 942   jcc(Assembler::equal, done);
 943 
 944   // mask integer result to narrower return type.
 945   cmpl(rcx, T_BOOLEAN);
 946   jcc(Assembler::notEqual, notBool);
 947   andl(result, 0x1);
 948   jmp(done);
 949 
 950   bind(notBool);
 951   cmpl(rcx, T_BYTE);
 952   jcc(Assembler::notEqual, notByte);
 953   LP64_ONLY(movsbl(result, result);)
 954   NOT_LP64(shll(result, 24);)      // truncate upper 24 bits
 955   NOT_LP64(sarl(result, 24);)      // and sign-extend byte
 956   jmp(done);
 957 
 958   bind(notByte);
 959   cmpl(rcx, T_CHAR);
 960   jcc(Assembler::notEqual, notChar);
 961   LP64_ONLY(movzwl(result, result);)
 962   NOT_LP64(andl(result, 0xFFFF);)  // truncate upper 16 bits
 963   jmp(done);
 964 
 965   bind(notChar);
 966   // cmpl(rcx, T_SHORT);  // all that's left
 967   // jcc(Assembler::notEqual, done);
 968   LP64_ONLY(movswl(result, result);)
 969   NOT_LP64(shll(result, 16);)      // truncate upper 16 bits
 970   NOT_LP64(sarl(result, 16);)      // and sign-extend short
 971 
 972   // Nothing to do for T_INT
 973   bind(done);
 974 }
 975 
 976 // remove activation
 977 //
 978 // Apply stack watermark barrier.
 979 // Unlock the receiver if this is a synchronized method.
 980 // Unlock any Java monitors from synchronized blocks.
 981 // Remove the activation from the stack.
 982 //
 983 // If there are locked Java monitors
 984 //    If throw_monitor_exception
 985 //       throws IllegalMonitorStateException
 986 //    Else if install_monitor_exception
 987 //       installs IllegalMonitorStateException
 988 //    Else
 989 //       no error processing
 990 void InterpreterMacroAssembler::remove_activation(
 991         TosState state,
 992         Register ret_addr,
 993         bool throw_monitor_exception,
 994         bool install_monitor_exception,
 995         bool notify_jvmdi) {
 996   // Note: Registers rdx xmm0 may be in use for the
 997   // result check if synchronized method
 998   Label unlocked, unlock, no_unlock;
 999 
1000   const Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1001   const Register robj    = LP64_ONLY(c_rarg1) NOT_LP64(rdx);
1002   const Register rmon    = LP64_ONLY(c_rarg1) NOT_LP64(rcx);
1003                               // monitor pointers need different register
1004                               // because rdx may have the result in it
1005   NOT_LP64(get_thread(rthread);)
1006 
1007   // The below poll is for the stack watermark barrier. It allows fixing up frames lazily,
1008   // that would normally not be safe to use. Such bad returns into unsafe territory of
1009   // the stack, will call InterpreterRuntime::at_unwind.
1010   Label slow_path;
1011   Label fast_path;
1012   safepoint_poll(slow_path, rthread, true /* at_return */, false /* in_nmethod */);
1013   jmp(fast_path);
1014   bind(slow_path);
1015   push(state);
1016   set_last_Java_frame(rthread, noreg, rbp, (address)pc(), rscratch1);
1017   super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), rthread);
1018   NOT_LP64(get_thread(rthread);) // call_VM clobbered it, restore
1019   reset_last_Java_frame(rthread, true);
1020   pop(state);
1021   bind(fast_path);
1022 
1023   // get the value of _do_not_unlock_if_synchronized into rdx
1024   const Address do_not_unlock_if_synchronized(rthread,
1025     in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1026   movbool(rbx, do_not_unlock_if_synchronized);
1027   movbool(do_not_unlock_if_synchronized, false); // reset the flag
1028 
1029  // get method access flags
1030   movptr(rcx, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
1031   movl(rcx, Address(rcx, Method::access_flags_offset()));
1032   testl(rcx, JVM_ACC_SYNCHRONIZED);
1033   jcc(Assembler::zero, unlocked);
1034 
1035   // Don't unlock anything if the _do_not_unlock_if_synchronized flag
1036   // is set.
1037   testbool(rbx);
1038   jcc(Assembler::notZero, no_unlock);
1039 
1040   // unlock monitor
1041   push(state); // save result
1042 
1043   // BasicObjectLock will be first in list, since this is a
1044   // synchronized method. However, need to check that the object has
1045   // not been unlocked by an explicit monitorexit bytecode.
1046   const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset *
1047                         wordSize - (int) sizeof(BasicObjectLock));
1048   // We use c_rarg1/rdx so that if we go slow path it will be the correct
1049   // register for unlock_object to pass to VM directly
1050   lea(robj, monitor); // address of first monitor
1051 
1052   movptr(rax, Address(robj, BasicObjectLock::obj_offset()));
1053   testptr(rax, rax);
1054   jcc(Assembler::notZero, unlock);
1055 
1056   pop(state);
1057   if (throw_monitor_exception) {
1058     // Entry already unlocked, need to throw exception
1059     NOT_LP64(empty_FPU_stack();)  // remove possible return value from FPU-stack, otherwise stack could overflow
1060     call_VM(noreg, CAST_FROM_FN_PTR(address,
1061                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1062     should_not_reach_here();
1063   } else {
1064     // Monitor already unlocked during a stack unroll. If requested,
1065     // install an illegal_monitor_state_exception.  Continue with
1066     // stack unrolling.
1067     if (install_monitor_exception) {
1068       NOT_LP64(empty_FPU_stack();)
1069       call_VM(noreg, CAST_FROM_FN_PTR(address,
1070                      InterpreterRuntime::new_illegal_monitor_state_exception));
1071     }
1072     jmp(unlocked);
1073   }
1074 
1075   bind(unlock);
1076   unlock_object(robj);
1077   pop(state);
1078 
1079   // Check that for block-structured locking (i.e., that all locked
1080   // objects has been unlocked)
1081   bind(unlocked);
1082 
1083   // rax, rdx: Might contain return value
1084 
1085   // Check that all monitors are unlocked
1086   {
1087     Label loop, exception, entry, restart;
1088     const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
1089     const Address monitor_block_top(
1090         rbp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
1091     const Address monitor_block_bot(
1092         rbp, frame::interpreter_frame_initial_sp_offset * wordSize);
1093 
1094     bind(restart);
1095     // We use c_rarg1 so that if we go slow path it will be the correct
1096     // register for unlock_object to pass to VM directly
1097     movptr(rmon, monitor_block_top); // derelativize pointer
1098     lea(rmon, Address(rbp, rmon, Address::times_ptr));
1099     // c_rarg1 points to current entry, starting with top-most entry
1100 
1101     lea(rbx, monitor_block_bot);  // points to word before bottom of
1102                                   // monitor block
1103     jmp(entry);
1104 
1105     // Entry already locked, need to throw exception
1106     bind(exception);
1107 
1108     if (throw_monitor_exception) {
1109       // Throw exception
1110       NOT_LP64(empty_FPU_stack();)
1111       MacroAssembler::call_VM(noreg,
1112                               CAST_FROM_FN_PTR(address, InterpreterRuntime::
1113                                    throw_illegal_monitor_state_exception));
1114       should_not_reach_here();
1115     } else {
1116       // Stack unrolling. Unlock object and install illegal_monitor_exception.
1117       // Unlock does not block, so don't have to worry about the frame.
1118       // We don't have to preserve c_rarg1 since we are going to throw an exception.
1119 
1120       push(state);
1121       mov(robj, rmon);   // nop if robj and rmon are the same
1122       unlock_object(robj);
1123       pop(state);
1124 
1125       if (install_monitor_exception) {
1126         NOT_LP64(empty_FPU_stack();)
1127         call_VM(noreg, CAST_FROM_FN_PTR(address,
1128                                         InterpreterRuntime::
1129                                         new_illegal_monitor_state_exception));
1130       }
1131 
1132       jmp(restart);
1133     }
1134 
1135     bind(loop);
1136     // check if current entry is used
1137     cmpptr(Address(rmon, BasicObjectLock::obj_offset()), NULL_WORD);
1138     jcc(Assembler::notEqual, exception);
1139 
1140     addptr(rmon, entry_size); // otherwise advance to next entry
1141     bind(entry);
1142     cmpptr(rmon, rbx); // check if bottom reached
1143     jcc(Assembler::notEqual, loop); // if not at bottom then check this entry
1144   }
1145 
1146   bind(no_unlock);
1147 
1148   // jvmti support
1149   if (notify_jvmdi) {
1150     notify_method_exit(state, NotifyJVMTI);    // preserve TOSCA
1151   } else {
1152     notify_method_exit(state, SkipNotifyJVMTI); // preserve TOSCA
1153   }
1154 
1155   // remove activation
1156   // get sender sp
1157   movptr(rbx,
1158          Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize));
1159   if (StackReservedPages > 0) {
1160     // testing if reserved zone needs to be re-enabled
1161     Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1162     Label no_reserved_zone_enabling;
1163 
1164     NOT_LP64(get_thread(rthread);)
1165 
1166     // check if already enabled - if so no re-enabling needed
1167     assert(sizeof(StackOverflow::StackGuardState) == 4, "unexpected size");
1168     cmpl(Address(rthread, JavaThread::stack_guard_state_offset()), StackOverflow::stack_guard_enabled);
1169     jcc(Assembler::equal, no_reserved_zone_enabling);
1170 
1171     cmpptr(rbx, Address(rthread, JavaThread::reserved_stack_activation_offset()));
1172     jcc(Assembler::lessEqual, no_reserved_zone_enabling);
1173 
1174     call_VM_leaf(
1175       CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), rthread);
1176     call_VM(noreg, CAST_FROM_FN_PTR(address,
1177                    InterpreterRuntime::throw_delayed_StackOverflowError));
1178     should_not_reach_here();
1179 
1180     bind(no_reserved_zone_enabling);
1181   }
1182   leave();                           // remove frame anchor
1183   pop(ret_addr);                     // get return address
1184   mov(rsp, rbx);                     // set sp to sender sp
1185   pop_cont_fastpath();
1186 }
1187 
1188 void InterpreterMacroAssembler::get_method_counters(Register method,
1189                                                     Register mcs, Label& skip) {
1190   Label has_counters;
1191   movptr(mcs, Address(method, Method::method_counters_offset()));
1192   testptr(mcs, mcs);
1193   jcc(Assembler::notZero, has_counters);
1194   call_VM(noreg, CAST_FROM_FN_PTR(address,
1195           InterpreterRuntime::build_method_counters), method);
1196   movptr(mcs, Address(method,Method::method_counters_offset()));
1197   testptr(mcs, mcs);
1198   jcc(Assembler::zero, skip); // No MethodCounters allocated, OutOfMemory
1199   bind(has_counters);
1200 }
1201 
1202 
1203 // Lock object
1204 //
1205 // Args:
1206 //      rdx, c_rarg1: BasicObjectLock to be used for locking
1207 //
1208 // Kills:
1209 //      rax, rbx
1210 void InterpreterMacroAssembler::lock_object(Register lock_reg) {
1211   assert(lock_reg == LP64_ONLY(c_rarg1) NOT_LP64(rdx),
1212          "The argument is only for looks. It must be c_rarg1");
1213 
1214   if (LockingMode == LM_MONITOR) {
1215     call_VM_preemptable(noreg,
1216             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1217             lock_reg);
1218   } else {
1219     Label count_locking, done, slow_case;
1220 
1221     const Register swap_reg = rax; // Must use rax for cmpxchg instruction
1222     const Register tmp_reg = rbx;
1223     const Register obj_reg = LP64_ONLY(c_rarg3) NOT_LP64(rcx); // Will contain the oop
1224     const Register rklass_decode_tmp = rscratch1;
1225 
1226     const int obj_offset = in_bytes(BasicObjectLock::obj_offset());
1227     const int lock_offset = in_bytes(BasicObjectLock::lock_offset());
1228     const int mark_offset = lock_offset +
1229                             BasicLock::displaced_header_offset_in_bytes();
1230 
1231     // Load object pointer into obj_reg
1232     movptr(obj_reg, Address(lock_reg, obj_offset));
1233 
1234     if (DiagnoseSyncOnValueBasedClasses != 0) {
1235       load_klass(tmp_reg, obj_reg, rklass_decode_tmp);
1236       testb(Address(tmp_reg, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
1237       jcc(Assembler::notZero, slow_case);
1238     }
1239 
1240     if (LockingMode == LM_LIGHTWEIGHT) {
1241 #ifdef _LP64
1242       const Register thread = r15_thread;
1243       lightweight_lock(lock_reg, obj_reg, swap_reg, thread, tmp_reg, slow_case);
1244 #else
1245       // Lacking registers and thread on x86_32. Always take slow path.
1246       jmp(slow_case);
1247 #endif
1248     } else if (LockingMode == LM_LEGACY) {
1249       // Load immediate 1 into swap_reg %rax
1250       movl(swap_reg, 1);
1251 
1252       // Load (object->mark() | 1) into swap_reg %rax
1253       orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1254 
1255       // Save (object->mark() | 1) into BasicLock's displaced header
1256       movptr(Address(lock_reg, mark_offset), swap_reg);
1257 
1258       assert(lock_offset == 0,
1259              "displaced header must be first word in BasicObjectLock");
1260 
1261       lock();
1262       cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1263       jcc(Assembler::zero, count_locking);
1264 
1265       const int zero_bits = LP64_ONLY(7) NOT_LP64(3);
1266 
1267       // Fast check for recursive lock.
1268       //
1269       // Can apply the optimization only if this is a stack lock
1270       // allocated in this thread. For efficiency, we can focus on
1271       // recently allocated stack locks (instead of reading the stack
1272       // base and checking whether 'mark' points inside the current
1273       // thread stack):
1274       //  1) (mark & zero_bits) == 0, and
1275       //  2) rsp <= mark < mark + os::pagesize()
1276       //
1277       // Warning: rsp + os::pagesize can overflow the stack base. We must
1278       // neither apply the optimization for an inflated lock allocated
1279       // just above the thread stack (this is why condition 1 matters)
1280       // nor apply the optimization if the stack lock is inside the stack
1281       // of another thread. The latter is avoided even in case of overflow
1282       // because we have guard pages at the end of all stacks. Hence, if
1283       // we go over the stack base and hit the stack of another thread,
1284       // this should not be in a writeable area that could contain a
1285       // stack lock allocated by that thread. As a consequence, a stack
1286       // lock less than page size away from rsp is guaranteed to be
1287       // owned by the current thread.
1288       //
1289       // These 3 tests can be done by evaluating the following
1290       // expression: ((mark - rsp) & (zero_bits - os::vm_page_size())),
1291       // assuming both stack pointer and pagesize have their
1292       // least significant bits clear.
1293       // NOTE: the mark is in swap_reg %rax as the result of cmpxchg
1294       subptr(swap_reg, rsp);
1295       andptr(swap_reg, zero_bits - (int)os::vm_page_size());
1296 
1297       // Save the test result, for recursive case, the result is zero
1298       movptr(Address(lock_reg, mark_offset), swap_reg);
1299       jcc(Assembler::notZero, slow_case);
1300 
1301       bind(count_locking);
1302       inc_held_monitor_count();
1303     }
1304     jmp(done);
1305 
1306     bind(slow_case);
1307 
1308     // Call the runtime routine for slow case
1309     call_VM_preemptable(noreg,
1310             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1311             lock_reg);
1312     bind(done);
1313   }
1314 }
1315 
1316 
1317 // Unlocks an object. Used in monitorexit bytecode and
1318 // remove_activation.  Throws an IllegalMonitorException if object is
1319 // not locked by current thread.
1320 //
1321 // Args:
1322 //      rdx, c_rarg1: BasicObjectLock for lock
1323 //
1324 // Kills:
1325 //      rax
1326 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ... (param regs)
1327 //      rscratch1 (scratch reg)
1328 // rax, rbx, rcx, rdx
1329 void InterpreterMacroAssembler::unlock_object(Register lock_reg) {
1330   assert(lock_reg == LP64_ONLY(c_rarg1) NOT_LP64(rdx),
1331          "The argument is only for looks. It must be c_rarg1");
1332 
1333   if (LockingMode == LM_MONITOR) {
1334     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1335   } else {
1336     Label count_locking, done, slow_case;
1337 
1338     const Register swap_reg   = rax;  // Must use rax for cmpxchg instruction
1339     const Register header_reg = LP64_ONLY(c_rarg2) NOT_LP64(rbx);  // Will contain the old oopMark
1340     const Register obj_reg    = LP64_ONLY(c_rarg3) NOT_LP64(rcx);  // Will contain the oop
1341 
1342     save_bcp(); // Save in case of exception
1343 
1344     if (LockingMode != LM_LIGHTWEIGHT) {
1345       // Convert from BasicObjectLock structure to object and BasicLock
1346       // structure Store the BasicLock address into %rax
1347       lea(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset()));
1348     }
1349 
1350     // Load oop into obj_reg(%c_rarg3)
1351     movptr(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset()));
1352 
1353     // Free entry
1354     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), NULL_WORD);
1355 
1356     if (LockingMode == LM_LIGHTWEIGHT) {
1357 #ifdef _LP64
1358       lightweight_unlock(obj_reg, swap_reg, r15_thread, header_reg, slow_case);
1359 #else
1360       // Lacking registers and thread on x86_32. Always take slow path.
1361       jmp(slow_case);
1362 #endif
1363     } else if (LockingMode == LM_LEGACY) {
1364       // Load the old header from BasicLock structure
1365       movptr(header_reg, Address(swap_reg,
1366                                  BasicLock::displaced_header_offset_in_bytes()));
1367 
1368       // Test for recursion
1369       testptr(header_reg, header_reg);
1370 
1371       // zero for recursive case
1372       jcc(Assembler::zero, count_locking);
1373 
1374       // Atomic swap back the old header
1375       lock();
1376       cmpxchgptr(header_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1377 
1378       // zero for simple unlock of a stack-lock case
1379       jcc(Assembler::notZero, slow_case);
1380 
1381       bind(count_locking);
1382       dec_held_monitor_count();
1383     }
1384     jmp(done);
1385 
1386     bind(slow_case);
1387     // Call the runtime routine for slow case.
1388     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), obj_reg); // restore obj
1389     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1390 
1391     bind(done);
1392 
1393     restore_bcp();
1394   }
1395 }
1396 
1397 void InterpreterMacroAssembler::test_method_data_pointer(Register mdp,
1398                                                          Label& zero_continue) {
1399   assert(ProfileInterpreter, "must be profiling interpreter");
1400   movptr(mdp, Address(rbp, frame::interpreter_frame_mdp_offset * wordSize));
1401   testptr(mdp, mdp);
1402   jcc(Assembler::zero, zero_continue);
1403 }
1404 
1405 
1406 // Set the method data pointer for the current bcp.
1407 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1408   assert(ProfileInterpreter, "must be profiling interpreter");
1409   Label set_mdp;
1410   push(rax);
1411   push(rbx);
1412 
1413   get_method(rbx);
1414   // Test MDO to avoid the call if it is null.
1415   movptr(rax, Address(rbx, in_bytes(Method::method_data_offset())));
1416   testptr(rax, rax);
1417   jcc(Assembler::zero, set_mdp);
1418   // rbx: method
1419   // _bcp_register: bcp
1420   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), rbx, _bcp_register);
1421   // rax: mdi
1422   // mdo is guaranteed to be non-zero here, we checked for it before the call.
1423   movptr(rbx, Address(rbx, in_bytes(Method::method_data_offset())));
1424   addptr(rbx, in_bytes(MethodData::data_offset()));
1425   addptr(rax, rbx);
1426   bind(set_mdp);
1427   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), rax);
1428   pop(rbx);
1429   pop(rax);
1430 }
1431 
1432 void InterpreterMacroAssembler::verify_method_data_pointer() {
1433   assert(ProfileInterpreter, "must be profiling interpreter");
1434 #ifdef ASSERT
1435   Label verify_continue;
1436   push(rax);
1437   push(rbx);
1438   Register arg3_reg = LP64_ONLY(c_rarg3) NOT_LP64(rcx);
1439   Register arg2_reg = LP64_ONLY(c_rarg2) NOT_LP64(rdx);
1440   push(arg3_reg);
1441   push(arg2_reg);
1442   test_method_data_pointer(arg3_reg, verify_continue); // If mdp is zero, continue
1443   get_method(rbx);
1444 
1445   // If the mdp is valid, it will point to a DataLayout header which is
1446   // consistent with the bcp.  The converse is highly probable also.
1447   load_unsigned_short(arg2_reg,
1448                       Address(arg3_reg, in_bytes(DataLayout::bci_offset())));
1449   addptr(arg2_reg, Address(rbx, Method::const_offset()));
1450   lea(arg2_reg, Address(arg2_reg, ConstMethod::codes_offset()));
1451   cmpptr(arg2_reg, _bcp_register);
1452   jcc(Assembler::equal, verify_continue);
1453   // rbx: method
1454   // _bcp_register: bcp
1455   // c_rarg3: mdp
1456   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp),
1457                rbx, _bcp_register, arg3_reg);
1458   bind(verify_continue);
1459   pop(arg2_reg);
1460   pop(arg3_reg);
1461   pop(rbx);
1462   pop(rax);
1463 #endif // ASSERT
1464 }
1465 
1466 
1467 void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in,
1468                                                 int constant,
1469                                                 Register value) {
1470   assert(ProfileInterpreter, "must be profiling interpreter");
1471   Address data(mdp_in, constant);
1472   movptr(data, value);
1473 }
1474 
1475 
1476 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1477                                                       int constant,
1478                                                       bool decrement) {
1479   // Counter address
1480   Address data(mdp_in, constant);
1481 
1482   increment_mdp_data_at(data, decrement);
1483 }
1484 
1485 void InterpreterMacroAssembler::increment_mdp_data_at(Address data,
1486                                                       bool decrement) {
1487   assert(ProfileInterpreter, "must be profiling interpreter");
1488   // %%% this does 64bit counters at best it is wasting space
1489   // at worst it is a rare bug when counters overflow
1490 
1491   if (decrement) {
1492     // Decrement the register.  Set condition codes.
1493     addptr(data, -DataLayout::counter_increment);
1494     // If the decrement causes the counter to overflow, stay negative
1495     Label L;
1496     jcc(Assembler::negative, L);
1497     addptr(data, DataLayout::counter_increment);
1498     bind(L);
1499   } else {
1500     assert(DataLayout::counter_increment == 1,
1501            "flow-free idiom only works with 1");
1502     // Increment the register.  Set carry flag.
1503     addptr(data, DataLayout::counter_increment);
1504     // If the increment causes the counter to overflow, pull back by 1.
1505     sbbptr(data, 0);
1506   }
1507 }
1508 
1509 
1510 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1511                                                       Register reg,
1512                                                       int constant,
1513                                                       bool decrement) {
1514   Address data(mdp_in, reg, Address::times_1, constant);
1515 
1516   increment_mdp_data_at(data, decrement);
1517 }
1518 
1519 void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1520                                                 int flag_byte_constant) {
1521   assert(ProfileInterpreter, "must be profiling interpreter");
1522   int header_offset = in_bytes(DataLayout::flags_offset());
1523   int header_bits = flag_byte_constant;
1524   // Set the flag
1525   orb(Address(mdp_in, header_offset), header_bits);
1526 }
1527 
1528 
1529 
1530 void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1531                                                  int offset,
1532                                                  Register value,
1533                                                  Register test_value_out,
1534                                                  Label& not_equal_continue) {
1535   assert(ProfileInterpreter, "must be profiling interpreter");
1536   if (test_value_out == noreg) {
1537     cmpptr(value, Address(mdp_in, offset));
1538   } else {
1539     // Put the test value into a register, so caller can use it:
1540     movptr(test_value_out, Address(mdp_in, offset));
1541     cmpptr(test_value_out, value);
1542   }
1543   jcc(Assembler::notEqual, not_equal_continue);
1544 }
1545 
1546 
1547 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1548                                                      int offset_of_disp) {
1549   assert(ProfileInterpreter, "must be profiling interpreter");
1550   Address disp_address(mdp_in, offset_of_disp);
1551   addptr(mdp_in, disp_address);
1552   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1553 }
1554 
1555 
1556 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1557                                                      Register reg,
1558                                                      int offset_of_disp) {
1559   assert(ProfileInterpreter, "must be profiling interpreter");
1560   Address disp_address(mdp_in, reg, Address::times_1, offset_of_disp);
1561   addptr(mdp_in, disp_address);
1562   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1563 }
1564 
1565 
1566 void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in,
1567                                                        int constant) {
1568   assert(ProfileInterpreter, "must be profiling interpreter");
1569   addptr(mdp_in, constant);
1570   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1571 }
1572 
1573 
1574 void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1575   assert(ProfileInterpreter, "must be profiling interpreter");
1576   push(return_bci); // save/restore across call_VM
1577   call_VM(noreg,
1578           CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1579           return_bci);
1580   pop(return_bci);
1581 }
1582 
1583 
1584 void InterpreterMacroAssembler::profile_taken_branch(Register mdp,
1585                                                      Register bumped_count) {
1586   if (ProfileInterpreter) {
1587     Label profile_continue;
1588 
1589     // If no method data exists, go to profile_continue.
1590     // Otherwise, assign to mdp
1591     test_method_data_pointer(mdp, profile_continue);
1592 
1593     // We are taking a branch.  Increment the taken count.
1594     // We inline increment_mdp_data_at to return bumped_count in a register
1595     //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset()));
1596     Address data(mdp, in_bytes(JumpData::taken_offset()));
1597     movptr(bumped_count, data);
1598     assert(DataLayout::counter_increment == 1,
1599             "flow-free idiom only works with 1");
1600     addptr(bumped_count, DataLayout::counter_increment);
1601     sbbptr(bumped_count, 0);
1602     movptr(data, bumped_count); // Store back out
1603 
1604     // The method data pointer needs to be updated to reflect the new target.
1605     update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1606     bind(profile_continue);
1607   }
1608 }
1609 
1610 
1611 void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) {
1612   if (ProfileInterpreter) {
1613     Label profile_continue;
1614 
1615     // If no method data exists, go to profile_continue.
1616     test_method_data_pointer(mdp, profile_continue);
1617 
1618     // We are taking a branch.  Increment the not taken count.
1619     increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()));
1620 
1621     // The method data pointer needs to be updated to correspond to
1622     // the next bytecode
1623     update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size()));
1624     bind(profile_continue);
1625   }
1626 }
1627 
1628 void InterpreterMacroAssembler::profile_call(Register mdp) {
1629   if (ProfileInterpreter) {
1630     Label profile_continue;
1631 
1632     // If no method data exists, go to profile_continue.
1633     test_method_data_pointer(mdp, profile_continue);
1634 
1635     // We are making a call.  Increment the count.
1636     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1637 
1638     // The method data pointer needs to be updated to reflect the new target.
1639     update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1640     bind(profile_continue);
1641   }
1642 }
1643 
1644 
1645 void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1646   if (ProfileInterpreter) {
1647     Label profile_continue;
1648 
1649     // If no method data exists, go to profile_continue.
1650     test_method_data_pointer(mdp, profile_continue);
1651 
1652     // We are making a call.  Increment the count.
1653     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1654 
1655     // The method data pointer needs to be updated to reflect the new target.
1656     update_mdp_by_constant(mdp,
1657                            in_bytes(VirtualCallData::
1658                                     virtual_call_data_size()));
1659     bind(profile_continue);
1660   }
1661 }
1662 
1663 
1664 void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1665                                                      Register mdp,
1666                                                      Register reg2,
1667                                                      bool receiver_can_be_null) {
1668   if (ProfileInterpreter) {
1669     Label profile_continue;
1670 
1671     // If no method data exists, go to profile_continue.
1672     test_method_data_pointer(mdp, profile_continue);
1673 
1674     Label skip_receiver_profile;
1675     if (receiver_can_be_null) {
1676       Label not_null;
1677       testptr(receiver, receiver);
1678       jccb(Assembler::notZero, not_null);
1679       // We are making a call.  Increment the count for null receiver.
1680       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1681       jmp(skip_receiver_profile);
1682       bind(not_null);
1683     }
1684 
1685     // Record the receiver type.
1686     record_klass_in_profile(receiver, mdp, reg2, true);
1687     bind(skip_receiver_profile);
1688 
1689     // The method data pointer needs to be updated to reflect the new target.
1690     update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1691     bind(profile_continue);
1692   }
1693 }
1694 
1695 // This routine creates a state machine for updating the multi-row
1696 // type profile at a virtual call site (or other type-sensitive bytecode).
1697 // The machine visits each row (of receiver/count) until the receiver type
1698 // is found, or until it runs out of rows.  At the same time, it remembers
1699 // the location of the first empty row.  (An empty row records null for its
1700 // receiver, and can be allocated for a newly-observed receiver type.)
1701 // Because there are two degrees of freedom in the state, a simple linear
1702 // search will not work; it must be a decision tree.  Hence this helper
1703 // function is recursive, to generate the required tree structured code.
1704 // It's the interpreter, so we are trading off code space for speed.
1705 // See below for example code.
1706 void InterpreterMacroAssembler::record_klass_in_profile_helper(
1707                                         Register receiver, Register mdp,
1708                                         Register reg2, int start_row,
1709                                         Label& done, bool is_virtual_call) {
1710   if (TypeProfileWidth == 0) {
1711     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1712   } else {
1713     record_item_in_profile_helper(receiver, mdp, reg2, 0, done, TypeProfileWidth,
1714                                   &VirtualCallData::receiver_offset, &VirtualCallData::receiver_count_offset);
1715   }
1716 }
1717 
1718 void InterpreterMacroAssembler::record_item_in_profile_helper(Register item, Register mdp, Register reg2, int start_row,
1719                                                               Label& done, int total_rows,
1720                                                               OffsetFunction item_offset_fn,
1721                                                               OffsetFunction item_count_offset_fn) {
1722   int last_row = total_rows - 1;
1723   assert(start_row <= last_row, "must be work left to do");
1724   // Test this row for both the item and for null.
1725   // Take any of three different outcomes:
1726   //   1. found item => increment count and goto done
1727   //   2. found null => keep looking for case 1, maybe allocate this cell
1728   //   3. found something else => keep looking for cases 1 and 2
1729   // Case 3 is handled by a recursive call.
1730   for (int row = start_row; row <= last_row; row++) {
1731     Label next_test;
1732     bool test_for_null_also = (row == start_row);
1733 
1734     // See if the item is item[n].
1735     int item_offset = in_bytes(item_offset_fn(row));
1736     test_mdp_data_at(mdp, item_offset, item,
1737                      (test_for_null_also ? reg2 : noreg),
1738                      next_test);
1739     // (Reg2 now contains the item from the CallData.)
1740 
1741     // The item is item[n].  Increment count[n].
1742     int count_offset = in_bytes(item_count_offset_fn(row));
1743     increment_mdp_data_at(mdp, count_offset);
1744     jmp(done);
1745     bind(next_test);
1746 
1747     if (test_for_null_also) {
1748       // Failed the equality check on item[n]...  Test for null.
1749       testptr(reg2, reg2);
1750       if (start_row == last_row) {
1751         // The only thing left to do is handle the null case.
1752         Label found_null;
1753         jccb(Assembler::zero, found_null);
1754         // Item did not match any saved item and there is no empty row for it.
1755         // Increment total counter to indicate polymorphic case.
1756         increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1757         jmp(done);
1758         bind(found_null);
1759         break;
1760       }
1761       Label found_null;
1762       // Since null is rare, make it be the branch-taken case.
1763       jcc(Assembler::zero, found_null);
1764 
1765       // Put all the "Case 3" tests here.
1766       record_item_in_profile_helper(item, mdp, reg2, start_row + 1, done, total_rows,
1767                                     item_offset_fn, item_count_offset_fn);
1768 
1769       // Found a null.  Keep searching for a matching item,
1770       // but remember that this is an empty (unused) slot.
1771       bind(found_null);
1772     }
1773   }
1774 
1775   // In the fall-through case, we found no matching item, but we
1776   // observed the item[start_row] is null.
1777 
1778   // Fill in the item field and increment the count.
1779   int item_offset = in_bytes(item_offset_fn(start_row));
1780   set_mdp_data_at(mdp, item_offset, item);
1781   int count_offset = in_bytes(item_count_offset_fn(start_row));
1782   movl(reg2, DataLayout::counter_increment);
1783   set_mdp_data_at(mdp, count_offset, reg2);
1784   if (start_row > 0) {
1785     jmp(done);
1786   }
1787 }
1788 
1789 // Example state machine code for three profile rows:
1790 //   // main copy of decision tree, rooted at row[1]
1791 //   if (row[0].rec == rec) { row[0].incr(); goto done; }
1792 //   if (row[0].rec != nullptr) {
1793 //     // inner copy of decision tree, rooted at row[1]
1794 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1795 //     if (row[1].rec != nullptr) {
1796 //       // degenerate decision tree, rooted at row[2]
1797 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1798 //       if (row[2].rec != nullptr) { count.incr(); goto done; } // overflow
1799 //       row[2].init(rec); goto done;
1800 //     } else {
1801 //       // remember row[1] is empty
1802 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1803 //       row[1].init(rec); goto done;
1804 //     }
1805 //   } else {
1806 //     // remember row[0] is empty
1807 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1808 //     if (row[2].rec == rec) { row[2].incr(); goto done; }
1809 //     row[0].init(rec); goto done;
1810 //   }
1811 //   done:
1812 
1813 void InterpreterMacroAssembler::record_klass_in_profile(Register receiver,
1814                                                         Register mdp, Register reg2,
1815                                                         bool is_virtual_call) {
1816   assert(ProfileInterpreter, "must be profiling");
1817   Label done;
1818 
1819   record_klass_in_profile_helper(receiver, mdp, reg2, 0, done, is_virtual_call);
1820 
1821   bind (done);
1822 }
1823 
1824 void InterpreterMacroAssembler::profile_ret(Register return_bci,
1825                                             Register mdp) {
1826   if (ProfileInterpreter) {
1827     Label profile_continue;
1828     uint row;
1829 
1830     // If no method data exists, go to profile_continue.
1831     test_method_data_pointer(mdp, profile_continue);
1832 
1833     // Update the total ret count.
1834     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1835 
1836     for (row = 0; row < RetData::row_limit(); row++) {
1837       Label next_test;
1838 
1839       // See if return_bci is equal to bci[n]:
1840       test_mdp_data_at(mdp,
1841                        in_bytes(RetData::bci_offset(row)),
1842                        return_bci, noreg,
1843                        next_test);
1844 
1845       // return_bci is equal to bci[n].  Increment the count.
1846       increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1847 
1848       // The method data pointer needs to be updated to reflect the new target.
1849       update_mdp_by_offset(mdp,
1850                            in_bytes(RetData::bci_displacement_offset(row)));
1851       jmp(profile_continue);
1852       bind(next_test);
1853     }
1854 
1855     update_mdp_for_ret(return_bci);
1856 
1857     bind(profile_continue);
1858   }
1859 }
1860 
1861 
1862 void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1863   if (ProfileInterpreter) {
1864     Label profile_continue;
1865 
1866     // If no method data exists, go to profile_continue.
1867     test_method_data_pointer(mdp, profile_continue);
1868 
1869     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1870 
1871     // The method data pointer needs to be updated.
1872     int mdp_delta = in_bytes(BitData::bit_data_size());
1873     if (TypeProfileCasts) {
1874       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1875     }
1876     update_mdp_by_constant(mdp, mdp_delta);
1877 
1878     bind(profile_continue);
1879   }
1880 }
1881 
1882 
1883 void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1884   if (ProfileInterpreter) {
1885     Label profile_continue;
1886 
1887     // If no method data exists, go to profile_continue.
1888     test_method_data_pointer(mdp, profile_continue);
1889 
1890     // The method data pointer needs to be updated.
1891     int mdp_delta = in_bytes(BitData::bit_data_size());
1892     if (TypeProfileCasts) {
1893       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1894 
1895       // Record the object type.
1896       record_klass_in_profile(klass, mdp, reg2, false);
1897       NOT_LP64(assert(reg2 == rdi, "we know how to fix this blown reg");)
1898       NOT_LP64(restore_locals();)         // Restore EDI
1899     }
1900     update_mdp_by_constant(mdp, mdp_delta);
1901 
1902     bind(profile_continue);
1903   }
1904 }
1905 
1906 
1907 void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1908   if (ProfileInterpreter) {
1909     Label profile_continue;
1910 
1911     // If no method data exists, go to profile_continue.
1912     test_method_data_pointer(mdp, profile_continue);
1913 
1914     // Update the default case count
1915     increment_mdp_data_at(mdp,
1916                           in_bytes(MultiBranchData::default_count_offset()));
1917 
1918     // The method data pointer needs to be updated.
1919     update_mdp_by_offset(mdp,
1920                          in_bytes(MultiBranchData::
1921                                   default_displacement_offset()));
1922 
1923     bind(profile_continue);
1924   }
1925 }
1926 
1927 
1928 void InterpreterMacroAssembler::profile_switch_case(Register index,
1929                                                     Register mdp,
1930                                                     Register reg2) {
1931   if (ProfileInterpreter) {
1932     Label profile_continue;
1933 
1934     // If no method data exists, go to profile_continue.
1935     test_method_data_pointer(mdp, profile_continue);
1936 
1937     // Build the base (index * per_case_size_in_bytes()) +
1938     // case_array_offset_in_bytes()
1939     movl(reg2, in_bytes(MultiBranchData::per_case_size()));
1940     imulptr(index, reg2); // XXX l ?
1941     addptr(index, in_bytes(MultiBranchData::case_array_offset())); // XXX l ?
1942 
1943     // Update the case count
1944     increment_mdp_data_at(mdp,
1945                           index,
1946                           in_bytes(MultiBranchData::relative_count_offset()));
1947 
1948     // The method data pointer needs to be updated.
1949     update_mdp_by_offset(mdp,
1950                          index,
1951                          in_bytes(MultiBranchData::
1952                                   relative_displacement_offset()));
1953 
1954     bind(profile_continue);
1955   }
1956 }
1957 
1958 
1959 
1960 void InterpreterMacroAssembler::_interp_verify_oop(Register reg, TosState state, const char* file, int line) {
1961   if (state == atos) {
1962     MacroAssembler::_verify_oop_checked(reg, "broken oop", file, line);
1963   }
1964 }
1965 
1966 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
1967 #ifndef _LP64
1968   if ((state == ftos && UseSSE < 1) ||
1969       (state == dtos && UseSSE < 2)) {
1970     MacroAssembler::verify_FPU(stack_depth);
1971   }
1972 #endif
1973 }
1974 
1975 // Jump if ((*counter_addr += increment) & mask) == 0
1976 void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, Address mask,
1977                                                         Register scratch, Label* where) {
1978   // This update is actually not atomic and can lose a number of updates
1979   // under heavy contention, but the alternative of using the (contended)
1980   // atomic update here penalizes profiling paths too much.
1981   movl(scratch, counter_addr);
1982   incrementl(scratch, InvocationCounter::count_increment);
1983   movl(counter_addr, scratch);
1984   andl(scratch, mask);
1985   if (where != nullptr) {
1986     jcc(Assembler::zero, *where);
1987   }
1988 }
1989 
1990 void InterpreterMacroAssembler::notify_method_entry() {
1991   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
1992   // track stack depth.  If it is possible to enter interp_only_mode we add
1993   // the code to check if the event should be sent.
1994   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1995   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
1996   if (JvmtiExport::can_post_interpreter_events()) {
1997     Label L;
1998     NOT_LP64(get_thread(rthread);)
1999     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2000     testl(rdx, rdx);
2001     jcc(Assembler::zero, L);
2002     call_VM(noreg, CAST_FROM_FN_PTR(address,
2003                                     InterpreterRuntime::post_method_entry));
2004     bind(L);
2005   }
2006 
2007   if (DTraceMethodProbes) {
2008     NOT_LP64(get_thread(rthread);)
2009     get_method(rarg);
2010     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2011                  rthread, rarg);
2012   }
2013 
2014   // RedefineClasses() tracing support for obsolete method entry
2015   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2016     NOT_LP64(get_thread(rthread);)
2017     get_method(rarg);
2018     call_VM_leaf(
2019       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2020       rthread, rarg);
2021   }
2022 }
2023 
2024 
2025 void InterpreterMacroAssembler::notify_method_exit(
2026     TosState state, NotifyMethodExitMode mode) {
2027   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
2028   // track stack depth.  If it is possible to enter interp_only_mode we add
2029   // the code to check if the event should be sent.
2030   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
2031   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
2032   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2033     Label L;
2034     // Note: frame::interpreter_frame_result has a dependency on how the
2035     // method result is saved across the call to post_method_exit. If this
2036     // is changed then the interpreter_frame_result implementation will
2037     // need to be updated too.
2038 
2039     // template interpreter will leave the result on the top of the stack.
2040     push(state);
2041     NOT_LP64(get_thread(rthread);)
2042     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2043     testl(rdx, rdx);
2044     jcc(Assembler::zero, L);
2045     call_VM(noreg,
2046             CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit));
2047     bind(L);
2048     pop(state);
2049   }
2050 
2051   if (DTraceMethodProbes) {
2052     push(state);
2053     NOT_LP64(get_thread(rthread);)
2054     get_method(rarg);
2055     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2056                  rthread, rarg);
2057     pop(state);
2058   }
2059 }
2060 
2061 void InterpreterMacroAssembler::load_resolved_indy_entry(Register cache, Register index) {
2062   // Get index out of bytecode pointer
2063   get_cache_index_at_bcp(index, 1, sizeof(u4));
2064   // Get address of invokedynamic array
2065   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2066   movptr(cache, Address(cache, in_bytes(ConstantPoolCache::invokedynamic_entries_offset())));
2067   if (is_power_of_2(sizeof(ResolvedIndyEntry))) {
2068     shll(index, log2i_exact(sizeof(ResolvedIndyEntry))); // Scale index by power of 2
2069   } else {
2070     imull(index, index, sizeof(ResolvedIndyEntry)); // Scale the index to be the entry index * sizeof(ResolvedIndyEntry)
2071   }
2072   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedIndyEntry>::base_offset_in_bytes()));
2073 }
2074 
2075 void InterpreterMacroAssembler::load_field_entry(Register cache, Register index, int bcp_offset) {
2076   // Get index out of bytecode pointer
2077   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2078   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2079 
2080   movptr(cache, Address(cache, ConstantPoolCache::field_entries_offset()));
2081   // Take shortcut if the size is a power of 2
2082   if (is_power_of_2(sizeof(ResolvedFieldEntry))) {
2083     shll(index, log2i_exact(sizeof(ResolvedFieldEntry))); // Scale index by power of 2
2084   } else {
2085     imull(index, index, sizeof(ResolvedFieldEntry)); // Scale the index to be the entry index * sizeof(ResolvedFieldEntry)
2086   }
2087   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedFieldEntry>::base_offset_in_bytes()));
2088 }
2089 
2090 void InterpreterMacroAssembler::load_method_entry(Register cache, Register index, int bcp_offset) {
2091   // Get index out of bytecode pointer
2092   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2093   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2094 
2095   movptr(cache, Address(cache, ConstantPoolCache::method_entries_offset()));
2096   imull(index, index, sizeof(ResolvedMethodEntry)); // Scale the index to be the entry index * sizeof(ResolvedMethodEntry)
2097   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedMethodEntry>::base_offset_in_bytes()));
2098 }