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