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