1 /*
   2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "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       // Load object header, prepare for CAS from unlocked to locked.
1256       movptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1257       lightweight_lock(obj_reg, swap_reg, thread, tmp_reg, slow_case);
1258     } else if (LockingMode == LM_LEGACY) {
1259       // Load immediate 1 into swap_reg %rax
1260       movl(swap_reg, 1);
1261 
1262       // Load (object->mark() | 1) into swap_reg %rax
1263       orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1264 
1265       // Save (object->mark() | 1) into BasicLock's displaced header
1266       movptr(Address(lock_reg, mark_offset), swap_reg);
1267 
1268       assert(lock_offset == 0,
1269              "displaced header must be first word in BasicObjectLock");
1270 
1271       lock();
1272       cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1273       jcc(Assembler::zero, count_locking);
1274 
1275       const int zero_bits = LP64_ONLY(7) NOT_LP64(3);
1276 
1277       // Fast check for recursive lock.
1278       //
1279       // Can apply the optimization only if this is a stack lock
1280       // allocated in this thread. For efficiency, we can focus on
1281       // recently allocated stack locks (instead of reading the stack
1282       // base and checking whether 'mark' points inside the current
1283       // thread stack):
1284       //  1) (mark & zero_bits) == 0, and
1285       //  2) rsp <= mark < mark + os::pagesize()
1286       //
1287       // Warning: rsp + os::pagesize can overflow the stack base. We must
1288       // neither apply the optimization for an inflated lock allocated
1289       // just above the thread stack (this is why condition 1 matters)
1290       // nor apply the optimization if the stack lock is inside the stack
1291       // of another thread. The latter is avoided even in case of overflow
1292       // because we have guard pages at the end of all stacks. Hence, if
1293       // we go over the stack base and hit the stack of another thread,
1294       // this should not be in a writeable area that could contain a
1295       // stack lock allocated by that thread. As a consequence, a stack
1296       // lock less than page size away from rsp is guaranteed to be
1297       // owned by the current thread.
1298       //
1299       // These 3 tests can be done by evaluating the following
1300       // expression: ((mark - rsp) & (zero_bits - os::vm_page_size())),
1301       // assuming both stack pointer and pagesize have their
1302       // least significant bits clear.
1303       // NOTE: the mark is in swap_reg %rax as the result of cmpxchg
1304       subptr(swap_reg, rsp);
1305       andptr(swap_reg, zero_bits - (int)os::vm_page_size());
1306 
1307       // Save the test result, for recursive case, the result is zero
1308       movptr(Address(lock_reg, mark_offset), swap_reg);
1309       jcc(Assembler::notZero, slow_case);
1310 
1311       bind(count_locking);
1312     }
1313     inc_held_monitor_count();
1314     jmp(done);
1315 
1316     bind(slow_case);
1317 
1318     // Call the runtime routine for slow case
1319     if (LockingMode == LM_LIGHTWEIGHT) {
1320       call_VM(noreg,
1321               CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter_obj),
1322               obj_reg);
1323     } else {
1324       call_VM(noreg,
1325               CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1326               lock_reg);
1327     }
1328     bind(done);
1329   }
1330 }
1331 
1332 
1333 // Unlocks an object. Used in monitorexit bytecode and
1334 // remove_activation.  Throws an IllegalMonitorException if object is
1335 // not locked by current thread.
1336 //
1337 // Args:
1338 //      rdx, c_rarg1: BasicObjectLock for lock
1339 //
1340 // Kills:
1341 //      rax
1342 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ... (param regs)
1343 //      rscratch1 (scratch reg)
1344 // rax, rbx, rcx, rdx
1345 void InterpreterMacroAssembler::unlock_object(Register lock_reg) {
1346   assert(lock_reg == LP64_ONLY(c_rarg1) NOT_LP64(rdx),
1347          "The argument is only for looks. It must be c_rarg1");
1348 
1349   if (LockingMode == LM_MONITOR) {
1350     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1351   } else {
1352     Label count_locking, done, slow_case;
1353 
1354     const Register swap_reg   = rax;  // Must use rax for cmpxchg instruction
1355     const Register header_reg = LP64_ONLY(c_rarg2) NOT_LP64(rbx);  // Will contain the old oopMark
1356     const Register obj_reg    = LP64_ONLY(c_rarg3) NOT_LP64(rcx);  // Will contain the oop
1357 
1358     save_bcp(); // Save in case of exception
1359 
1360     if (LockingMode != LM_LIGHTWEIGHT) {
1361       // Convert from BasicObjectLock structure to object and BasicLock
1362       // structure Store the BasicLock address into %rax
1363       lea(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset()));
1364     }
1365 
1366     // Load oop into obj_reg(%c_rarg3)
1367     movptr(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset()));
1368 
1369     // Free entry
1370     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), NULL_WORD);
1371 
1372     if (LockingMode == LM_LIGHTWEIGHT) {
1373 #ifdef _LP64
1374       const Register thread = r15_thread;
1375 #else
1376       const Register thread = header_reg;
1377       get_thread(thread);
1378 #endif
1379       // Handle unstructured locking.
1380       Register tmp = swap_reg;
1381       movl(tmp, Address(thread, JavaThread::lock_stack_top_offset()));
1382       cmpptr(obj_reg, Address(thread, tmp, Address::times_1,  -oopSize));
1383       jcc(Assembler::notEqual, slow_case);
1384       // Try to swing header from locked to unlocked.
1385       movptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1386       andptr(swap_reg, ~(int32_t)markWord::lock_mask_in_place);
1387       lightweight_unlock(obj_reg, swap_reg, header_reg, slow_case);
1388     } else if (LockingMode == LM_LEGACY) {
1389       // Load the old header from BasicLock structure
1390       movptr(header_reg, Address(swap_reg,
1391                                  BasicLock::displaced_header_offset_in_bytes()));
1392 
1393       // Test for recursion
1394       testptr(header_reg, header_reg);
1395 
1396       // zero for recursive case
1397       jcc(Assembler::zero, count_locking);
1398 
1399       // Atomic swap back the old header
1400       lock();
1401       cmpxchgptr(header_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1402 
1403       // zero for simple unlock of a stack-lock case
1404       jcc(Assembler::notZero, slow_case);
1405 
1406       bind(count_locking);
1407     }
1408     dec_held_monitor_count();
1409     jmp(done);
1410 
1411     bind(slow_case);
1412     // Call the runtime routine for slow case.
1413     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), obj_reg); // restore obj
1414     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1415 
1416     bind(done);
1417 
1418     restore_bcp();
1419   }
1420 }
1421 
1422 void InterpreterMacroAssembler::test_method_data_pointer(Register mdp,
1423                                                          Label& zero_continue) {
1424   assert(ProfileInterpreter, "must be profiling interpreter");
1425   movptr(mdp, Address(rbp, frame::interpreter_frame_mdp_offset * wordSize));
1426   testptr(mdp, mdp);
1427   jcc(Assembler::zero, zero_continue);
1428 }
1429 
1430 
1431 // Set the method data pointer for the current bcp.
1432 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1433   assert(ProfileInterpreter, "must be profiling interpreter");
1434   Label set_mdp;
1435   push(rax);
1436   push(rbx);
1437 
1438   get_method(rbx);
1439   // Test MDO to avoid the call if it is null.
1440   movptr(rax, Address(rbx, in_bytes(Method::method_data_offset())));
1441   testptr(rax, rax);
1442   jcc(Assembler::zero, set_mdp);
1443   // rbx: method
1444   // _bcp_register: bcp
1445   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), rbx, _bcp_register);
1446   // rax: mdi
1447   // mdo is guaranteed to be non-zero here, we checked for it before the call.
1448   movptr(rbx, Address(rbx, in_bytes(Method::method_data_offset())));
1449   addptr(rbx, in_bytes(MethodData::data_offset()));
1450   addptr(rax, rbx);
1451   bind(set_mdp);
1452   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), rax);
1453   pop(rbx);
1454   pop(rax);
1455 }
1456 
1457 void InterpreterMacroAssembler::verify_method_data_pointer() {
1458   assert(ProfileInterpreter, "must be profiling interpreter");
1459 #ifdef ASSERT
1460   Label verify_continue;
1461   push(rax);
1462   push(rbx);
1463   Register arg3_reg = LP64_ONLY(c_rarg3) NOT_LP64(rcx);
1464   Register arg2_reg = LP64_ONLY(c_rarg2) NOT_LP64(rdx);
1465   push(arg3_reg);
1466   push(arg2_reg);
1467   test_method_data_pointer(arg3_reg, verify_continue); // If mdp is zero, continue
1468   get_method(rbx);
1469 
1470   // If the mdp is valid, it will point to a DataLayout header which is
1471   // consistent with the bcp.  The converse is highly probable also.
1472   load_unsigned_short(arg2_reg,
1473                       Address(arg3_reg, in_bytes(DataLayout::bci_offset())));
1474   addptr(arg2_reg, Address(rbx, Method::const_offset()));
1475   lea(arg2_reg, Address(arg2_reg, ConstMethod::codes_offset()));
1476   cmpptr(arg2_reg, _bcp_register);
1477   jcc(Assembler::equal, verify_continue);
1478   // rbx: method
1479   // _bcp_register: bcp
1480   // c_rarg3: mdp
1481   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp),
1482                rbx, _bcp_register, arg3_reg);
1483   bind(verify_continue);
1484   pop(arg2_reg);
1485   pop(arg3_reg);
1486   pop(rbx);
1487   pop(rax);
1488 #endif // ASSERT
1489 }
1490 
1491 
1492 void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in,
1493                                                 int constant,
1494                                                 Register value) {
1495   assert(ProfileInterpreter, "must be profiling interpreter");
1496   Address data(mdp_in, constant);
1497   movptr(data, value);
1498 }
1499 
1500 
1501 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1502                                                       int constant,
1503                                                       bool decrement) {
1504   // Counter address
1505   Address data(mdp_in, constant);
1506 
1507   increment_mdp_data_at(data, decrement);
1508 }
1509 
1510 void InterpreterMacroAssembler::increment_mdp_data_at(Address data,
1511                                                       bool decrement) {
1512   assert(ProfileInterpreter, "must be profiling interpreter");
1513   // %%% this does 64bit counters at best it is wasting space
1514   // at worst it is a rare bug when counters overflow
1515 
1516   if (decrement) {
1517     // Decrement the register.  Set condition codes.
1518     addptr(data, -DataLayout::counter_increment);
1519     // If the decrement causes the counter to overflow, stay negative
1520     Label L;
1521     jcc(Assembler::negative, L);
1522     addptr(data, DataLayout::counter_increment);
1523     bind(L);
1524   } else {
1525     assert(DataLayout::counter_increment == 1,
1526            "flow-free idiom only works with 1");
1527     // Increment the register.  Set carry flag.
1528     addptr(data, DataLayout::counter_increment);
1529     // If the increment causes the counter to overflow, pull back by 1.
1530     sbbptr(data, 0);
1531   }
1532 }
1533 
1534 
1535 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1536                                                       Register reg,
1537                                                       int constant,
1538                                                       bool decrement) {
1539   Address data(mdp_in, reg, Address::times_1, constant);
1540 
1541   increment_mdp_data_at(data, decrement);
1542 }
1543 
1544 void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1545                                                 int flag_byte_constant) {
1546   assert(ProfileInterpreter, "must be profiling interpreter");
1547   int header_offset = in_bytes(DataLayout::flags_offset());
1548   int header_bits = flag_byte_constant;
1549   // Set the flag
1550   orb(Address(mdp_in, header_offset), header_bits);
1551 }
1552 
1553 
1554 
1555 void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1556                                                  int offset,
1557                                                  Register value,
1558                                                  Register test_value_out,
1559                                                  Label& not_equal_continue) {
1560   assert(ProfileInterpreter, "must be profiling interpreter");
1561   if (test_value_out == noreg) {
1562     cmpptr(value, Address(mdp_in, offset));
1563   } else {
1564     // Put the test value into a register, so caller can use it:
1565     movptr(test_value_out, Address(mdp_in, offset));
1566     cmpptr(test_value_out, value);
1567   }
1568   jcc(Assembler::notEqual, not_equal_continue);
1569 }
1570 
1571 
1572 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1573                                                      int offset_of_disp) {
1574   assert(ProfileInterpreter, "must be profiling interpreter");
1575   Address disp_address(mdp_in, offset_of_disp);
1576   addptr(mdp_in, disp_address);
1577   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1578 }
1579 
1580 
1581 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1582                                                      Register reg,
1583                                                      int offset_of_disp) {
1584   assert(ProfileInterpreter, "must be profiling interpreter");
1585   Address disp_address(mdp_in, reg, Address::times_1, offset_of_disp);
1586   addptr(mdp_in, disp_address);
1587   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1588 }
1589 
1590 
1591 void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in,
1592                                                        int constant) {
1593   assert(ProfileInterpreter, "must be profiling interpreter");
1594   addptr(mdp_in, constant);
1595   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1596 }
1597 
1598 
1599 void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1600   assert(ProfileInterpreter, "must be profiling interpreter");
1601   push(return_bci); // save/restore across call_VM
1602   call_VM(noreg,
1603           CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1604           return_bci);
1605   pop(return_bci);
1606 }
1607 
1608 
1609 void InterpreterMacroAssembler::profile_taken_branch(Register mdp,
1610                                                      Register bumped_count) {
1611   if (ProfileInterpreter) {
1612     Label profile_continue;
1613 
1614     // If no method data exists, go to profile_continue.
1615     // Otherwise, assign to mdp
1616     test_method_data_pointer(mdp, profile_continue);
1617 
1618     // We are taking a branch.  Increment the taken count.
1619     // We inline increment_mdp_data_at to return bumped_count in a register
1620     //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset()));
1621     Address data(mdp, in_bytes(JumpData::taken_offset()));
1622     movptr(bumped_count, data);
1623     assert(DataLayout::counter_increment == 1,
1624             "flow-free idiom only works with 1");
1625     addptr(bumped_count, DataLayout::counter_increment);
1626     sbbptr(bumped_count, 0);
1627     movptr(data, bumped_count); // Store back out
1628 
1629     // The method data pointer needs to be updated to reflect the new target.
1630     update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1631     bind(profile_continue);
1632   }
1633 }
1634 
1635 
1636 void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) {
1637   if (ProfileInterpreter) {
1638     Label profile_continue;
1639 
1640     // If no method data exists, go to profile_continue.
1641     test_method_data_pointer(mdp, profile_continue);
1642 
1643     // We are taking a branch.  Increment the not taken count.
1644     increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()));
1645 
1646     // The method data pointer needs to be updated to correspond to
1647     // the next bytecode
1648     update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size()));
1649     bind(profile_continue);
1650   }
1651 }
1652 
1653 void InterpreterMacroAssembler::profile_call(Register mdp) {
1654   if (ProfileInterpreter) {
1655     Label profile_continue;
1656 
1657     // If no method data exists, go to profile_continue.
1658     test_method_data_pointer(mdp, profile_continue);
1659 
1660     // We are making a call.  Increment the count.
1661     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1662 
1663     // The method data pointer needs to be updated to reflect the new target.
1664     update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1665     bind(profile_continue);
1666   }
1667 }
1668 
1669 
1670 void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1671   if (ProfileInterpreter) {
1672     Label profile_continue;
1673 
1674     // If no method data exists, go to profile_continue.
1675     test_method_data_pointer(mdp, profile_continue);
1676 
1677     // We are making a call.  Increment the count.
1678     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1679 
1680     // The method data pointer needs to be updated to reflect the new target.
1681     update_mdp_by_constant(mdp,
1682                            in_bytes(VirtualCallData::
1683                                     virtual_call_data_size()));
1684     bind(profile_continue);
1685   }
1686 }
1687 
1688 
1689 void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1690                                                      Register mdp,
1691                                                      Register reg2,
1692                                                      bool receiver_can_be_null) {
1693   if (ProfileInterpreter) {
1694     Label profile_continue;
1695 
1696     // If no method data exists, go to profile_continue.
1697     test_method_data_pointer(mdp, profile_continue);
1698 
1699     Label skip_receiver_profile;
1700     if (receiver_can_be_null) {
1701       Label not_null;
1702       testptr(receiver, receiver);
1703       jccb(Assembler::notZero, not_null);
1704       // We are making a call.  Increment the count for null receiver.
1705       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1706       jmp(skip_receiver_profile);
1707       bind(not_null);
1708     }
1709 
1710     // Record the receiver type.
1711     record_klass_in_profile(receiver, mdp, reg2, true);
1712     bind(skip_receiver_profile);
1713 
1714     // The method data pointer needs to be updated to reflect the new target.
1715     update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1716     bind(profile_continue);
1717   }
1718 }
1719 
1720 // This routine creates a state machine for updating the multi-row
1721 // type profile at a virtual call site (or other type-sensitive bytecode).
1722 // The machine visits each row (of receiver/count) until the receiver type
1723 // is found, or until it runs out of rows.  At the same time, it remembers
1724 // the location of the first empty row.  (An empty row records null for its
1725 // receiver, and can be allocated for a newly-observed receiver type.)
1726 // Because there are two degrees of freedom in the state, a simple linear
1727 // search will not work; it must be a decision tree.  Hence this helper
1728 // function is recursive, to generate the required tree structured code.
1729 // It's the interpreter, so we are trading off code space for speed.
1730 // See below for example code.
1731 void InterpreterMacroAssembler::record_klass_in_profile_helper(
1732                                         Register receiver, Register mdp,
1733                                         Register reg2, int start_row,
1734                                         Label& done, bool is_virtual_call) {
1735   if (TypeProfileWidth == 0) {
1736     if (is_virtual_call) {
1737       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1738     }
1739 #if INCLUDE_JVMCI
1740     else if (EnableJVMCI) {
1741       increment_mdp_data_at(mdp, in_bytes(ReceiverTypeData::nonprofiled_receiver_count_offset()));
1742     }
1743 #endif // INCLUDE_JVMCI
1744   } else {
1745     int non_profiled_offset = -1;
1746     if (is_virtual_call) {
1747       non_profiled_offset = in_bytes(CounterData::count_offset());
1748     }
1749 #if INCLUDE_JVMCI
1750     else if (EnableJVMCI) {
1751       non_profiled_offset = in_bytes(ReceiverTypeData::nonprofiled_receiver_count_offset());
1752     }
1753 #endif // INCLUDE_JVMCI
1754 
1755     record_item_in_profile_helper(receiver, mdp, reg2, 0, done, TypeProfileWidth,
1756         &VirtualCallData::receiver_offset, &VirtualCallData::receiver_count_offset, non_profiled_offset);
1757   }
1758 }
1759 
1760 void InterpreterMacroAssembler::record_item_in_profile_helper(Register item, Register mdp,
1761                                         Register reg2, int start_row, Label& done, int total_rows,
1762                                         OffsetFunction item_offset_fn, OffsetFunction item_count_offset_fn,
1763                                         int non_profiled_offset) {
1764   int last_row = total_rows - 1;
1765   assert(start_row <= last_row, "must be work left to do");
1766   // Test this row for both the item and for null.
1767   // Take any of three different outcomes:
1768   //   1. found item => increment count and goto done
1769   //   2. found null => keep looking for case 1, maybe allocate this cell
1770   //   3. found something else => keep looking for cases 1 and 2
1771   // Case 3 is handled by a recursive call.
1772   for (int row = start_row; row <= last_row; row++) {
1773     Label next_test;
1774     bool test_for_null_also = (row == start_row);
1775 
1776     // See if the item is item[n].
1777     int item_offset = in_bytes(item_offset_fn(row));
1778     test_mdp_data_at(mdp, item_offset, item,
1779                      (test_for_null_also ? reg2 : noreg),
1780                      next_test);
1781     // (Reg2 now contains the item from the CallData.)
1782 
1783     // The item is item[n].  Increment count[n].
1784     int count_offset = in_bytes(item_count_offset_fn(row));
1785     increment_mdp_data_at(mdp, count_offset);
1786     jmp(done);
1787     bind(next_test);
1788 
1789     if (test_for_null_also) {
1790       // Failed the equality check on item[n]...  Test for null.
1791       testptr(reg2, reg2);
1792       if (start_row == last_row) {
1793         // The only thing left to do is handle the null case.
1794         if (non_profiled_offset >= 0) {
1795           Label found_null;
1796           jccb(Assembler::zero, found_null);
1797           // Item did not match any saved item and there is no empty row for it.
1798           // Increment total counter to indicate polymorphic case.
1799           increment_mdp_data_at(mdp, non_profiled_offset);
1800           jmp(done);
1801           bind(found_null);
1802         } else {
1803           jcc(Assembler::notZero, done);
1804         }
1805         break;
1806       }
1807       Label found_null;
1808       // Since null is rare, make it be the branch-taken case.
1809       jcc(Assembler::zero, found_null);
1810 
1811       // Put all the "Case 3" tests here.
1812       record_item_in_profile_helper(item, mdp, reg2, start_row + 1, done, total_rows,
1813         item_offset_fn, item_count_offset_fn, non_profiled_offset);
1814 
1815       // Found a null.  Keep searching for a matching item,
1816       // but remember that this is an empty (unused) slot.
1817       bind(found_null);
1818     }
1819   }
1820 
1821   // In the fall-through case, we found no matching item, but we
1822   // observed the item[start_row] is null.
1823 
1824   // Fill in the item field and increment the count.
1825   int item_offset = in_bytes(item_offset_fn(start_row));
1826   set_mdp_data_at(mdp, item_offset, item);
1827   int count_offset = in_bytes(item_count_offset_fn(start_row));
1828   movl(reg2, DataLayout::counter_increment);
1829   set_mdp_data_at(mdp, count_offset, reg2);
1830   if (start_row > 0) {
1831     jmp(done);
1832   }
1833 }
1834 
1835 // Example state machine code for three profile rows:
1836 //   // main copy of decision tree, rooted at row[1]
1837 //   if (row[0].rec == rec) { row[0].incr(); goto done; }
1838 //   if (row[0].rec != nullptr) {
1839 //     // inner copy of decision tree, rooted at row[1]
1840 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1841 //     if (row[1].rec != nullptr) {
1842 //       // degenerate decision tree, rooted at row[2]
1843 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1844 //       if (row[2].rec != nullptr) { count.incr(); goto done; } // overflow
1845 //       row[2].init(rec); goto done;
1846 //     } else {
1847 //       // remember row[1] is empty
1848 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1849 //       row[1].init(rec); goto done;
1850 //     }
1851 //   } else {
1852 //     // remember row[0] is empty
1853 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1854 //     if (row[2].rec == rec) { row[2].incr(); goto done; }
1855 //     row[0].init(rec); goto done;
1856 //   }
1857 //   done:
1858 
1859 void InterpreterMacroAssembler::record_klass_in_profile(Register receiver,
1860                                                         Register mdp, Register reg2,
1861                                                         bool is_virtual_call) {
1862   assert(ProfileInterpreter, "must be profiling");
1863   Label done;
1864 
1865   record_klass_in_profile_helper(receiver, mdp, reg2, 0, done, is_virtual_call);
1866 
1867   bind (done);
1868 }
1869 
1870 void InterpreterMacroAssembler::profile_ret(Register return_bci,
1871                                             Register mdp) {
1872   if (ProfileInterpreter) {
1873     Label profile_continue;
1874     uint row;
1875 
1876     // If no method data exists, go to profile_continue.
1877     test_method_data_pointer(mdp, profile_continue);
1878 
1879     // Update the total ret count.
1880     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1881 
1882     for (row = 0; row < RetData::row_limit(); row++) {
1883       Label next_test;
1884 
1885       // See if return_bci is equal to bci[n]:
1886       test_mdp_data_at(mdp,
1887                        in_bytes(RetData::bci_offset(row)),
1888                        return_bci, noreg,
1889                        next_test);
1890 
1891       // return_bci is equal to bci[n].  Increment the count.
1892       increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1893 
1894       // The method data pointer needs to be updated to reflect the new target.
1895       update_mdp_by_offset(mdp,
1896                            in_bytes(RetData::bci_displacement_offset(row)));
1897       jmp(profile_continue);
1898       bind(next_test);
1899     }
1900 
1901     update_mdp_for_ret(return_bci);
1902 
1903     bind(profile_continue);
1904   }
1905 }
1906 
1907 
1908 void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1909   if (ProfileInterpreter) {
1910     Label profile_continue;
1911 
1912     // If no method data exists, go to profile_continue.
1913     test_method_data_pointer(mdp, profile_continue);
1914 
1915     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1916 
1917     // The method data pointer needs to be updated.
1918     int mdp_delta = in_bytes(BitData::bit_data_size());
1919     if (TypeProfileCasts) {
1920       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1921     }
1922     update_mdp_by_constant(mdp, mdp_delta);
1923 
1924     bind(profile_continue);
1925   }
1926 }
1927 
1928 
1929 void InterpreterMacroAssembler::profile_typecheck_failed(Register mdp) {
1930   if (ProfileInterpreter && TypeProfileCasts) {
1931     Label profile_continue;
1932 
1933     // If no method data exists, go to profile_continue.
1934     test_method_data_pointer(mdp, profile_continue);
1935 
1936     int count_offset = in_bytes(CounterData::count_offset());
1937     // Back up the address, since we have already bumped the mdp.
1938     count_offset -= in_bytes(VirtualCallData::virtual_call_data_size());
1939 
1940     // *Decrement* the counter.  We expect to see zero or small negatives.
1941     increment_mdp_data_at(mdp, count_offset, true);
1942 
1943     bind (profile_continue);
1944   }
1945 }
1946 
1947 
1948 void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1949   if (ProfileInterpreter) {
1950     Label profile_continue;
1951 
1952     // If no method data exists, go to profile_continue.
1953     test_method_data_pointer(mdp, profile_continue);
1954 
1955     // The method data pointer needs to be updated.
1956     int mdp_delta = in_bytes(BitData::bit_data_size());
1957     if (TypeProfileCasts) {
1958       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1959 
1960       // Record the object type.
1961       record_klass_in_profile(klass, mdp, reg2, false);
1962       NOT_LP64(assert(reg2 == rdi, "we know how to fix this blown reg");)
1963       NOT_LP64(restore_locals();)         // Restore EDI
1964     }
1965     update_mdp_by_constant(mdp, mdp_delta);
1966 
1967     bind(profile_continue);
1968   }
1969 }
1970 
1971 
1972 void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1973   if (ProfileInterpreter) {
1974     Label profile_continue;
1975 
1976     // If no method data exists, go to profile_continue.
1977     test_method_data_pointer(mdp, profile_continue);
1978 
1979     // Update the default case count
1980     increment_mdp_data_at(mdp,
1981                           in_bytes(MultiBranchData::default_count_offset()));
1982 
1983     // The method data pointer needs to be updated.
1984     update_mdp_by_offset(mdp,
1985                          in_bytes(MultiBranchData::
1986                                   default_displacement_offset()));
1987 
1988     bind(profile_continue);
1989   }
1990 }
1991 
1992 
1993 void InterpreterMacroAssembler::profile_switch_case(Register index,
1994                                                     Register mdp,
1995                                                     Register reg2) {
1996   if (ProfileInterpreter) {
1997     Label profile_continue;
1998 
1999     // If no method data exists, go to profile_continue.
2000     test_method_data_pointer(mdp, profile_continue);
2001 
2002     // Build the base (index * per_case_size_in_bytes()) +
2003     // case_array_offset_in_bytes()
2004     movl(reg2, in_bytes(MultiBranchData::per_case_size()));
2005     imulptr(index, reg2); // XXX l ?
2006     addptr(index, in_bytes(MultiBranchData::case_array_offset())); // XXX l ?
2007 
2008     // Update the case count
2009     increment_mdp_data_at(mdp,
2010                           index,
2011                           in_bytes(MultiBranchData::relative_count_offset()));
2012 
2013     // The method data pointer needs to be updated.
2014     update_mdp_by_offset(mdp,
2015                          index,
2016                          in_bytes(MultiBranchData::
2017                                   relative_displacement_offset()));
2018 
2019     bind(profile_continue);
2020   }
2021 }
2022 
2023 
2024 
2025 void InterpreterMacroAssembler::_interp_verify_oop(Register reg, TosState state, const char* file, int line) {
2026   if (state == atos) {
2027     MacroAssembler::_verify_oop_checked(reg, "broken oop", file, line);
2028   }
2029 }
2030 
2031 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
2032 #ifndef _LP64
2033   if ((state == ftos && UseSSE < 1) ||
2034       (state == dtos && UseSSE < 2)) {
2035     MacroAssembler::verify_FPU(stack_depth);
2036   }
2037 #endif
2038 }
2039 
2040 // Jump if ((*counter_addr += increment) & mask) == 0
2041 void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, Address mask,
2042                                                         Register scratch, Label* where) {
2043   // This update is actually not atomic and can lose a number of updates
2044   // under heavy contention, but the alternative of using the (contended)
2045   // atomic update here penalizes profiling paths too much.
2046   movl(scratch, counter_addr);
2047   incrementl(scratch, InvocationCounter::count_increment);
2048   movl(counter_addr, scratch);
2049   andl(scratch, mask);
2050   if (where != nullptr) {
2051     jcc(Assembler::zero, *where);
2052   }
2053 }
2054 
2055 void InterpreterMacroAssembler::notify_method_entry() {
2056   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
2057   // track stack depth.  If it is possible to enter interp_only_mode we add
2058   // the code to check if the event should be sent.
2059   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
2060   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
2061   if (JvmtiExport::can_post_interpreter_events()) {
2062     Label L;
2063     NOT_LP64(get_thread(rthread);)
2064     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2065     testl(rdx, rdx);
2066     jcc(Assembler::zero, L);
2067     call_VM(noreg, CAST_FROM_FN_PTR(address,
2068                                     InterpreterRuntime::post_method_entry));
2069     bind(L);
2070   }
2071 
2072   {
2073     SkipIfEqual skip(this, &DTraceMethodProbes, false, rscratch1);
2074     NOT_LP64(get_thread(rthread);)
2075     get_method(rarg);
2076     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2077                  rthread, rarg);
2078   }
2079 
2080   // RedefineClasses() tracing support for obsolete method entry
2081   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2082     NOT_LP64(get_thread(rthread);)
2083     get_method(rarg);
2084     call_VM_leaf(
2085       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2086       rthread, rarg);
2087   }
2088 }
2089 
2090 
2091 void InterpreterMacroAssembler::notify_method_exit(
2092     TosState state, NotifyMethodExitMode mode) {
2093   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
2094   // track stack depth.  If it is possible to enter interp_only_mode we add
2095   // the code to check if the event should be sent.
2096   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
2097   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
2098   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2099     Label L;
2100     // Note: frame::interpreter_frame_result has a dependency on how the
2101     // method result is saved across the call to post_method_exit. If this
2102     // is changed then the interpreter_frame_result implementation will
2103     // need to be updated too.
2104 
2105     // template interpreter will leave the result on the top of the stack.
2106     push(state);
2107     NOT_LP64(get_thread(rthread);)
2108     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2109     testl(rdx, rdx);
2110     jcc(Assembler::zero, L);
2111     call_VM(noreg,
2112             CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit));
2113     bind(L);
2114     pop(state);
2115   }
2116 
2117   {
2118     SkipIfEqual skip(this, &DTraceMethodProbes, false, rscratch1);
2119     push(state);
2120     NOT_LP64(get_thread(rthread);)
2121     get_method(rarg);
2122     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2123                  rthread, rarg);
2124     pop(state);
2125   }
2126 }
2127 
2128 void InterpreterMacroAssembler::load_resolved_indy_entry(Register cache, Register index) {
2129   // Get index out of bytecode pointer, get_cache_entry_pointer_at_bcp
2130   get_cache_index_at_bcp(index, 1, sizeof(u4));
2131   // Get address of invokedynamic array
2132   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2133   movptr(cache, Address(cache, in_bytes(ConstantPoolCache::invokedynamic_entries_offset())));
2134   if (is_power_of_2(sizeof(ResolvedIndyEntry))) {
2135     shll(index, log2i_exact(sizeof(ResolvedIndyEntry))); // Scale index by power of 2
2136   } else {
2137     imull(index, index, sizeof(ResolvedIndyEntry)); // Scale the index to be the entry index * sizeof(ResolvedInvokeDynamicInfo)
2138   }
2139   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedIndyEntry>::base_offset_in_bytes()));
2140 }