1 /*
   2  * Copyright (c) 2003, 2025, 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 "asm/macroAssembler.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "compiler/compiler_globals.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interpreter/bytecodeHistogram.hpp"
  31 #include "interpreter/interp_masm.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interpreterRuntime.hpp"
  34 #include "interpreter/templateInterpreterGenerator.hpp"
  35 #include "interpreter/templateTable.hpp"
  36 #include "oops/arrayOop.hpp"
  37 #include "oops/methodCounters.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "oops/method.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "oops/inlineKlass.hpp"
  42 #include "oops/resolvedIndyEntry.hpp"
  43 #include "oops/resolvedMethodEntry.hpp"
  44 #include "prims/jvmtiExport.hpp"
  45 #include "prims/jvmtiThreadState.hpp"
  46 #include "runtime/continuation.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/globals.hpp"
  50 #include "runtime/jniHandles.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/synchronizer.hpp"
  54 #include "runtime/timer.hpp"
  55 #include "runtime/vframeArray.hpp"
  56 #include "utilities/checkedCast.hpp"
  57 #include "utilities/debug.hpp"
  58 #include "utilities/macros.hpp"
  59 
  60 #define __ Disassembler::hook<InterpreterMacroAssembler>(__FILE__, __LINE__, _masm)->
  61 
  62 // Size of interpreter code.  Increase if too small.  Interpreter will
  63 // fail with a guarantee ("not enough space for interpreter generation");
  64 // if too small.
  65 // Run with +PrintInterpreter to get the VM to print out the size.
  66 // Max size with JVMTI
  67 int TemplateInterpreter::InterpreterCodeSize = JVMCI_ONLY(280) NOT_JVMCI(268) * 1024;
  68 
  69 // Global Register Names
  70 static const Register rbcp     = r13;
  71 static const Register rlocals  = r14;
  72 
  73 const int method_offset = frame::interpreter_frame_method_offset * wordSize;
  74 const int bcp_offset    = frame::interpreter_frame_bcp_offset    * wordSize;
  75 const int locals_offset = frame::interpreter_frame_locals_offset * wordSize;
  76 
  77 
  78 //-----------------------------------------------------------------------------
  79 
  80 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
  81   address entry = __ pc();
  82 
  83 #ifdef ASSERT
  84   {
  85     Label L;
  86     __ movptr(rax, Address(rbp,
  87                            frame::interpreter_frame_monitor_block_top_offset *
  88                            wordSize));
  89     __ lea(rax, Address(rbp, rax, Address::times_ptr));
  90     __ cmpptr(rax, rsp); // rax = maximal rsp for current rbp (stack
  91                          // grows negative)
  92     __ jcc(Assembler::aboveEqual, L); // check if frame is complete
  93     __ stop ("interpreter frame not set up");
  94     __ bind(L);
  95   }
  96 #endif // ASSERT
  97   // Restore bcp under the assumption that the current frame is still
  98   // interpreted
  99   __ restore_bcp();
 100 
 101   // expression stack must be empty before entering the VM if an
 102   // exception happened
 103   __ empty_expression_stack();
 104   // throw exception
 105   __ call_VM(noreg,
 106              CAST_FROM_FN_PTR(address,
 107                               InterpreterRuntime::throw_StackOverflowError));
 108   return entry;
 109 }
 110 
 111 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 112   address entry = __ pc();
 113   // The expression stack must be empty before entering the VM if an
 114   // exception happened.
 115   __ empty_expression_stack();
 116 
 117   // Setup parameters.
 118   // ??? convention: expect aberrant index in register ebx/rbx.
 119   // Pass array to create more detailed exceptions.
 120   __ call_VM(noreg,
 121              CAST_FROM_FN_PTR(address,
 122                               InterpreterRuntime::
 123                               throw_ArrayIndexOutOfBoundsException),
 124              c_rarg1, rbx);
 125   return entry;
 126 }
 127 
 128 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 129   address entry = __ pc();
 130 
 131   // object is at TOS
 132   __ pop(c_rarg1);
 133 
 134   // expression stack must be empty before entering the VM if an
 135   // exception happened
 136   __ empty_expression_stack();
 137 
 138   __ call_VM(noreg,
 139              CAST_FROM_FN_PTR(address,
 140                               InterpreterRuntime::
 141                               throw_ClassCastException),
 142              c_rarg1);
 143   return entry;
 144 }
 145 
 146 address TemplateInterpreterGenerator::generate_exception_handler_common(
 147         const char* name, const char* message, bool pass_oop) {
 148   assert(!pass_oop || message == nullptr, "either oop or message but not both");
 149   address entry = __ pc();
 150 
 151   if (pass_oop) {
 152     // object is at TOS
 153     __ pop(c_rarg2);
 154   }
 155   // expression stack must be empty before entering the VM if an
 156   // exception happened
 157   __ empty_expression_stack();
 158   // setup parameters
 159   __ lea(c_rarg1, ExternalAddress((address)name));
 160   if (pass_oop) {
 161     __ call_VM(rax, CAST_FROM_FN_PTR(address,
 162                                      InterpreterRuntime::
 163                                      create_klass_exception),
 164                c_rarg1, c_rarg2);
 165   } else {
 166     __ lea(c_rarg2, ExternalAddress((address)message));
 167     __ call_VM(rax,
 168                CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception),
 169                c_rarg1, c_rarg2);
 170   }
 171   // throw exception
 172   __ jump(RuntimeAddress(Interpreter::throw_exception_entry()));
 173   return entry;
 174 }
 175 
 176 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 177   address entry = __ pc();
 178 
 179   // Restore stack bottom in case i2c adjusted stack
 180   __ movptr(rscratch1, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
 181   __ lea(rsp, Address(rbp, rscratch1, Address::times_ptr));
 182   // and null it as marker that esp is now tos until next java call
 183   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 184 
 185   if (state == atos && InlineTypeReturnedAsFields) {
 186     __ store_inline_type_fields_to_buf(nullptr);
 187   }
 188 
 189   __ restore_bcp();
 190   __ restore_locals();
 191 
 192   if (state == atos) {
 193     Register mdp = rbx;
 194     Register tmp = rcx;
 195     __ profile_return_type(mdp, rax, tmp);
 196   }
 197 
 198   const Register cache = rbx;
 199   const Register index = rcx;
 200   if (index_size == sizeof(u4)) {
 201     __ load_resolved_indy_entry(cache, index);
 202     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedIndyEntry::num_parameters_offset())));
 203     __ lea(rsp, Address(rsp, cache, Interpreter::stackElementScale()));
 204   } else {
 205     assert(index_size == sizeof(u2), "Can only be u2");
 206     __ load_method_entry(cache, index);
 207     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedMethodEntry::num_parameters_offset())));
 208     __ lea(rsp, Address(rsp, cache, Interpreter::stackElementScale()));
 209   }
 210 
 211    if (JvmtiExport::can_pop_frame()) {
 212      __ check_and_handle_popframe();
 213    }
 214    if (JvmtiExport::can_force_early_return()) {
 215      __ check_and_handle_earlyret();
 216    }
 217 
 218   __ dispatch_next(state, step);
 219 
 220   return entry;
 221 }
 222 
 223 
 224 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step, address continuation) {
 225   address entry = __ pc();
 226 
 227   // null last_sp until next java call
 228   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 229   __ restore_bcp();
 230   __ restore_locals();
 231   const Register thread = r15_thread;
 232 #if INCLUDE_JVMCI
 233   // Check if we need to take lock at entry of synchronized method.  This can
 234   // only occur on method entry so emit it only for vtos with step 0.
 235   if (EnableJVMCI && state == vtos && step == 0) {
 236     Label L;
 237     __ cmpb(Address(thread, JavaThread::pending_monitorenter_offset()), 0);
 238     __ jcc(Assembler::zero, L);
 239     // Clear flag.
 240     __ movb(Address(thread, JavaThread::pending_monitorenter_offset()), 0);
 241     // Satisfy calling convention for lock_method().
 242     __ get_method(rbx);
 243     // Take lock.
 244     lock_method();
 245     __ bind(L);
 246   } else {
 247 #ifdef ASSERT
 248     if (EnableJVMCI) {
 249       Label L;
 250       __ cmpb(Address(r15_thread, JavaThread::pending_monitorenter_offset()), 0);
 251       __ jcc(Assembler::zero, L);
 252       __ stop("unexpected pending monitor in deopt entry");
 253       __ bind(L);
 254     }
 255 #endif
 256   }
 257 #endif
 258   // handle exceptions
 259   {
 260     Label L;
 261     __ cmpptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
 262     __ jcc(Assembler::zero, L);
 263     __ call_VM(noreg,
 264                CAST_FROM_FN_PTR(address,
 265                                 InterpreterRuntime::throw_pending_exception));
 266     __ should_not_reach_here();
 267     __ bind(L);
 268   }
 269   if (continuation == nullptr) {
 270     __ dispatch_next(state, step);
 271   } else {
 272     __ jump_to_entry(continuation);
 273   }
 274   return entry;
 275 }
 276 
 277 address TemplateInterpreterGenerator::generate_result_handler_for(
 278         BasicType type) {
 279   address entry = __ pc();
 280   switch (type) {
 281   case T_BOOLEAN: __ c2bool(rax);            break;
 282   case T_CHAR   : __ movzwl(rax, rax);       break;
 283   case T_BYTE   : __ sign_extend_byte(rax);  break;
 284   case T_SHORT  : __ sign_extend_short(rax); break;
 285   case T_INT    : /* nothing to do */        break;
 286   case T_LONG   : /* nothing to do */        break;
 287   case T_VOID   : /* nothing to do */        break;
 288   case T_FLOAT  : /* nothing to do */        break;
 289   case T_DOUBLE : /* nothing to do */        break;
 290 
 291   case T_OBJECT :
 292     // retrieve result from frame
 293     __ movptr(rax, Address(rbp, frame::interpreter_frame_oop_temp_offset*wordSize));
 294     // and verify it
 295     __ verify_oop(rax);
 296     break;
 297   default       : ShouldNotReachHere();
 298   }
 299   __ ret(0);                                   // return from result handler
 300   return entry;
 301 }
 302 
 303 address TemplateInterpreterGenerator::generate_safept_entry_for(
 304         TosState state,
 305         address runtime_entry) {
 306   address entry = __ pc();
 307 
 308   __ push(state);
 309   __ push_cont_fastpath();
 310   __ call_VM(noreg, runtime_entry);
 311   __ pop_cont_fastpath();
 312 
 313   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 314   return entry;
 315 }
 316 
 317 address TemplateInterpreterGenerator::generate_cont_resume_interpreter_adapter() {
 318   if (!Continuations::enabled()) return nullptr;
 319   address start = __ pc();
 320 
 321   __ restore_bcp();
 322   __ restore_locals();
 323 
 324   // Get return address before adjusting rsp
 325   __ movptr(rax, Address(rsp, 0));
 326 
 327   // Restore stack bottom
 328   __ movptr(rcx, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
 329   __ lea(rsp, Address(rbp, rcx, Address::times_ptr));
 330   // and null it as marker that esp is now tos until next java call
 331   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 332 
 333   __ jmp(rax);
 334 
 335   return start;
 336 }
 337 
 338 
 339 // Helpers for commoning out cases in the various type of method entries.
 340 //
 341 
 342 
 343 // increment invocation count & check for overflow
 344 //
 345 // Note: checking for negative value instead of overflow
 346 //       so we have a 'sticky' overflow test
 347 //
 348 // rbx: method
 349 // rcx: invocation counter
 350 //
 351 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 352   Label done;
 353   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 354   Label no_mdo;
 355   if (ProfileInterpreter) {
 356     // Are we profiling?
 357     __ movptr(rax, Address(rbx, Method::method_data_offset()));
 358     __ testptr(rax, rax);
 359     __ jccb(Assembler::zero, no_mdo);
 360     // Increment counter in the MDO
 361     const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) +
 362         in_bytes(InvocationCounter::counter_offset()));
 363     const Address mask(rax, in_bytes(MethodData::invoke_mask_offset()));
 364     __ increment_mask_and_jump(mdo_invocation_counter, mask, rcx, overflow);
 365     __ jmp(done);
 366   }
 367   __ bind(no_mdo);
 368   // Increment counter in MethodCounters
 369   const Address invocation_counter(rax,
 370       MethodCounters::invocation_counter_offset() +
 371       InvocationCounter::counter_offset());
 372   __ get_method_counters(rbx, rax, done);
 373   const Address mask(rax, in_bytes(MethodCounters::invoke_mask_offset()));
 374   __ increment_mask_and_jump(invocation_counter, mask, rcx, overflow);
 375   __ bind(done);
 376 }
 377 
 378 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 379 
 380   // Asm interpreter on entry
 381   // r14/rdi - locals
 382   // r13/rsi - bcp
 383   // rbx - method
 384   // rdx - cpool --- DOES NOT APPEAR TO BE TRUE
 385   // rbp - interpreter frame
 386 
 387   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 388   // Everything as it was on entry
 389   // rdx is not restored. Doesn't appear to really be set.
 390 
 391   // InterpreterRuntime::frequency_counter_overflow takes two
 392   // arguments, the first (thread) is passed by call_VM, the second
 393   // indicates if the counter overflow occurs at a backwards branch
 394   // (null bcp).  We pass zero for it.  The call returns the address
 395   // of the verified entry point for the method or null if the
 396   // compilation did not complete (either went background or bailed
 397   // out).
 398   __ movl(c_rarg1, 0);
 399   __ call_VM(noreg,
 400              CAST_FROM_FN_PTR(address,
 401                               InterpreterRuntime::frequency_counter_overflow),
 402              c_rarg1);
 403 
 404   __ movptr(rbx, Address(rbp, method_offset));   // restore Method*
 405   // Preserve invariant that r13/r14 contain bcp/locals of sender frame
 406   // and jump to the interpreted entry.
 407   __ jmp(do_continue, relocInfo::none);
 408 }
 409 
 410 // See if we've got enough room on the stack for locals plus overhead below
 411 // JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 412 // without going through the signal handler, i.e., reserved and yellow zones
 413 // will not be made usable. The shadow zone must suffice to handle the
 414 // overflow.
 415 // The expression stack grows down incrementally, so the normal guard
 416 // page mechanism will work for that.
 417 //
 418 // NOTE: Since the additional locals are also always pushed (wasn't
 419 // obvious in generate_fixed_frame) so the guard should work for them
 420 // too.
 421 //
 422 // Args:
 423 //      rdx: number of additional locals this frame needs (what we must check)
 424 //      rbx: Method*
 425 //
 426 // Kills:
 427 //      rax
 428 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 429 
 430   // monitor entry size: see picture of stack in frame_x86.hpp
 431   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 432 
 433   // total overhead size: entry_size + (saved rbp through expr stack
 434   // bottom).  be sure to change this if you add/subtract anything
 435   // to/from the overhead area
 436   const int overhead_size =
 437     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 438 
 439   const int page_size = (int)os::vm_page_size();
 440 
 441   Label after_frame_check;
 442 
 443   // see if the frame is greater than one page in size. If so,
 444   // then we need to verify there is enough stack space remaining
 445   // for the additional locals.
 446   __ cmpl(rdx, (page_size - overhead_size) / Interpreter::stackElementSize);
 447   __ jcc(Assembler::belowEqual, after_frame_check);
 448 
 449   // compute rsp as if this were going to be the last frame on
 450   // the stack before the red zone
 451 
 452   Label after_frame_check_pop;
 453 
 454   const Address stack_limit(r15_thread, JavaThread::stack_overflow_limit_offset());
 455 
 456   // locals + overhead, in bytes
 457   __ mov(rax, rdx);
 458   __ shlptr(rax, Interpreter::logStackElementSize); // Convert parameter count to bytes.
 459   __ addptr(rax, overhead_size);
 460 
 461 #ifdef ASSERT
 462   Label limit_okay;
 463   // Verify that thread stack overflow limit is non-zero.
 464   __ cmpptr(stack_limit, NULL_WORD);
 465   __ jcc(Assembler::notEqual, limit_okay);
 466   __ stop("stack overflow limit is zero");
 467   __ bind(limit_okay);
 468 #endif
 469 
 470   // Add locals/frame size to stack limit.
 471   __ addptr(rax, stack_limit);
 472 
 473   // Check against the current stack bottom.
 474   __ cmpptr(rsp, rax);
 475 
 476   __ jcc(Assembler::above, after_frame_check_pop);
 477 
 478   // Restore sender's sp as SP. This is necessary if the sender's
 479   // frame is an extended compiled frame (see gen_c2i_adapter())
 480   // and safer anyway in case of JSR292 adaptations.
 481 
 482   __ pop(rax); // return address must be moved if SP is changed
 483   __ mov(rsp, rbcp);
 484   __ push(rax);
 485 
 486   // Note: the restored frame is not necessarily interpreted.
 487   // Use the shared runtime version of the StackOverflowError.
 488   assert(SharedRuntime::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 489   __ jump(RuntimeAddress(SharedRuntime::throw_StackOverflowError_entry()));
 490   // all done with frame size check
 491   __ bind(after_frame_check_pop);
 492 
 493   // all done with frame size check
 494   __ bind(after_frame_check);
 495 }
 496 
 497 // Allocate monitor and lock method (asm interpreter)
 498 //
 499 // Args:
 500 //      rbx: Method*
 501 //      r14/rdi: locals
 502 //
 503 // Kills:
 504 //      rax
 505 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 506 //      rscratch1, rscratch2 (scratch regs)
 507 void TemplateInterpreterGenerator::lock_method() {
 508   // synchronize method
 509   const Address access_flags(rbx, Method::access_flags_offset());
 510   const Address monitor_block_top(
 511         rbp,
 512         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 513   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 514 
 515 #ifdef ASSERT
 516   {
 517     Label L;
 518     __ load_unsigned_short(rax, access_flags);
 519     __ testl(rax, JVM_ACC_SYNCHRONIZED);
 520     __ jcc(Assembler::notZero, L);
 521     __ stop("method doesn't need synchronization");
 522     __ bind(L);
 523   }
 524 #endif // ASSERT
 525 
 526   // get synchronization object
 527   {
 528     Label done;
 529     __ load_unsigned_short(rax, access_flags);
 530     __ testl(rax, JVM_ACC_STATIC);
 531     // get receiver (assume this is frequent case)
 532     __ movptr(rax, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 533     __ jcc(Assembler::zero, done);
 534     __ load_mirror(rax, rbx, rscratch2);
 535 
 536 #ifdef ASSERT
 537     {
 538       Label L;
 539       __ testptr(rax, rax);
 540       __ jcc(Assembler::notZero, L);
 541       __ stop("synchronization object is null");
 542       __ bind(L);
 543     }
 544 #endif // ASSERT
 545 
 546     __ bind(done);
 547   }
 548 
 549   // add space for monitor & lock
 550   __ subptr(rsp, entry_size); // add space for a monitor entry
 551   __ subptr(monitor_block_top, entry_size / wordSize); // set new monitor block top
 552   // store object
 553   __ movptr(Address(rsp, BasicObjectLock::obj_offset()), rax);
 554   __ movptr(c_rarg1, rsp); // object address
 555   __ lock_object(c_rarg1);
 556 }
 557 
 558 // Generate a fixed interpreter frame. This is identical setup for
 559 // interpreted methods and for native methods hence the shared code.
 560 //
 561 // Args:
 562 //      rax: return address
 563 //      rbx: Method*
 564 //      r14/rdi: pointer to locals
 565 //      r13/rsi: sender sp
 566 //      rdx: cp cache
 567 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 568   // initialize fixed part of activation frame
 569   __ push(rax);         // save return address
 570   __ enter();           // save old & set new rbp
 571   __ push(rbcp);        // set sender sp
 572 
 573   // Resolve ConstMethod* -> ConstantPool*.
 574   // Get codebase, while we still have ConstMethod*.
 575   // Save ConstantPool* in rax for later use.
 576   __ movptr(rax, Address(rbx, Method::const_offset()));
 577   __ lea(rbcp, Address(rax, ConstMethod::codes_offset()));
 578   __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
 579 
 580   __ push(NULL_WORD);  // leave last_sp as null
 581   __ push(rbx);        // save Method*
 582 
 583   // Get mirror and store it in the frame as GC root for this Method*.
 584   // rax is still ConstantPool*, resolve ConstantPool* -> InstanceKlass* -> Java mirror.
 585   __ movptr(rdx, Address(rax, ConstantPool::pool_holder_offset()));
 586   __ movptr(rdx, Address(rdx, in_bytes(Klass::java_mirror_offset())));
 587   __ resolve_oop_handle(rdx, rscratch2);
 588   __ push(rdx);
 589 
 590   if (ProfileInterpreter) {
 591     Label method_data_continue;
 592     __ movptr(rdx, Address(rbx, in_bytes(Method::method_data_offset())));
 593     __ testptr(rdx, rdx);
 594     __ jccb(Assembler::zero, method_data_continue);
 595     __ addptr(rdx, in_bytes(MethodData::data_offset()));
 596     __ bind(method_data_continue);
 597     __ push(rdx);      // set the mdp (method data pointer)
 598   } else {
 599     __ push(NULL_WORD);
 600   }
 601 
 602   // rax is still ConstantPool*, set the constant pool cache
 603   __ movptr(rdx, Address(rax, ConstantPool::cache_offset()));
 604   __ push(rdx);
 605 
 606   __ movptr(rax, rlocals);
 607   __ subptr(rax, rbp);
 608   __ shrptr(rax, Interpreter::logStackElementSize);  // rax = rlocals - fp();
 609   __ push(rax); // set relativized rlocals, see frame::interpreter_frame_locals()
 610 
 611   if (native_call) {
 612     __ push(NULL_WORD); // no bcp
 613   } else {
 614     __ push(rbcp); // set bcp
 615   }
 616   // initialize relativized pointer to expression stack bottom
 617   __ push(frame::interpreter_frame_initial_sp_offset);
 618 }
 619 
 620 // End of helpers
 621 
 622 // Method entry for java.lang.ref.Reference.get.
 623 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 624   // Code: _aload_0, _getfield, _areturn
 625   // parameter size = 1
 626   //
 627   // The code that gets generated by this routine is split into 2 parts:
 628   //    1. The "intrinsified" code performing an ON_WEAK_OOP_REF load,
 629   //    2. The slow path - which is an expansion of the regular method entry.
 630   //
 631   // Notes:-
 632   // * An intrinsic is always executed, where an ON_WEAK_OOP_REF load is performed.
 633   // * We may jump to the slow path iff the receiver is null. If the
 634   //   Reference object is null then we no longer perform an ON_WEAK_OOP_REF load
 635   //   Thus we can use the regular method entry code to generate the NPE.
 636   //
 637   // rbx: Method*
 638 
 639   // r13: senderSP must preserve for slow path, set SP to it on fast path
 640 
 641   address entry = __ pc();
 642 
 643   const int referent_offset = java_lang_ref_Reference::referent_offset();
 644 
 645   Label slow_path;
 646   // rbx: method
 647 
 648   // Check if local 0 != null
 649   // If the receiver is null then it is OK to jump to the slow path.
 650   __ movptr(rax, Address(rsp, wordSize));
 651 
 652   __ testptr(rax, rax);
 653   __ jcc(Assembler::zero, slow_path);
 654 
 655   // rax: local 0
 656   // rbx: method (but can be used as scratch now)
 657   // rdx: scratch
 658   // rdi: scratch
 659 
 660   // Load the value of the referent field.
 661   const Address field_address(rax, referent_offset);
 662   __ load_heap_oop(rax, field_address, /*tmp1*/ rbx, ON_WEAK_OOP_REF);
 663 
 664   // _areturn
 665   __ pop(rdi);                // get return address
 666   __ mov(rsp, r13);           // set sp to sender sp
 667   __ jmp(rdi);
 668   __ ret(0);
 669 
 670   // generate a vanilla interpreter entry as the slow path
 671   __ bind(slow_path);
 672   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 673   return entry;
 674 }
 675 
 676 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
 677   // See more discussion in stackOverflow.hpp.
 678 
 679   // Note that we do the banging after the frame is setup, since the exception
 680   // handling code expects to find a valid interpreter frame on the stack.
 681   // Doing the banging earlier fails if the caller frame is not an interpreter
 682   // frame.
 683   // (Also, the exception throwing code expects to unlock any synchronized
 684   // method receiver, so do the banging after locking the receiver.)
 685 
 686   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
 687   const int page_size = (int)os::vm_page_size();
 688   const int n_shadow_pages = shadow_zone_size / page_size;
 689 
 690   const Register thread = r15_thread;
 691 
 692 #ifdef ASSERT
 693   Label L_good_limit;
 694   __ cmpptr(Address(thread, JavaThread::shadow_zone_safe_limit()), NULL_WORD);
 695   __ jcc(Assembler::notEqual, L_good_limit);
 696   __ stop("shadow zone safe limit is not initialized");
 697   __ bind(L_good_limit);
 698 
 699   Label L_good_watermark;
 700   __ cmpptr(Address(thread, JavaThread::shadow_zone_growth_watermark()), NULL_WORD);
 701   __ jcc(Assembler::notEqual, L_good_watermark);
 702   __ stop("shadow zone growth watermark is not initialized");
 703   __ bind(L_good_watermark);
 704 #endif
 705 
 706   Label L_done;
 707 
 708   __ cmpptr(rsp, Address(thread, JavaThread::shadow_zone_growth_watermark()));
 709   __ jcc(Assembler::above, L_done);
 710 
 711   for (int p = 1; p <= n_shadow_pages; p++) {
 712     __ bang_stack_with_offset(p*page_size);
 713   }
 714 
 715   // Record the new watermark, but only if update is above the safe limit.
 716   // Otherwise, the next time around the check above would pass the safe limit.
 717   __ cmpptr(rsp, Address(thread, JavaThread::shadow_zone_safe_limit()));
 718   __ jccb(Assembler::belowEqual, L_done);
 719   __ movptr(Address(thread, JavaThread::shadow_zone_growth_watermark()), rsp);
 720 
 721   __ bind(L_done);
 722 }
 723 
 724 // Interpreter stub for calling a native method. (asm interpreter)
 725 // This sets up a somewhat different looking stack for calling the
 726 // native method than the typical interpreter frame setup.
 727 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
 728   // determine code generation flags
 729   bool inc_counter  = UseCompiler || CountCompiledCalls;
 730 
 731   // rbx: Method*
 732   // rbcp: sender sp
 733 
 734   address entry_point = __ pc();
 735 
 736   const Address constMethod       (rbx, Method::const_offset());
 737   const Address access_flags      (rbx, Method::access_flags_offset());
 738   const Address size_of_parameters(rcx, ConstMethod::
 739                                         size_of_parameters_offset());
 740 
 741 
 742   // get parameter size (always needed)
 743   __ movptr(rcx, constMethod);
 744   __ load_unsigned_short(rcx, size_of_parameters);
 745 
 746   // native calls don't need the stack size check since they have no
 747   // expression stack and the arguments are already on the stack and
 748   // we only add a handful of words to the stack
 749 
 750   // rbx: Method*
 751   // rcx: size of parameters
 752   // rbcp: sender sp
 753   __ pop(rax);                                       // get return address
 754 
 755   // for natives the size of locals is zero
 756 
 757   // compute beginning of parameters
 758   __ lea(rlocals, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
 759 
 760   // add 2 zero-initialized slots for native calls
 761   // initialize result_handler slot
 762   __ push(NULL_WORD);
 763   // slot for oop temp
 764   // (static native method holder mirror/jni oop result)
 765   __ push(NULL_WORD);
 766 
 767   // initialize fixed part of activation frame
 768   generate_fixed_frame(true);
 769 
 770   // make sure method is native & not abstract
 771 #ifdef ASSERT
 772   __ load_unsigned_short(rax, access_flags);
 773   {
 774     Label L;
 775     __ testl(rax, JVM_ACC_NATIVE);
 776     __ jcc(Assembler::notZero, L);
 777     __ stop("tried to execute non-native method as native");
 778     __ bind(L);
 779   }
 780   {
 781     Label L;
 782     __ testl(rax, JVM_ACC_ABSTRACT);
 783     __ jcc(Assembler::zero, L);
 784     __ stop("tried to execute abstract method in interpreter");
 785     __ bind(L);
 786   }
 787 #endif
 788 
 789   // Since at this point in the method invocation the exception handler
 790   // would try to exit the monitor of synchronized methods which hasn't
 791   // been entered yet, we set the thread local variable
 792   // _do_not_unlock_if_synchronized to true. The remove_activation will
 793   // check this flag.
 794 
 795   const Address do_not_unlock_if_synchronized(r15_thread,
 796         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
 797   __ movbool(do_not_unlock_if_synchronized, true);
 798 
 799   // increment invocation count & check for overflow
 800   Label invocation_counter_overflow;
 801   if (inc_counter) {
 802     generate_counter_incr(&invocation_counter_overflow);
 803   }
 804 
 805   Label continue_after_compile;
 806   __ bind(continue_after_compile);
 807 
 808   bang_stack_shadow_pages(true);
 809 
 810   // reset the _do_not_unlock_if_synchronized flag
 811   __ movbool(do_not_unlock_if_synchronized, false);
 812 
 813   // check for synchronized methods
 814   // Must happen AFTER invocation_counter check and stack overflow check,
 815   // so method is not locked if overflows.
 816   if (synchronized) {
 817     lock_method();
 818   } else {
 819     // no synchronization necessary
 820 #ifdef ASSERT
 821     {
 822       Label L;
 823       __ load_unsigned_short(rax, access_flags);
 824       __ testl(rax, JVM_ACC_SYNCHRONIZED);
 825       __ jcc(Assembler::zero, L);
 826       __ stop("method needs synchronization");
 827       __ bind(L);
 828     }
 829 #endif
 830   }
 831 
 832   // start execution
 833 #ifdef ASSERT
 834   {
 835     Label L;
 836     const Address monitor_block_top(rbp,
 837                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
 838     __ movptr(rax, monitor_block_top);
 839     __ lea(rax, Address(rbp, rax, Address::times_ptr));
 840     __ cmpptr(rax, rsp);
 841     __ jcc(Assembler::equal, L);
 842     __ stop("broken stack frame setup in interpreter 5");
 843     __ bind(L);
 844   }
 845 #endif
 846 
 847   // jvmti support
 848   __ notify_method_entry();
 849 
 850   // work registers
 851   const Register method = rbx;
 852   const Register thread = r15_thread;
 853   const Register t      = r11;
 854 
 855   // allocate space for parameters
 856   __ get_method(method);
 857   __ movptr(t, Address(method, Method::const_offset()));
 858   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
 859 
 860   __ shll(t, Interpreter::logStackElementSize);
 861 
 862   __ subptr(rsp, t);
 863   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
 864   __ andptr(rsp, -16); // must be 16 byte boundary (see amd64 ABI)
 865 
 866   // get signature handler
 867   {
 868     Label L;
 869     __ movptr(t, Address(method, Method::signature_handler_offset()));
 870     __ testptr(t, t);
 871     __ jcc(Assembler::notZero, L);
 872     __ call_VM(noreg,
 873                CAST_FROM_FN_PTR(address,
 874                                 InterpreterRuntime::prepare_native_call),
 875                method);
 876     __ get_method(method);
 877     __ movptr(t, Address(method, Method::signature_handler_offset()));
 878     __ bind(L);
 879   }
 880 
 881   // call signature handler
 882   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
 883          "adjust this code");
 884   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == rsp,
 885          "adjust this code");
 886   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
 887          "adjust this code");
 888 
 889   // The generated handlers do not touch RBX (the method).
 890   // However, large signatures cannot be cached and are generated
 891   // each time here.  The slow-path generator can do a GC on return,
 892   // so we must reload it after the call.
 893   __ call(t);
 894   __ get_method(method);        // slow path can do a GC, reload RBX
 895 
 896 
 897   // result handler is in rax
 898   // set result handler
 899   __ movptr(Address(rbp,
 900                     (frame::interpreter_frame_result_handler_offset) * wordSize),
 901             rax);
 902 
 903   // pass mirror handle if static call
 904   {
 905     Label L;
 906     __ load_unsigned_short(t, Address(method, Method::access_flags_offset()));
 907     __ testl(t, JVM_ACC_STATIC);
 908     __ jcc(Assembler::zero, L);
 909     // get mirror
 910     __ load_mirror(t, method, rax);
 911     // copy mirror into activation frame
 912     __ movptr(Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize),
 913             t);
 914     // pass handle to mirror
 915     __ lea(c_rarg1,
 916            Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize));
 917     __ bind(L);
 918   }
 919 
 920   // get native function entry point
 921   {
 922     Label L;
 923     __ movptr(rax, Address(method, Method::native_function_offset()));
 924     ExternalAddress unsatisfied(SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 925     __ cmpptr(rax, unsatisfied.addr(), rscratch1);
 926     __ jcc(Assembler::notEqual, L);
 927     __ call_VM(noreg,
 928                CAST_FROM_FN_PTR(address,
 929                                 InterpreterRuntime::prepare_native_call),
 930                method);
 931     __ get_method(method);
 932     __ movptr(rax, Address(method, Method::native_function_offset()));
 933     __ bind(L);
 934   }
 935 
 936   // pass JNIEnv
 937    __ lea(c_rarg0, Address(r15_thread, JavaThread::jni_environment_offset()));
 938 
 939    // It is enough that the pc() points into the right code
 940    // segment. It does not have to be the correct return pc.
 941    // For convenience we use the pc we want to resume to in
 942    // case of preemption on Object.wait.
 943    Label native_return;
 944    __ set_last_Java_frame(rsp, rbp, native_return, rscratch1);
 945 
 946   // change thread state
 947 #ifdef ASSERT
 948   {
 949     Label L;
 950     __ movl(t, Address(thread, JavaThread::thread_state_offset()));
 951     __ cmpl(t, _thread_in_Java);
 952     __ jcc(Assembler::equal, L);
 953     __ stop("Wrong thread state in native stub");
 954     __ bind(L);
 955   }
 956 #endif
 957 
 958   // Change state to native
 959 
 960   __ movl(Address(thread, JavaThread::thread_state_offset()),
 961           _thread_in_native);
 962 
 963   __ push_cont_fastpath();
 964 
 965   // Call the native method.
 966   __ call(rax);
 967   // 32: result potentially in rdx:rax or ST0
 968   // 64: result potentially in rax or xmm0
 969 
 970   __ pop_cont_fastpath();
 971 
 972   // Verify or restore cpu control state after JNI call
 973   __ restore_cpu_control_state_after_jni(rscratch1);
 974 
 975   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
 976   // in order to extract the result of a method call. If the order of these
 977   // pushes change or anything else is added to the stack then the code in
 978   // interpreter_frame_result must also change.
 979 
 980   __ push(dtos);
 981   __ push(ltos);
 982 
 983   // change thread state
 984   __ movl(Address(thread, JavaThread::thread_state_offset()),
 985           _thread_in_native_trans);
 986 
 987   // Force this write out before the read below
 988   if (!UseSystemMemoryBarrier) {
 989     __ membar(Assembler::Membar_mask_bits(
 990                 Assembler::LoadLoad | Assembler::LoadStore |
 991                 Assembler::StoreLoad | Assembler::StoreStore));
 992   }
 993 
 994   // check for safepoint operation in progress and/or pending suspend requests
 995   {
 996     Label Continue;
 997     Label slow_path;
 998 
 999     __ safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
1000 
1001     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
1002     __ jcc(Assembler::equal, Continue);
1003     __ bind(slow_path);
1004 
1005     // Don't use call_VM as it will see a possible pending exception
1006     // and forward it and never return here preventing us from
1007     // clearing _last_native_pc down below.  Also can't use
1008     // call_VM_leaf either as it will check to see if r13 & r14 are
1009     // preserved and correspond to the bcp/locals pointers. So we do a
1010     // runtime call by hand.
1011     //
1012     __ mov(c_rarg0, r15_thread);
1013     __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
1014     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1015     __ andptr(rsp, -16); // align stack as required by ABI
1016     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1017     __ mov(rsp, r12); // restore sp
1018     __ reinit_heapbase();
1019     __ bind(Continue);
1020   }
1021 
1022   // change thread state
1023   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
1024 
1025   if (LockingMode != LM_LEGACY) {
1026     // Check preemption for Object.wait()
1027     Label not_preempted;
1028     __ movptr(rscratch1, Address(r15_thread, JavaThread::preempt_alternate_return_offset()));
1029     __ cmpptr(rscratch1, NULL_WORD);
1030     __ jccb(Assembler::equal, not_preempted);
1031     __ movptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
1032     __ jmp(rscratch1);
1033     __ bind(native_return);
1034     __ restore_after_resume(true /* is_native */);
1035     __ bind(not_preempted);
1036   } else {
1037     // any pc will do so just use this one for LM_LEGACY to keep code together.
1038     __ bind(native_return);
1039   }
1040 
1041   // reset_last_Java_frame
1042   __ reset_last_Java_frame(true);
1043 
1044   if (CheckJNICalls) {
1045     // clear_pending_jni_exception_check
1046     __ movptr(Address(thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
1047   }
1048 
1049   // reset handle block
1050   __ movptr(t, Address(thread, JavaThread::active_handles_offset()));
1051   __ movl(Address(t, JNIHandleBlock::top_offset()), NULL_WORD);
1052 
1053   // If result is an oop unbox and store it in frame where gc will see it
1054   // and result handler will pick it up
1055 
1056   {
1057     Label no_oop;
1058     __ lea(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1059     __ cmpptr(t, Address(rbp, frame::interpreter_frame_result_handler_offset*wordSize));
1060     __ jcc(Assembler::notEqual, no_oop);
1061     // retrieve result
1062     __ pop(ltos);
1063     // Unbox oop result, e.g. JNIHandles::resolve value.
1064     __ resolve_jobject(rax /* value */,
1065                        t /* tmp */);
1066     __ movptr(Address(rbp, frame::interpreter_frame_oop_temp_offset*wordSize), rax);
1067     // keep stack depth as expected by pushing oop which will eventually be discarded
1068     __ push(ltos);
1069     __ bind(no_oop);
1070   }
1071 
1072 
1073   {
1074     Label no_reguard;
1075     __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()),
1076             StackOverflow::stack_guard_yellow_reserved_disabled);
1077     __ jcc(Assembler::notEqual, no_reguard);
1078 
1079     __ pusha(); // XXX only save smashed registers
1080     __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
1081     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1082     __ andptr(rsp, -16); // align stack as required by ABI
1083     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1084     __ mov(rsp, r12); // restore sp
1085     __ popa(); // XXX only restore smashed registers
1086     __ reinit_heapbase();
1087 
1088     __ bind(no_reguard);
1089   }
1090 
1091 
1092   // The method register is junk from after the thread_in_native transition
1093   // until here.  Also can't call_VM until the bcp has been
1094   // restored.  Need bcp for throwing exception below so get it now.
1095   __ get_method(method);
1096 
1097   // restore to have legal interpreter frame, i.e., bci == 0 <=> code_base()
1098   __ movptr(rbcp, Address(method, Method::const_offset()));   // get ConstMethod*
1099   __ lea(rbcp, Address(rbcp, ConstMethod::codes_offset()));    // get codebase
1100 
1101   // handle exceptions (exception handling will handle unlocking!)
1102   {
1103     Label L;
1104     __ cmpptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
1105     __ jcc(Assembler::zero, L);
1106     // Note: At some point we may want to unify this with the code
1107     // used in call_VM_base(); i.e., we should use the
1108     // StubRoutines::forward_exception code. For now this doesn't work
1109     // here because the rsp is not correctly set at this point.
1110     __ MacroAssembler::call_VM(noreg,
1111                                CAST_FROM_FN_PTR(address,
1112                                InterpreterRuntime::throw_pending_exception));
1113     __ should_not_reach_here();
1114     __ bind(L);
1115   }
1116 
1117   // do unlocking if necessary
1118   {
1119     Label L;
1120     __ load_unsigned_short(t, Address(method, Method::access_flags_offset()));
1121     __ testl(t, JVM_ACC_SYNCHRONIZED);
1122     __ jcc(Assembler::zero, L);
1123     // the code below should be shared with interpreter macro
1124     // assembler implementation
1125     {
1126       Label unlock;
1127       // BasicObjectLock will be first in list, since this is a
1128       // synchronized method. However, need to check that the object
1129       // has not been unlocked by an explicit monitorexit bytecode.
1130       const Address monitor(rbp,
1131                             (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1132                                        wordSize - (int)sizeof(BasicObjectLock)));
1133 
1134       const Register regmon = c_rarg1;
1135 
1136       // monitor expect in c_rarg1 for slow unlock path
1137       __ lea(regmon, monitor); // address of first monitor
1138 
1139       __ movptr(t, Address(regmon, BasicObjectLock::obj_offset()));
1140       __ testptr(t, t);
1141       __ jcc(Assembler::notZero, unlock);
1142 
1143       // Entry already unlocked, need to throw exception
1144       __ MacroAssembler::call_VM(noreg,
1145                                  CAST_FROM_FN_PTR(address,
1146                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1147       __ should_not_reach_here();
1148 
1149       __ bind(unlock);
1150       __ unlock_object(regmon);
1151     }
1152     __ bind(L);
1153   }
1154 
1155 #if INCLUDE_JFR
1156   __ enter_jfr_critical_section();
1157 
1158   // This poll test is to uphold the invariant that a JFR sampled frame
1159   // must not return to its caller without a prior safepoint poll check.
1160   // The earlier poll check in this routine is insufficient for this purpose
1161   // because the thread has transitioned back to Java.
1162 
1163   Label slow_path;
1164   Label fast_path;
1165   __ safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
1166   __ jmp(fast_path);
1167   __ bind(slow_path);
1168   __ push(dtos);
1169   __ push(ltos);
1170   __ set_last_Java_frame(noreg, rbp, (address)__ pc(), rscratch1);
1171   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), r15_thread);
1172   __ reset_last_Java_frame(true);
1173   __ pop(ltos);
1174   __ pop(dtos);
1175   __ bind(fast_path);
1176 
1177 #endif // INCLUDE_JFR
1178 
1179   // jvmti support
1180   // Note: This must happen _after_ handling/throwing any exceptions since
1181   //       the exception handler code notifies the runtime of method exits
1182   //       too. If this happens before, method entry/exit notifications are
1183   //       not properly paired (was bug - gri 11/22/99).
1184   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1185 
1186   // restore potential result in edx:eax, call result handler to
1187   // restore potential result in ST0 & handle result
1188 
1189   __ pop(ltos);
1190   __ pop(dtos);
1191 
1192   __ movptr(t, Address(rbp,
1193                        (frame::interpreter_frame_result_handler_offset) * wordSize));
1194   __ call(t);
1195 
1196   // remove activation
1197   __ movptr(t, Address(rbp,
1198                        frame::interpreter_frame_sender_sp_offset *
1199                        wordSize)); // get sender sp
1200   __ leave();                                // remove frame anchor
1201 
1202   JFR_ONLY(__ leave_jfr_critical_section();)
1203 
1204   __ pop(rdi);                               // get return address
1205   __ mov(rsp, t);                            // set sp to sender sp
1206 
1207   __ jmp(rdi);
1208 
1209   if (inc_counter) {
1210     // Handle overflow of counter and compile method
1211     __ bind(invocation_counter_overflow);
1212     generate_counter_overflow(continue_after_compile);
1213   }
1214 
1215   return entry_point;
1216 }
1217 
1218 // Abstract method entry
1219 // Attempt to execute abstract method. Throw exception
1220 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
1221 
1222   address entry_point = __ pc();
1223 
1224   // abstract method entry
1225 
1226   //  pop return address, reset last_sp to null
1227   __ empty_expression_stack();
1228   __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
1229   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
1230 
1231   // throw exception
1232   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodErrorWithMethod), rbx);
1233   // the call_VM checks for exception, so we should never return here.
1234   __ should_not_reach_here();
1235 
1236   return entry_point;
1237 }
1238 
1239 //
1240 // Generic interpreted method entry to (asm) interpreter
1241 //
1242 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1243   // determine code generation flags
1244   bool inc_counter  = UseCompiler || CountCompiledCalls;
1245 
1246   // ebx: Method*
1247   // rbcp: sender sp (set in InterpreterMacroAssembler::prepare_to_jump_from_interpreted / generate_call_stub)
1248   address entry_point = __ pc();
1249 
1250   const Address constMethod(rbx, Method::const_offset());
1251   const Address access_flags(rbx, Method::access_flags_offset());
1252   const Address size_of_parameters(rdx,
1253                                    ConstMethod::size_of_parameters_offset());
1254   const Address size_of_locals(rdx, ConstMethod::size_of_locals_offset());
1255 
1256 
1257   // get parameter size (always needed)
1258   __ movptr(rdx, constMethod);
1259   __ load_unsigned_short(rcx, size_of_parameters);
1260 
1261   // rbx: Method*
1262   // rcx: size of parameters
1263   // rbcp: sender_sp (could differ from sp+wordSize if we were called via c2i )
1264 
1265   __ load_unsigned_short(rdx, size_of_locals); // get size of locals in words
1266   __ subl(rdx, rcx); // rdx = no. of additional locals
1267 
1268   // YYY
1269 //   __ incrementl(rdx);
1270 //   __ andl(rdx, -2);
1271 
1272   // see if we've got enough room on the stack for locals plus overhead.
1273   generate_stack_overflow_check();
1274 
1275   // get return address
1276   __ pop(rax);
1277 
1278   // compute beginning of parameters
1279   __ lea(rlocals, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
1280 
1281   // rdx - # of additional locals
1282   // allocate space for locals
1283   // explicitly initialize locals
1284   {
1285     Label exit, loop;
1286     __ testl(rdx, rdx);
1287     __ jccb(Assembler::lessEqual, exit); // do nothing if rdx <= 0
1288     __ bind(loop);
1289     __ push(NULL_WORD); // initialize local variables
1290     __ decrementl(rdx); // until everything initialized
1291     __ jccb(Assembler::greater, loop);
1292     __ bind(exit);
1293   }
1294 
1295   // initialize fixed part of activation frame
1296   generate_fixed_frame(false);
1297 
1298   // make sure method is not native & not abstract
1299 #ifdef ASSERT
1300   __ load_unsigned_short(rax, access_flags);
1301   {
1302     Label L;
1303     __ testl(rax, JVM_ACC_NATIVE);
1304     __ jcc(Assembler::zero, L);
1305     __ stop("tried to execute native method as non-native");
1306     __ bind(L);
1307   }
1308   {
1309     Label L;
1310     __ testl(rax, JVM_ACC_ABSTRACT);
1311     __ jcc(Assembler::zero, L);
1312     __ stop("tried to execute abstract method in interpreter");
1313     __ bind(L);
1314   }
1315 #endif
1316 
1317   // Since at this point in the method invocation the exception
1318   // handler would try to exit the monitor of synchronized methods
1319   // which hasn't been entered yet, we set the thread local variable
1320   // _do_not_unlock_if_synchronized to true. The remove_activation
1321   // will check this flag.
1322 
1323   const Address do_not_unlock_if_synchronized(r15_thread,
1324         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1325   __ movbool(do_not_unlock_if_synchronized, true);
1326 
1327   __ profile_parameters_type(rax, rcx, rdx);
1328   // increment invocation count & check for overflow
1329   Label invocation_counter_overflow;
1330   if (inc_counter) {
1331     generate_counter_incr(&invocation_counter_overflow);
1332   }
1333 
1334   Label continue_after_compile;
1335   __ bind(continue_after_compile);
1336 
1337   // check for synchronized interpreted methods
1338   bang_stack_shadow_pages(false);
1339 
1340   // reset the _do_not_unlock_if_synchronized flag
1341   __ movbool(do_not_unlock_if_synchronized, false);
1342 
1343   // check for synchronized methods
1344   // Must happen AFTER invocation_counter check and stack overflow check,
1345   // so method is not locked if overflows.
1346   if (synchronized) {
1347     // Allocate monitor and lock method
1348     lock_method();
1349   } else {
1350     // no synchronization necessary
1351 #ifdef ASSERT
1352     {
1353       Label L;
1354       __ load_unsigned_short(rax, access_flags);
1355       __ testl(rax, JVM_ACC_SYNCHRONIZED);
1356       __ jcc(Assembler::zero, L);
1357       __ stop("method needs synchronization");
1358       __ bind(L);
1359     }
1360 #endif
1361   }
1362 
1363   // start execution
1364 #ifdef ASSERT
1365   {
1366     Label L;
1367      const Address monitor_block_top (rbp,
1368                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1369     __ movptr(rax, monitor_block_top);
1370     __ lea(rax, Address(rbp, rax, Address::times_ptr));
1371     __ cmpptr(rax, rsp);
1372     __ jcc(Assembler::equal, L);
1373     __ stop("broken stack frame setup in interpreter 6");
1374     __ bind(L);
1375   }
1376 #endif
1377 
1378   // jvmti support
1379   __ notify_method_entry();
1380 
1381   __ dispatch_next(vtos);
1382 
1383   // invocation counter overflow
1384   if (inc_counter) {
1385     // Handle overflow of counter and compile method
1386     __ bind(invocation_counter_overflow);
1387     generate_counter_overflow(continue_after_compile);
1388   }
1389 
1390   return entry_point;
1391 }
1392 
1393 //-----------------------------------------------------------------------------
1394 // Exceptions
1395 
1396 void TemplateInterpreterGenerator::generate_throw_exception() {
1397   // Entry point in previous activation (i.e., if the caller was
1398   // interpreted)
1399   Interpreter::_rethrow_exception_entry = __ pc();
1400   // Restore sp to interpreter_frame_last_sp even though we are going
1401   // to empty the expression stack for the exception processing.
1402   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1403   // rax: exception
1404   // rdx: return address/pc that threw exception
1405   __ restore_bcp();    // r13/rsi points to call/send
1406   __ restore_locals();
1407   __ reinit_heapbase();  // restore r12 as heapbase.
1408   // Entry point for exceptions thrown within interpreter code
1409   Interpreter::_throw_exception_entry = __ pc();
1410   // expression stack is undefined here
1411   // rax: exception
1412   // r13/rsi: exception bcp
1413   __ verify_oop(rax);
1414   __ mov(c_rarg1, rax);
1415 
1416   // expression stack must be empty before entering the VM in case of
1417   // an exception
1418   __ empty_expression_stack();
1419   // find exception handler address and preserve exception oop
1420   __ call_VM(rdx,
1421              CAST_FROM_FN_PTR(address,
1422                           InterpreterRuntime::exception_handler_for_exception),
1423              c_rarg1);
1424   // rax: exception handler entry point
1425   // rdx: preserved exception oop
1426   // r13/rsi: bcp for exception handler
1427   __ push_ptr(rdx); // push exception which is now the only value on the stack
1428   __ jmp(rax); // jump to exception handler (may be _remove_activation_entry!)
1429 
1430   // If the exception is not handled in the current frame the frame is
1431   // removed and the exception is rethrown (i.e. exception
1432   // continuation is _rethrow_exception).
1433   //
1434   // Note: At this point the bci is still the bxi for the instruction
1435   // which caused the exception and the expression stack is
1436   // empty. Thus, for any VM calls at this point, GC will find a legal
1437   // oop map (with empty expression stack).
1438 
1439   // In current activation
1440   // tos: exception
1441   // esi: exception bcp
1442 
1443   //
1444   // JVMTI PopFrame support
1445   //
1446 
1447   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1448   __ empty_expression_stack();
1449   // Set the popframe_processing bit in pending_popframe_condition
1450   // indicating that we are currently handling popframe, so that
1451   // call_VMs that may happen later do not trigger new popframe
1452   // handling cycles.
1453   const Register thread = r15_thread;
1454   __ movl(rdx, Address(thread, JavaThread::popframe_condition_offset()));
1455   __ orl(rdx, JavaThread::popframe_processing_bit);
1456   __ movl(Address(thread, JavaThread::popframe_condition_offset()), rdx);
1457 
1458   {
1459     // Check to see whether we are returning to a deoptimized frame.
1460     // (The PopFrame call ensures that the caller of the popped frame is
1461     // either interpreted or compiled and deoptimizes it if compiled.)
1462     // In this case, we can't call dispatch_next() after the frame is
1463     // popped, but instead must save the incoming arguments and restore
1464     // them after deoptimization has occurred.
1465     //
1466     // Note that we don't compare the return PC against the
1467     // deoptimization blob's unpack entry because of the presence of
1468     // adapter frames in C2.
1469     Label caller_not_deoptimized;
1470     __ movptr(c_rarg1, Address(rbp, frame::return_addr_offset * wordSize));
1471     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1472                                InterpreterRuntime::interpreter_contains), c_rarg1);
1473     __ testl(rax, rax);
1474     __ jcc(Assembler::notZero, caller_not_deoptimized);
1475 
1476     // Compute size of arguments for saving when returning to
1477     // deoptimized caller
1478     __ get_method(rax);
1479     __ movptr(rax, Address(rax, Method::const_offset()));
1480     __ load_unsigned_short(rax, Address(rax, in_bytes(ConstMethod::
1481                                                 size_of_parameters_offset())));
1482     __ shll(rax, Interpreter::logStackElementSize);
1483     __ restore_locals();
1484     __ subptr(rlocals, rax);
1485     __ addptr(rlocals, wordSize);
1486     // Save these arguments
1487     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1488                                            Deoptimization::
1489                                            popframe_preserve_args),
1490                           thread, rax, rlocals);
1491 
1492     __ remove_activation(vtos, rdx,
1493                          /* throw_monitor_exception */ false,
1494                          /* install_monitor_exception */ false,
1495                          /* notify_jvmdi */ false);
1496 
1497     // Inform deoptimization that it is responsible for restoring
1498     // these arguments
1499     __ movl(Address(thread, JavaThread::popframe_condition_offset()),
1500             JavaThread::popframe_force_deopt_reexecution_bit);
1501 
1502     // Continue in deoptimization handler
1503     __ jmp(rdx);
1504 
1505     __ bind(caller_not_deoptimized);
1506   }
1507 
1508   __ remove_activation(vtos, rdx, /* rdx result (retaddr) is not used */
1509                        /* throw_monitor_exception */ false,
1510                        /* install_monitor_exception */ false,
1511                        /* notify_jvmdi */ false);
1512 
1513   // Finish with popframe handling
1514   // A previous I2C followed by a deoptimization might have moved the
1515   // outgoing arguments further up the stack. PopFrame expects the
1516   // mutations to those outgoing arguments to be preserved and other
1517   // constraints basically require this frame to look exactly as
1518   // though it had previously invoked an interpreted activation with
1519   // no space between the top of the expression stack (current
1520   // last_sp) and the top of stack. Rather than force deopt to
1521   // maintain this kind of invariant all the time we call a small
1522   // fixup routine to move the mutated arguments onto the top of our
1523   // expression stack if necessary.
1524   __ mov(c_rarg1, rsp);
1525   __ movptr(c_rarg2, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1526   __ lea(c_rarg2, Address(rbp, c_rarg2, Address::times_ptr));
1527   // PC must point into interpreter here
1528   __ set_last_Java_frame(noreg, rbp, __ pc(), rscratch1);
1529   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::popframe_move_outgoing_args), r15_thread, c_rarg1, c_rarg2);
1530   __ reset_last_Java_frame(true);
1531 
1532   // Restore the last_sp and null it out
1533   __ movptr(rcx, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1534   __ lea(rsp, Address(rbp, rcx, Address::times_ptr));
1535   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1536 
1537   __ restore_bcp();
1538   __ restore_locals();
1539   // The method data pointer was incremented already during
1540   // call profiling. We have to restore the mdp for the current bcp.
1541   if (ProfileInterpreter) {
1542     __ set_method_data_pointer_for_bcp();
1543   }
1544 
1545   // Clear the popframe condition flag
1546   __ movl(Address(thread, JavaThread::popframe_condition_offset()),
1547           JavaThread::popframe_inactive);
1548 
1549 #if INCLUDE_JVMTI
1550   {
1551     Label L_done;
1552     const Register local0 = rlocals;
1553 
1554     __ cmpb(Address(rbcp, 0), Bytecodes::_invokestatic);
1555     __ jcc(Assembler::notEqual, L_done);
1556 
1557     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1558     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1559 
1560     __ get_method(rdx);
1561     __ movptr(rax, Address(local0, 0));
1562     __ call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), rax, rdx, rbcp);
1563 
1564     __ testptr(rax, rax);
1565     __ jcc(Assembler::zero, L_done);
1566 
1567     __ movptr(Address(rbx, 0), rax);
1568     __ bind(L_done);
1569   }
1570 #endif // INCLUDE_JVMTI
1571 
1572   __ dispatch_next(vtos);
1573   // end of PopFrame support
1574 
1575   Interpreter::_remove_activation_entry = __ pc();
1576 
1577   // preserve exception over this code sequence
1578   __ pop_ptr(rax);
1579   __ movptr(Address(thread, JavaThread::vm_result_oop_offset()), rax);
1580   // remove the activation (without doing throws on illegalMonitorExceptions)
1581   __ remove_activation(vtos, rdx, false, true, false);
1582   // restore exception
1583   __ get_vm_result_oop(rax);
1584 
1585   // In between activations - previous activation type unknown yet
1586   // compute continuation point - the continuation point expects the
1587   // following registers set up:
1588   //
1589   // rax: exception
1590   // rdx: return address/pc that threw exception
1591   // rsp: expression stack of caller
1592   // rbp: ebp of caller
1593   __ push(rax);                                  // save exception
1594   __ push(rdx);                                  // save return address
1595   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1596                           SharedRuntime::exception_handler_for_return_address),
1597                         thread, rdx);
1598   __ mov(rbx, rax);                              // save exception handler
1599   __ pop(rdx);                                   // restore return address
1600   __ pop(rax);                                   // restore exception
1601   // Note that an "issuing PC" is actually the next PC after the call
1602   __ jmp(rbx);                                   // jump to exception
1603                                                  // handler of caller
1604 }
1605 
1606 
1607 //
1608 // JVMTI ForceEarlyReturn support
1609 //
1610 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1611   address entry = __ pc();
1612 
1613   __ restore_bcp();
1614   __ restore_locals();
1615   __ empty_expression_stack();
1616   __ load_earlyret_value(state);  // 32 bits returns value in rdx, so don't reuse
1617 
1618   __ movptr(rcx, Address(r15_thread, JavaThread::jvmti_thread_state_offset()));
1619   Address cond_addr(rcx, JvmtiThreadState::earlyret_state_offset());
1620 
1621   // Clear the earlyret state
1622   __ movl(cond_addr, JvmtiThreadState::earlyret_inactive);
1623 
1624   __ remove_activation(state, rsi,
1625                        false, /* throw_monitor_exception */
1626                        false, /* install_monitor_exception */
1627                        true); /* notify_jvmdi */
1628   __ jmp(rsi);
1629 
1630   return entry;
1631 } // end of ForceEarlyReturn support
1632 
1633 
1634 //-----------------------------------------------------------------------------
1635 // Helper for vtos entry point generation
1636 
1637 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
1638                                                          address& bep,
1639                                                          address& cep,
1640                                                          address& sep,
1641                                                          address& aep,
1642                                                          address& iep,
1643                                                          address& lep,
1644                                                          address& fep,
1645                                                          address& dep,
1646                                                          address& vep) {
1647   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1648   Label L;
1649   fep = __ pc();     // ftos entry point
1650       __ push_f(xmm0);
1651       __ jmpb(L);
1652   dep = __ pc();     // dtos entry point
1653       __ push_d(xmm0);
1654       __ jmpb(L);
1655   lep = __ pc();     // ltos entry point
1656       __ push_l();
1657       __ jmpb(L);
1658   aep = bep = cep = sep = iep = __ pc();      // [abcsi]tos entry point
1659       __ push_i_or_ptr();
1660   vep = __ pc();    // vtos entry point
1661   __ bind(L);
1662   generate_and_dispatch(t);
1663 }
1664 
1665 //-----------------------------------------------------------------------------
1666 
1667 // Non-product code
1668 #ifndef PRODUCT
1669 
1670 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1671   address entry = __ pc();
1672 
1673   __ push(state);
1674   __ push(c_rarg0);
1675   __ push(c_rarg1);
1676   __ push(c_rarg2);
1677   __ push(c_rarg3);
1678   __ mov(c_rarg2, rax);  // Pass itos
1679 #ifdef _WIN64
1680   __ movflt(xmm3, xmm0); // Pass ftos
1681 #endif
1682   __ call_VM(noreg,
1683              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
1684              c_rarg1, c_rarg2, c_rarg3);
1685   __ pop(c_rarg3);
1686   __ pop(c_rarg2);
1687   __ pop(c_rarg1);
1688   __ pop(c_rarg0);
1689   __ pop(state);
1690   __ ret(0);                                   // return from result handler
1691 
1692   return entry;
1693 }
1694 
1695 void TemplateInterpreterGenerator::count_bytecode() {
1696   __ incrementq(ExternalAddress((address) &BytecodeCounter::_counter_value), rscratch1);
1697 }
1698 
1699 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1700   __ incrementl(ExternalAddress((address) &BytecodeHistogram::_counters[t->bytecode()]), rscratch1);
1701 }
1702 
1703 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1704   __ mov32(rbx, ExternalAddress((address) &BytecodePairHistogram::_index));
1705   __ shrl(rbx, BytecodePairHistogram::log2_number_of_codes);
1706   __ orl(rbx,
1707          ((int) t->bytecode()) <<
1708          BytecodePairHistogram::log2_number_of_codes);
1709   __ mov32(ExternalAddress((address) &BytecodePairHistogram::_index), rbx, rscratch1);
1710   __ lea(rscratch1, ExternalAddress((address) BytecodePairHistogram::_counters));
1711   __ incrementl(Address(rscratch1, rbx, Address::times_4));
1712 }
1713 
1714 
1715 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
1716   // Call a little run-time stub to avoid blow-up for each bytecode.
1717   // The run-time runtime saves the right registers, depending on
1718   // the tosca in-state for the given template.
1719 
1720   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
1721          "entry must have been generated");
1722   __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
1723   __ andptr(rsp, -16); // align stack as required by ABI
1724   __ call(RuntimeAddress(Interpreter::trace_code(t->tos_in())));
1725   __ mov(rsp, r12); // restore sp
1726   __ reinit_heapbase();
1727 }
1728 
1729 
1730 void TemplateInterpreterGenerator::stop_interpreter_at() {
1731   Label L;
1732   __ mov64(rscratch1, StopInterpreterAt);
1733   __ cmp64(rscratch1, ExternalAddress((address) &BytecodeCounter::_counter_value), rscratch2);
1734   __ jcc(Assembler::notEqual, L);
1735   __ int3();
1736   __ bind(L);
1737 }
1738 #endif // !PRODUCT