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