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