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