1 /*
   2  * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2020, Red Hat Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "compiler/compiler_globals.hpp"
  30 #include "gc/shared/barrierSetAssembler.hpp"
  31 #include "interpreter/bytecodeHistogram.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interpreterRuntime.hpp"
  34 #include "interpreter/interp_masm.hpp"
  35 #include "interpreter/templateInterpreterGenerator.hpp"
  36 #include "interpreter/templateTable.hpp"
  37 #include "interpreter/bytecodeTracer.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/arrayOop.hpp"
  40 #include "oops/method.hpp"
  41 #include "oops/methodCounters.hpp"
  42 #include "oops/methodData.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/resolvedIndyEntry.hpp"
  45 #include "oops/resolvedMethodEntry.hpp"
  46 #include "prims/jvmtiExport.hpp"
  47 #include "prims/jvmtiThreadState.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/deoptimization.hpp"
  50 #include "runtime/frame.inline.hpp"
  51 #include "runtime/globals.hpp"
  52 #include "runtime/jniHandles.hpp"
  53 #include "runtime/sharedRuntime.hpp"
  54 #include "runtime/stubRoutines.hpp"
  55 #include "runtime/synchronizer.hpp"
  56 #include "runtime/timer.hpp"
  57 #include "runtime/vframeArray.hpp"
  58 #include "utilities/checkedCast.hpp"
  59 #include "utilities/debug.hpp"
  60 #include "utilities/powerOfTwo.hpp"
  61 #include <sys/types.h>
  62 
  63 // Size of interpreter code.  Increase if too small.  Interpreter will
  64 // fail with a guarantee ("not enough space for interpreter generation");
  65 // if too small.
  66 // Run with +PrintInterpreter to get the VM to print out the size.
  67 // Max size with JVMTI
  68 int TemplateInterpreter::InterpreterCodeSize = 200 * 1024;
  69 
  70 #define __ _masm->
  71 
  72 //-----------------------------------------------------------------------------
  73 
  74 extern "C" void entry(CodeBuffer*);
  75 
  76 //-----------------------------------------------------------------------------
  77 
  78 address TemplateInterpreterGenerator::generate_slow_signature_handler() {
  79   address entry = __ pc();
  80 
  81   __ andr(esp, esp, -16);
  82   __ mov(c_rarg3, esp);
  83   // rmethod
  84   // rlocals
  85   // c_rarg3: first stack arg - wordSize
  86 
  87   // adjust sp
  88   __ sub(sp, c_rarg3, 18 * wordSize);
  89   __ str(lr, Address(__ pre(sp, -2 * wordSize)));
  90   __ call_VM(noreg,
  91              CAST_FROM_FN_PTR(address,
  92                               InterpreterRuntime::slow_signature_handler),
  93              rmethod, rlocals, c_rarg3);
  94 
  95   // r0: result handler
  96 
  97   // Stack layout:
  98   // rsp: return address           <- sp
  99   //      1 garbage
 100   //      8 integer args (if static first is unused)
 101   //      1 float/double identifiers
 102   //      8 double args
 103   //        stack args              <- esp
 104   //        garbage
 105   //        expression stack bottom
 106   //        bcp (null)
 107   //        ...
 108 
 109   // Restore LR
 110   __ ldr(lr, Address(__ post(sp, 2 * wordSize)));
 111 
 112   // Do FP first so we can use c_rarg3 as temp
 113   __ ldrw(c_rarg3, Address(sp, 9 * wordSize)); // float/double identifiers
 114 
 115   for (int i = 0; i < Argument::n_float_register_parameters_c; i++) {
 116     const FloatRegister r = as_FloatRegister(i);
 117 
 118     Label d, done;
 119 
 120     __ tbnz(c_rarg3, i, d);
 121     __ ldrs(r, Address(sp, (10 + i) * wordSize));
 122     __ b(done);
 123     __ bind(d);
 124     __ ldrd(r, Address(sp, (10 + i) * wordSize));
 125     __ bind(done);
 126   }
 127 
 128   // c_rarg0 contains the result from the call of
 129   // InterpreterRuntime::slow_signature_handler so we don't touch it
 130   // here.  It will be loaded with the JNIEnv* later.
 131   __ ldr(c_rarg1, Address(sp, 1 * wordSize));
 132   for (int i = c_rarg2->encoding(); i <= c_rarg7->encoding(); i += 2) {
 133     Register rm = as_Register(i), rn = as_Register(i+1);
 134     __ ldp(rm, rn, Address(sp, i * wordSize));
 135   }
 136 
 137   __ add(sp, sp, 18 * wordSize);
 138   __ ret(lr);
 139 
 140   return entry;
 141 }
 142 
 143 
 144 //
 145 // Various method entries
 146 //
 147 
 148 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
 149   // rmethod: Method*
 150   // r19_sender_sp: sender sp
 151   // esp: args
 152 
 153   // These don't need a safepoint check because they aren't virtually
 154   // callable. We won't enter these intrinsics from compiled code.
 155   // If in the future we added an intrinsic which was virtually callable
 156   // we'd have to worry about how to safepoint so that this code is used.
 157 
 158   // mathematical functions inlined by compiler
 159   // (interpreter must provide identical implementation
 160   // in order to avoid monotonicity bugs when switching
 161   // from interpreter to compiler in the middle of some
 162   // computation)
 163   //
 164   // stack:
 165   //        [ arg ] <-- esp
 166   //        [ arg ]
 167   // retaddr in lr
 168 
 169   address entry_point = nullptr;
 170   Register continuation = lr;
 171   switch (kind) {
 172   case Interpreter::java_lang_math_abs:
 173     entry_point = __ pc();
 174     __ ldrd(v0, Address(esp));
 175     __ fabsd(v0, v0);
 176     __ mov(sp, r19_sender_sp); // Restore caller's SP
 177     break;
 178   case Interpreter::java_lang_math_sqrt:
 179     entry_point = __ pc();
 180     __ ldrd(v0, Address(esp));
 181     __ fsqrtd(v0, v0);
 182     __ mov(sp, r19_sender_sp);
 183     break;
 184   case Interpreter::java_lang_math_sin :
 185   case Interpreter::java_lang_math_cos :
 186   case Interpreter::java_lang_math_tan :
 187   case Interpreter::java_lang_math_log :
 188   case Interpreter::java_lang_math_log10 :
 189   case Interpreter::java_lang_math_exp :
 190     entry_point = __ pc();
 191     __ ldrd(v0, Address(esp));
 192     __ mov(sp, r19_sender_sp);
 193     __ mov(r23, lr);
 194     continuation = r23;  // The first free callee-saved register
 195     generate_transcendental_entry(kind, 1);
 196     break;
 197   case Interpreter::java_lang_math_pow :
 198     entry_point = __ pc();
 199     __ mov(r23, lr);
 200     continuation = r23;
 201     __ ldrd(v0, Address(esp, 2 * Interpreter::stackElementSize));
 202     __ ldrd(v1, Address(esp));
 203     __ mov(sp, r19_sender_sp);
 204     generate_transcendental_entry(kind, 2);
 205     break;
 206   case Interpreter::java_lang_math_fmaD :
 207     if (UseFMA) {
 208       entry_point = __ pc();
 209       __ ldrd(v0, Address(esp, 4 * Interpreter::stackElementSize));
 210       __ ldrd(v1, Address(esp, 2 * Interpreter::stackElementSize));
 211       __ ldrd(v2, Address(esp));
 212       __ fmaddd(v0, v0, v1, v2);
 213       __ mov(sp, r19_sender_sp); // Restore caller's SP
 214     }
 215     break;
 216   case Interpreter::java_lang_math_fmaF :
 217     if (UseFMA) {
 218       entry_point = __ pc();
 219       __ ldrs(v0, Address(esp, 2 * Interpreter::stackElementSize));
 220       __ ldrs(v1, Address(esp, Interpreter::stackElementSize));
 221       __ ldrs(v2, Address(esp));
 222       __ fmadds(v0, v0, v1, v2);
 223       __ mov(sp, r19_sender_sp); // Restore caller's SP
 224     }
 225     break;
 226   default:
 227     ;
 228   }
 229   if (entry_point) {
 230     __ br(continuation);
 231   }
 232 
 233   return entry_point;
 234 }
 235 
 236   // double trigonometrics and transcendentals
 237   // static jdouble dsin(jdouble x);
 238   // static jdouble dcos(jdouble x);
 239   // static jdouble dtan(jdouble x);
 240   // static jdouble dlog(jdouble x);
 241   // static jdouble dlog10(jdouble x);
 242   // static jdouble dexp(jdouble x);
 243   // static jdouble dpow(jdouble x, jdouble y);
 244 
 245 void TemplateInterpreterGenerator::generate_transcendental_entry(AbstractInterpreter::MethodKind kind, int fpargs) {
 246   address fn;
 247   switch (kind) {
 248   case Interpreter::java_lang_math_sin :
 249     if (StubRoutines::dsin() == nullptr) {
 250       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);
 251     } else {
 252       fn = CAST_FROM_FN_PTR(address, StubRoutines::dsin());
 253     }
 254     break;
 255   case Interpreter::java_lang_math_cos :
 256     if (StubRoutines::dcos() == nullptr) {
 257       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);
 258     } else {
 259       fn = CAST_FROM_FN_PTR(address, StubRoutines::dcos());
 260     }
 261     break;
 262   case Interpreter::java_lang_math_tan :
 263     if (StubRoutines::dtan() == nullptr) {
 264       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);
 265     } else {
 266       fn = CAST_FROM_FN_PTR(address, StubRoutines::dtan());
 267     }
 268     break;
 269   case Interpreter::java_lang_math_log :
 270     if (StubRoutines::dlog() == nullptr) {
 271       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);
 272     } else {
 273       fn = CAST_FROM_FN_PTR(address, StubRoutines::dlog());
 274     }
 275     break;
 276   case Interpreter::java_lang_math_log10 :
 277     if (StubRoutines::dlog10() == nullptr) {
 278       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10);
 279     } else {
 280       fn = CAST_FROM_FN_PTR(address, StubRoutines::dlog10());
 281     }
 282     break;
 283   case Interpreter::java_lang_math_exp :
 284     if (StubRoutines::dexp() == nullptr) {
 285       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);
 286     } else {
 287       fn = CAST_FROM_FN_PTR(address, StubRoutines::dexp());
 288     }
 289     break;
 290   case Interpreter::java_lang_math_pow :
 291     if (StubRoutines::dpow() == nullptr) {
 292       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
 293     } else {
 294       fn = CAST_FROM_FN_PTR(address, StubRoutines::dpow());
 295     }
 296     break;
 297   default:
 298     ShouldNotReachHere();
 299     fn = nullptr;  // unreachable
 300   }
 301   __ mov(rscratch1, fn);
 302   __ blr(rscratch1);
 303 }
 304 
 305 address TemplateInterpreterGenerator::generate_Float_float16ToFloat_entry() {
 306   assert(VM_Version::supports_float16(), "this intrinsic is not supported");
 307   // r19_sender_sp: sender sp
 308   // stack:
 309   //        [ arg ] <-- esp
 310   //        [ arg ]
 311   // retaddr in lr
 312   // result in v0
 313 
 314   address entry_point = __ pc();
 315   __ ldrw(c_rarg0, Address(esp));
 316   __ flt16_to_flt(v0, c_rarg0, v1);
 317   __ mov(sp, r19_sender_sp); // Restore caller's SP
 318   __ br(lr);
 319   return entry_point;
 320 }
 321 
 322 address TemplateInterpreterGenerator::generate_Float_floatToFloat16_entry() {
 323   assert(VM_Version::supports_float16(), "this intrinsic is not supported");
 324   // r19_sender_sp: sender sp
 325   // stack:
 326   //        [ arg ] <-- esp
 327   //        [ arg ]
 328   // retaddr in lr
 329   // result in c_rarg0
 330 
 331   address entry_point = __ pc();
 332   __ ldrs(v0, Address(esp));
 333   __ flt_to_flt16(c_rarg0, v0, v1);
 334   __ mov(sp, r19_sender_sp); // Restore caller's SP
 335   __ br(lr);
 336   return entry_point;
 337 }
 338 
 339 // Abstract method entry
 340 // Attempt to execute abstract method. Throw exception
 341 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
 342   // rmethod: Method*
 343   // r19_sender_sp: sender SP
 344 
 345   address entry_point = __ pc();
 346 
 347   // abstract method entry
 348 
 349   //  pop return address, reset last_sp to null
 350   __ empty_expression_stack();
 351   __ restore_bcp();      // bcp must be correct for exception handler   (was destroyed)
 352   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
 353 
 354   // throw exception
 355   __ call_VM(noreg, CAST_FROM_FN_PTR(address,
 356                                      InterpreterRuntime::throw_AbstractMethodErrorWithMethod),
 357                                      rmethod);
 358   // the call_VM checks for exception, so we should never return here.
 359   __ should_not_reach_here();
 360 
 361   return entry_point;
 362 }
 363 
 364 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
 365   address entry = __ pc();
 366 
 367 #ifdef ASSERT
 368   {
 369     Label L;
 370     __ ldr(rscratch1, Address(rfp,
 371                        frame::interpreter_frame_monitor_block_top_offset *
 372                        wordSize));
 373     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 374     __ mov(rscratch2, sp);
 375     __ cmp(rscratch1, rscratch2); // maximal rsp for current rfp (stack
 376                            // grows negative)
 377     __ br(Assembler::HS, L); // check if frame is complete
 378     __ stop ("interpreter frame not set up");
 379     __ bind(L);
 380   }
 381 #endif // ASSERT
 382   // Restore bcp under the assumption that the current frame is still
 383   // interpreted
 384   __ restore_bcp();
 385 
 386   // expression stack must be empty before entering the VM if an
 387   // exception happened
 388   __ empty_expression_stack();
 389   // throw exception
 390   __ call_VM(noreg,
 391              CAST_FROM_FN_PTR(address,
 392                               InterpreterRuntime::throw_StackOverflowError));
 393   return entry;
 394 }
 395 
 396 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 397   address entry = __ pc();
 398   // expression stack must be empty before entering the VM if an
 399   // exception happened
 400   __ empty_expression_stack();
 401   // setup parameters
 402 
 403   // ??? convention: expect aberrant index in register r1
 404   __ movw(c_rarg2, r1);
 405   // ??? convention: expect array in register r3
 406   __ mov(c_rarg1, r3);
 407   __ call_VM(noreg,
 408              CAST_FROM_FN_PTR(address,
 409                               InterpreterRuntime::
 410                               throw_ArrayIndexOutOfBoundsException),
 411              c_rarg1, c_rarg2);
 412   return entry;
 413 }
 414 
 415 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 416   address entry = __ pc();
 417 
 418   // object is at TOS
 419   __ pop(c_rarg1);
 420 
 421   // expression stack must be empty before entering the VM if an
 422   // exception happened
 423   __ empty_expression_stack();
 424 
 425   __ call_VM(noreg,
 426              CAST_FROM_FN_PTR(address,
 427                               InterpreterRuntime::
 428                               throw_ClassCastException),
 429              c_rarg1);
 430   return entry;
 431 }
 432 
 433 address TemplateInterpreterGenerator::generate_exception_handler_common(
 434         const char* name, const char* message, bool pass_oop) {
 435   assert(!pass_oop || message == nullptr, "either oop or message but not both");
 436   address entry = __ pc();
 437   if (pass_oop) {
 438     // object is at TOS
 439     __ pop(c_rarg2);
 440   }
 441   // expression stack must be empty before entering the VM if an
 442   // exception happened
 443   __ empty_expression_stack();
 444   // setup parameters
 445   __ lea(c_rarg1, Address((address)name));
 446   if (pass_oop) {
 447     __ call_VM(r0, CAST_FROM_FN_PTR(address,
 448                                     InterpreterRuntime::
 449                                     create_klass_exception),
 450                c_rarg1, c_rarg2);
 451   } else {
 452     // kind of lame ExternalAddress can't take null because
 453     // external_word_Relocation will assert.
 454     if (message != nullptr) {
 455       __ lea(c_rarg2, Address((address)message));
 456     } else {
 457       __ mov(c_rarg2, NULL_WORD);
 458     }
 459     __ call_VM(r0,
 460                CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception),
 461                c_rarg1, c_rarg2);
 462   }
 463   // throw exception
 464   __ b(address(Interpreter::throw_exception_entry()));
 465   return entry;
 466 }
 467 
 468 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 469   address entry = __ pc();
 470 
 471   // Restore stack bottom in case i2c adjusted stack
 472   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 473   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 474   // and null it as marker that esp is now tos until next java call
 475   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 476   __ restore_bcp();
 477   __ restore_locals();
 478   __ restore_constant_pool_cache();
 479   __ get_method(rmethod);
 480 
 481   if (state == atos) {
 482     Register obj = r0;
 483     Register mdp = r1;
 484     Register tmp = r2;
 485     __ profile_return_type(mdp, obj, tmp);
 486   }
 487 
 488   const Register cache = r1;
 489   const Register index = r2;
 490 
 491   if (index_size == sizeof(u4)) {
 492     __ load_resolved_indy_entry(cache, index);
 493     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedIndyEntry::num_parameters_offset())));
 494     __ add(esp, esp, cache, Assembler::LSL, 3);
 495   } else {
 496     // Pop N words from the stack
 497     assert(index_size == sizeof(u2), "Can only be u2");
 498     __ load_method_entry(cache, index);
 499     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedMethodEntry::num_parameters_offset())));
 500     __ add(esp, esp, cache, Assembler::LSL, 3);
 501   }
 502 
 503   // Restore machine SP
 504   __ restore_sp_after_call();
 505 
 506   __ check_and_handle_popframe(rthread);
 507   __ check_and_handle_earlyret(rthread);
 508 
 509   __ get_dispatch();
 510   __ dispatch_next(state, step);
 511 
 512   return entry;
 513 }
 514 
 515 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state,
 516                                                                int step,
 517                                                                address continuation) {
 518   address entry = __ pc();
 519   __ restore_bcp();
 520   __ restore_locals();
 521   __ restore_constant_pool_cache();
 522   __ get_method(rmethod);
 523   __ get_dispatch();
 524 
 525   __ restore_sp_after_call();  // Restore SP to extended SP
 526 
 527   // Restore expression stack pointer
 528   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 529   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 530   // null last_sp until next java call
 531   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 532 
 533 #if INCLUDE_JVMCI
 534   // Check if we need to take lock at entry of synchronized method.  This can
 535   // only occur on method entry so emit it only for vtos with step 0.
 536   if (EnableJVMCI && state == vtos && step == 0) {
 537     Label L;
 538     __ ldrb(rscratch1, Address(rthread, JavaThread::pending_monitorenter_offset()));
 539     __ cbz(rscratch1, L);
 540     // Clear flag.
 541     __ strb(zr, Address(rthread, JavaThread::pending_monitorenter_offset()));
 542     // Take lock.
 543     lock_method();
 544     __ bind(L);
 545   } else {
 546 #ifdef ASSERT
 547     if (EnableJVMCI) {
 548       Label L;
 549       __ ldrb(rscratch1, Address(rthread, JavaThread::pending_monitorenter_offset()));
 550       __ cbz(rscratch1, L);
 551       __ stop("unexpected pending monitor in deopt entry");
 552       __ bind(L);
 553     }
 554 #endif
 555   }
 556 #endif
 557   // handle exceptions
 558   {
 559     Label L;
 560     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
 561     __ cbz(rscratch1, L);
 562     __ call_VM(noreg,
 563                CAST_FROM_FN_PTR(address,
 564                                 InterpreterRuntime::throw_pending_exception));
 565     __ should_not_reach_here();
 566     __ bind(L);
 567   }
 568 
 569   if (continuation == nullptr) {
 570     __ dispatch_next(state, step);
 571   } else {
 572     __ jump_to_entry(continuation);
 573   }
 574   return entry;
 575 }
 576 
 577 address TemplateInterpreterGenerator::generate_result_handler_for(
 578         BasicType type) {
 579     address entry = __ pc();
 580   switch (type) {
 581   case T_BOOLEAN: __ c2bool(r0);         break;
 582   case T_CHAR   : __ uxth(r0, r0);       break;
 583   case T_BYTE   : __ sxtb(r0, r0);        break;
 584   case T_SHORT  : __ sxth(r0, r0);        break;
 585   case T_INT    : __ uxtw(r0, r0);        break;  // FIXME: We almost certainly don't need this
 586   case T_LONG   : /* nothing to do */        break;
 587   case T_VOID   : /* nothing to do */        break;
 588   case T_FLOAT  : /* nothing to do */        break;
 589   case T_DOUBLE : /* nothing to do */        break;
 590   case T_OBJECT :
 591     // retrieve result from frame
 592     __ ldr(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
 593     // and verify it
 594     __ verify_oop(r0);
 595     break;
 596   default       : ShouldNotReachHere();
 597   }
 598   __ ret(lr);                                  // return from result handler
 599   return entry;
 600 }
 601 
 602 address TemplateInterpreterGenerator::generate_safept_entry_for(
 603         TosState state,
 604         address runtime_entry) {
 605   address entry = __ pc();
 606   __ push(state);
 607   __ push_cont_fastpath(rthread);
 608   __ call_VM(noreg, runtime_entry);
 609   __ pop_cont_fastpath(rthread);
 610   __ membar(Assembler::AnyAny);
 611   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 612   return entry;
 613 }
 614 
 615 // Helpers for commoning out cases in the various type of method entries.
 616 //
 617 
 618 
 619 // increment invocation count & check for overflow
 620 //
 621 // Note: checking for negative value instead of overflow
 622 //       so we have a 'sticky' overflow test
 623 //
 624 // rmethod: method
 625 //
 626 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 627   Label done;
 628   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 629   int increment = InvocationCounter::count_increment;
 630   Label no_mdo;
 631   if (ProfileInterpreter) {
 632     // Are we profiling?
 633     __ ldr(r0, Address(rmethod, Method::method_data_offset()));
 634     __ cbz(r0, no_mdo);
 635     // Increment counter in the MDO
 636     const Address mdo_invocation_counter(r0, in_bytes(MethodData::invocation_counter_offset()) +
 637                                               in_bytes(InvocationCounter::counter_offset()));
 638     const Address mask(r0, in_bytes(MethodData::invoke_mask_offset()));
 639     __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rscratch1, rscratch2, false, Assembler::EQ, overflow);
 640     __ b(done);
 641   }
 642   __ bind(no_mdo);
 643   // Increment counter in MethodCounters
 644   const Address invocation_counter(rscratch2,
 645                 MethodCounters::invocation_counter_offset() +
 646                 InvocationCounter::counter_offset());
 647   __ get_method_counters(rmethod, rscratch2, done);
 648   const Address mask(rscratch2, in_bytes(MethodCounters::invoke_mask_offset()));
 649   __ increment_mask_and_jump(invocation_counter, increment, mask, rscratch1, r1, false, Assembler::EQ, overflow);
 650   __ bind(done);
 651 }
 652 
 653 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 654 
 655   // Asm interpreter on entry
 656   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 657   // Everything as it was on entry
 658 
 659   // InterpreterRuntime::frequency_counter_overflow takes two
 660   // arguments, the first (thread) is passed by call_VM, the second
 661   // indicates if the counter overflow occurs at a backwards branch
 662   // (null bcp).  We pass zero for it.  The call returns the address
 663   // of the verified entry point for the method or null if the
 664   // compilation did not complete (either went background or bailed
 665   // out).
 666   __ mov(c_rarg1, 0);
 667   __ call_VM(noreg,
 668              CAST_FROM_FN_PTR(address,
 669                               InterpreterRuntime::frequency_counter_overflow),
 670              c_rarg1);
 671 
 672   __ b(do_continue);
 673 }
 674 
 675 // See if we've got enough room on the stack for locals plus overhead
 676 // below JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 677 // without going through the signal handler, i.e., reserved and yellow zones
 678 // will not be made usable. The shadow zone must suffice to handle the
 679 // overflow.
 680 // The expression stack grows down incrementally, so the normal guard
 681 // page mechanism will work for that.
 682 //
 683 // NOTE: Since the additional locals are also always pushed (wasn't
 684 // obvious in generate_method_entry) so the guard should work for them
 685 // too.
 686 //
 687 // Args:
 688 //      r3: number of additional locals this frame needs (what we must check)
 689 //      rmethod: Method*
 690 //
 691 // Kills:
 692 //      r0
 693 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 694 
 695   // monitor entry size: see picture of stack set
 696   // (generate_method_entry) and frame_amd64.hpp
 697   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 698 
 699   // total overhead size: entry_size + (saved rbp through expr stack
 700   // bottom).  be sure to change this if you add/subtract anything
 701   // to/from the overhead area
 702   const int overhead_size =
 703     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 704 
 705   const size_t page_size = os::vm_page_size();
 706 
 707   Label after_frame_check;
 708 
 709   // see if the frame is greater than one page in size. If so,
 710   // then we need to verify there is enough stack space remaining
 711   // for the additional locals.
 712   //
 713   // Note that we use SUBS rather than CMP here because the immediate
 714   // field of this instruction may overflow.  SUBS can cope with this
 715   // because it is a macro that will expand to some number of MOV
 716   // instructions and a register operation.
 717   __ subs(rscratch1, r3, (page_size - overhead_size) / Interpreter::stackElementSize);
 718   __ br(Assembler::LS, after_frame_check);
 719 
 720   // compute rsp as if this were going to be the last frame on
 721   // the stack before the red zone
 722 
 723   // locals + overhead, in bytes
 724   __ mov(r0, overhead_size);
 725   __ add(r0, r0, r3, Assembler::LSL, Interpreter::logStackElementSize);  // 2 slots per parameter.
 726 
 727   const Address stack_limit(rthread, JavaThread::stack_overflow_limit_offset());
 728   __ ldr(rscratch1, stack_limit);
 729 
 730 #ifdef ASSERT
 731   Label limit_okay;
 732   // Verify that thread stack limit is non-zero.
 733   __ cbnz(rscratch1, limit_okay);
 734   __ stop("stack overflow limit is zero");
 735   __ bind(limit_okay);
 736 #endif
 737 
 738   // Add stack limit to locals.
 739   __ add(r0, r0, rscratch1);
 740 
 741   // Check against the current stack bottom.
 742   __ cmp(sp, r0);
 743   __ br(Assembler::HI, after_frame_check);
 744 
 745   // Remove the incoming args, peeling the machine SP back to where it
 746   // was in the caller.  This is not strictly necessary, but unless we
 747   // do so the stack frame may have a garbage FP; this ensures a
 748   // correct call stack that we can always unwind.  The ANDR should be
 749   // unnecessary because the sender SP in r19 is always aligned, but
 750   // it doesn't hurt.
 751   __ andr(sp, r19_sender_sp, -16);
 752 
 753   // Note: the restored frame is not necessarily interpreted.
 754   // Use the shared runtime version of the StackOverflowError.
 755   assert(StubRoutines::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 756   __ far_jump(RuntimeAddress(StubRoutines::throw_StackOverflowError_entry()));
 757 
 758   // all done with frame size check
 759   __ bind(after_frame_check);
 760 }
 761 
 762 // Allocate monitor and lock method (asm interpreter)
 763 //
 764 // Args:
 765 //      rmethod: Method*
 766 //      rlocals: locals
 767 //
 768 // Kills:
 769 //      r0
 770 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 771 //      rscratch1, rscratch2 (scratch regs)
 772 void TemplateInterpreterGenerator::lock_method() {
 773   // synchronize method
 774   const Address access_flags(rmethod, Method::access_flags_offset());
 775   const Address monitor_block_top(
 776         rfp,
 777         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 778   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 779 
 780 #ifdef ASSERT
 781   {
 782     Label L;
 783     __ ldrw(r0, access_flags);
 784     __ tst(r0, JVM_ACC_SYNCHRONIZED);
 785     __ br(Assembler::NE, L);
 786     __ stop("method doesn't need synchronization");
 787     __ bind(L);
 788   }
 789 #endif // ASSERT
 790 
 791   // get synchronization object
 792   {
 793     Label done;
 794     __ ldrw(r0, access_flags);
 795     __ tst(r0, JVM_ACC_STATIC);
 796     // get receiver (assume this is frequent case)
 797     __ ldr(r0, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 798     __ br(Assembler::EQ, done);
 799     __ load_mirror(r0, rmethod, r5, rscratch2);
 800 
 801 #ifdef ASSERT
 802     {
 803       Label L;
 804       __ cbnz(r0, L);
 805       __ stop("synchronization object is null");
 806       __ bind(L);
 807     }
 808 #endif // ASSERT
 809 
 810     __ bind(done);
 811   }
 812 
 813   // add space for monitor & lock
 814   __ check_extended_sp();
 815   __ sub(sp, sp, entry_size); // add space for a monitor entry
 816   __ sub(esp, esp, entry_size);
 817   __ sub(rscratch1, sp, rfp);
 818   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 819   __ str(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 820   __ sub(rscratch1, esp, rfp);
 821   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 822   __ str(rscratch1, monitor_block_top);  // set new monitor block top
 823 
 824   // store object
 825   __ str(r0, Address(esp, BasicObjectLock::obj_offset()));
 826   __ mov(c_rarg1, esp); // object address
 827   __ lock_object(c_rarg1);
 828 }
 829 
 830 // Generate a fixed interpreter frame. This is identical setup for
 831 // interpreted methods and for native methods hence the shared code.
 832 //
 833 // Args:
 834 //      lr: return address
 835 //      rmethod: Method*
 836 //      rlocals: pointer to locals
 837 //      rcpool: cp cache
 838 //      stack_pointer: previous sp
 839 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 840   // initialize fixed part of activation frame
 841   if (native_call) {
 842     __ sub(esp, sp, 14 *  wordSize);
 843     __ mov(rbcp, zr);
 844     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 845     __ stp(rscratch1, zr, Address(__ pre(sp, -14 * wordSize)));
 846     // add 2 zero-initialized slots for native calls
 847     __ stp(zr, zr, Address(sp, 12 * wordSize));
 848   } else {
 849     __ sub(esp, sp, 12 *  wordSize);
 850     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));    // get ConstMethod
 851     __ add(rbcp, rscratch1, in_bytes(ConstMethod::codes_offset())); // get codebase
 852     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 853     __ stp(rscratch1, rbcp, Address(__ pre(sp, -12 * wordSize)));
 854   }
 855 
 856   if (ProfileInterpreter) {
 857     Label method_data_continue;
 858     __ ldr(rscratch1, Address(rmethod, Method::method_data_offset()));
 859     __ cbz(rscratch1, method_data_continue);
 860     __ lea(rscratch1, Address(rscratch1, in_bytes(MethodData::data_offset())));
 861     __ bind(method_data_continue);
 862     __ stp(rscratch1, rmethod, Address(sp, 6 * wordSize));  // save Method* and mdp (method data pointer)
 863   } else {
 864     __ stp(zr, rmethod, Address(sp, 6 * wordSize));         // save Method* (no mdp)
 865   }
 866 
 867   __ protect_return_address();
 868   __ stp(rfp, lr, Address(sp, 10 * wordSize));
 869   __ lea(rfp, Address(sp, 10 * wordSize));
 870 
 871   __ ldr(rcpool, Address(rmethod, Method::const_offset()));
 872   __ ldr(rcpool, Address(rcpool, ConstMethod::constants_offset()));
 873   __ ldr(rcpool, Address(rcpool, ConstantPool::cache_offset()));
 874   __ sub(rscratch1, rlocals, rfp);
 875   __ lsr(rscratch1, rscratch1, Interpreter::logStackElementSize);   // rscratch1 = rlocals - fp();
 876   // Store relativized rlocals, see frame::interpreter_frame_locals().
 877   __ stp(rscratch1, rcpool, Address(sp, 2 * wordSize));
 878 
 879   // set sender sp
 880   // leave last_sp as null
 881   __ stp(zr, r19_sender_sp, Address(sp, 8 * wordSize));
 882 
 883   // Get mirror
 884   __ load_mirror(r10, rmethod, r5, rscratch2);
 885   if (! native_call) {
 886     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));
 887     __ ldrh(rscratch1, Address(rscratch1, ConstMethod::max_stack_offset()));
 888     __ add(rscratch1, rscratch1, MAX2(3, Method::extra_stack_entries()));
 889     __ sub(rscratch1, sp, rscratch1, ext::uxtw, 3);
 890     __ andr(rscratch1, rscratch1, -16);
 891     __ sub(rscratch2, rscratch1, rfp);
 892     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 893     // Store extended SP and mirror
 894     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 895     // Move SP out of the way
 896     __ mov(sp, rscratch1);
 897   } else {
 898     // Make sure there is room for the exception oop pushed in case method throws
 899     // an exception (see TemplateInterpreterGenerator::generate_throw_exception())
 900     __ sub(rscratch1, sp, 2 * wordSize);
 901     __ sub(rscratch2, rscratch1, rfp);
 902     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 903     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 904     __ mov(sp, rscratch1);
 905   }
 906 }
 907 
 908 // End of helpers
 909 
 910 // Various method entries
 911 //------------------------------------------------------------------------------------------------------------------------
 912 //
 913 //
 914 
 915 // Method entry for java.lang.ref.Reference.get.
 916 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 917   // Code: _aload_0, _getfield, _areturn
 918   // parameter size = 1
 919   //
 920   // The code that gets generated by this routine is split into 2 parts:
 921   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 922   //    2. The slow path - which is an expansion of the regular method entry.
 923   //
 924   // Notes:-
 925   // * In the G1 code we do not check whether we need to block for
 926   //   a safepoint. If G1 is enabled then we must execute the specialized
 927   //   code for Reference.get (except when the Reference object is null)
 928   //   so that we can log the value in the referent field with an SATB
 929   //   update buffer.
 930   //   If the code for the getfield template is modified so that the
 931   //   G1 pre-barrier code is executed when the current method is
 932   //   Reference.get() then going through the normal method entry
 933   //   will be fine.
 934   // * The G1 code can, however, check the receiver object (the instance
 935   //   of java.lang.Reference) and jump to the slow path if null. If the
 936   //   Reference object is null then we obviously cannot fetch the referent
 937   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 938   //   regular method entry code to generate the NPE.
 939   //
 940   // This code is based on generate_accessor_entry.
 941   //
 942   // rmethod: Method*
 943   // r19_sender_sp: senderSP must preserve for slow path, set SP to it on fast path
 944 
 945   // LR is live.  It must be saved around calls.
 946 
 947   address entry = __ pc();
 948 
 949   const int referent_offset = java_lang_ref_Reference::referent_offset();
 950 
 951   Label slow_path;
 952   const Register local_0 = c_rarg0;
 953   // Check if local 0 != null
 954   // If the receiver is null then it is OK to jump to the slow path.
 955   __ ldr(local_0, Address(esp, 0));
 956   __ cbz(local_0, slow_path);
 957 
 958   // Load the value of the referent field.
 959   const Address field_address(local_0, referent_offset);
 960   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 961   bs->load_at(_masm, IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT, local_0, field_address, /*tmp1*/ rscratch1, /*tmp2*/ rscratch2);
 962 
 963   // areturn
 964   __ andr(sp, r19_sender_sp, -16);  // done with stack
 965   __ ret(lr);
 966 
 967   // generate a vanilla interpreter entry as the slow path
 968   __ bind(slow_path);
 969   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 970   return entry;
 971 
 972 }
 973 
 974 /**
 975  * Method entry for static native methods:
 976  *   int java.util.zip.CRC32.update(int crc, int b)
 977  */
 978 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
 979   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
 980   address entry = __ pc();
 981 
 982   // rmethod: Method*
 983   // r19_sender_sp: senderSP must preserved for slow path
 984   // esp: args
 985 
 986   Label slow_path;
 987   // If we need a safepoint check, generate full interpreter entry.
 988   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
 989 
 990   // We don't generate local frame and don't align stack because
 991   // we call stub code and there is no safepoint on this path.
 992 
 993   // Load parameters
 994   const Register crc = c_rarg0;  // crc
 995   const Register val = c_rarg1;  // source java byte value
 996   const Register tbl = c_rarg2;  // scratch
 997 
 998   // Arguments are reversed on java expression stack
 999   __ ldrw(val, Address(esp, 0));              // byte value
1000   __ ldrw(crc, Address(esp, wordSize));       // Initial CRC
1001 
1002   uint64_t offset;
1003   __ adrp(tbl, ExternalAddress(StubRoutines::crc_table_addr()), offset);
1004   __ add(tbl, tbl, offset);
1005 
1006   __ mvnw(crc, crc); // ~crc
1007   __ update_byte_crc32(crc, val, tbl);
1008   __ mvnw(crc, crc); // ~crc
1009 
1010   // result in c_rarg0
1011 
1012   __ andr(sp, r19_sender_sp, -16);
1013   __ ret(lr);
1014 
1015   // generate a vanilla native entry as the slow path
1016   __ bind(slow_path);
1017   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1018   return entry;
1019 }
1020 
1021 /**
1022  * Method entry for static native methods:
1023  *   int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len)
1024  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
1025  */
1026 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1027   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1028   address entry = __ pc();
1029 
1030   // rmethod,: Method*
1031   // r19_sender_sp: senderSP must preserved for slow path
1032 
1033   Label slow_path;
1034   // If we need a safepoint check, generate full interpreter entry.
1035   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
1036 
1037   // We don't generate local frame and don't align stack because
1038   // we call stub code and there is no safepoint on this path.
1039 
1040   // Load parameters
1041   const Register crc = c_rarg0;  // crc
1042   const Register buf = c_rarg1;  // source java byte array address
1043   const Register len = c_rarg2;  // length
1044   const Register off = len;      // offset (never overlaps with 'len')
1045 
1046   // Arguments are reversed on java expression stack
1047   // Calculate address of start element
1048   if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) {
1049     __ ldr(buf, Address(esp, 2*wordSize)); // long buf
1050     __ ldrw(off, Address(esp, wordSize)); // offset
1051     __ add(buf, buf, off); // + offset
1052     __ ldrw(crc,   Address(esp, 4*wordSize)); // Initial CRC
1053   } else {
1054     __ ldr(buf, Address(esp, 2*wordSize)); // byte[] array
1055     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1056     __ ldrw(off, Address(esp, wordSize)); // offset
1057     __ add(buf, buf, off); // + offset
1058     __ ldrw(crc,   Address(esp, 3*wordSize)); // Initial CRC
1059   }
1060   // Can now load 'len' since we're finished with 'off'
1061   __ ldrw(len, Address(esp, 0x0)); // Length
1062 
1063   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1064 
1065   // We are frameless so we can just jump to the stub.
1066   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()));
1067 
1068   // generate a vanilla native entry as the slow path
1069   __ bind(slow_path);
1070   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1071   return entry;
1072 }
1073 
1074 /**
1075  * Method entry for intrinsic-candidate (non-native) methods:
1076  *   int java.util.zip.CRC32C.updateBytes(int crc, byte[] b, int off, int end)
1077  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
1078  * Unlike CRC32, CRC32C does not have any methods marked as native
1079  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1080  */
1081 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1082   assert(UseCRC32CIntrinsics, "this intrinsic is not supported");
1083   address entry = __ pc();
1084 
1085   // Prepare jump to stub using parameters from the stack
1086   const Register crc = c_rarg0; // initial crc
1087   const Register buf = c_rarg1; // source java byte array address
1088   const Register len = c_rarg2; // len argument to the kernel
1089 
1090   const Register end = len; // index of last element to process
1091   const Register off = crc; // offset
1092 
1093   __ ldrw(end, Address(esp)); // int end
1094   __ ldrw(off, Address(esp, wordSize)); // int offset
1095   __ sub(len, end, off);
1096   __ ldr(buf, Address(esp, 2*wordSize)); // byte[] buf | long buf
1097   __ add(buf, buf, off); // + offset
1098   if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) {
1099     __ ldrw(crc, Address(esp, 4*wordSize)); // long crc
1100   } else {
1101     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1102     __ ldrw(crc, Address(esp, 3*wordSize)); // long crc
1103   }
1104 
1105   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1106 
1107   // Jump to the stub.
1108   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32C()));
1109 
1110   return entry;
1111 }
1112 
1113 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1114   // See more discussion in stackOverflow.hpp.
1115 
1116   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
1117   const int page_size = (int)os::vm_page_size();
1118   const int n_shadow_pages = shadow_zone_size / page_size;
1119 
1120 #ifdef ASSERT
1121   Label L_good_limit;
1122   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1123   __ cbnz(rscratch1, L_good_limit);
1124   __ stop("shadow zone safe limit is not initialized");
1125   __ bind(L_good_limit);
1126 
1127   Label L_good_watermark;
1128   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1129   __ cbnz(rscratch1, L_good_watermark);
1130   __ stop("shadow zone growth watermark is not initialized");
1131   __ bind(L_good_watermark);
1132 #endif
1133 
1134   Label L_done;
1135 
1136   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1137   __ cmp(sp, rscratch1);
1138   __ br(Assembler::HI, L_done);
1139 
1140   for (int p = 1; p <= n_shadow_pages; p++) {
1141     __ sub(rscratch2, sp, p*page_size);
1142     __ str(zr, Address(rscratch2));
1143   }
1144 
1145   // Record the new watermark, but only if the update is above the safe limit.
1146   // Otherwise, the next time around the check above would pass the safe limit.
1147   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1148   __ cmp(sp, rscratch1);
1149   __ br(Assembler::LS, L_done);
1150   __ mov(rscratch1, sp);
1151   __ str(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1152 
1153   __ bind(L_done);
1154 }
1155 
1156 // Interpreter stub for calling a native method. (asm interpreter)
1157 // This sets up a somewhat different looking stack for calling the
1158 // native method than the typical interpreter frame setup.
1159 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1160   // determine code generation flags
1161   bool inc_counter  = UseCompiler || CountCompiledCalls;
1162 
1163   // r1: Method*
1164   // rscratch1: sender sp
1165 
1166   address entry_point = __ pc();
1167 
1168   const Address constMethod       (rmethod, Method::const_offset());
1169   const Address access_flags      (rmethod, Method::access_flags_offset());
1170   const Address size_of_parameters(r2, ConstMethod::
1171                                        size_of_parameters_offset());
1172 
1173   // get parameter size (always needed)
1174   __ ldr(r2, constMethod);
1175   __ load_unsigned_short(r2, size_of_parameters);
1176 
1177   // Native calls don't need the stack size check since they have no
1178   // expression stack and the arguments are already on the stack and
1179   // we only add a handful of words to the stack.
1180 
1181   // rmethod: Method*
1182   // r2: size of parameters
1183   // rscratch1: sender sp
1184 
1185   // for natives the size of locals is zero
1186 
1187   // compute beginning of parameters (rlocals)
1188   __ add(rlocals, esp, r2, ext::uxtx, 3);
1189   __ add(rlocals, rlocals, -wordSize);
1190 
1191   // Pull SP back to minimum size: this avoids holes in the stack
1192   __ andr(sp, esp, -16);
1193 
1194   // initialize fixed part of activation frame
1195   generate_fixed_frame(true);
1196 
1197   // make sure method is native & not abstract
1198 #ifdef ASSERT
1199   __ ldrw(r0, access_flags);
1200   {
1201     Label L;
1202     __ tst(r0, JVM_ACC_NATIVE);
1203     __ br(Assembler::NE, L);
1204     __ stop("tried to execute non-native method as native");
1205     __ bind(L);
1206   }
1207   {
1208     Label L;
1209     __ tst(r0, JVM_ACC_ABSTRACT);
1210     __ br(Assembler::EQ, L);
1211     __ stop("tried to execute abstract method in interpreter");
1212     __ bind(L);
1213   }
1214 #endif
1215 
1216   // Since at this point in the method invocation the exception
1217   // handler would try to exit the monitor of synchronized methods
1218   // which hasn't been entered yet, we set the thread local variable
1219   // _do_not_unlock_if_synchronized to true. The remove_activation
1220   // will check this flag.
1221 
1222    const Address do_not_unlock_if_synchronized(rthread,
1223         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1224   __ mov(rscratch2, true);
1225   __ strb(rscratch2, do_not_unlock_if_synchronized);
1226 
1227   // increment invocation count & check for overflow
1228   Label invocation_counter_overflow;
1229   if (inc_counter) {
1230     generate_counter_incr(&invocation_counter_overflow);
1231   }
1232 
1233   Label continue_after_compile;
1234   __ bind(continue_after_compile);
1235 
1236   bang_stack_shadow_pages(true);
1237 
1238   // reset the _do_not_unlock_if_synchronized flag
1239   __ strb(zr, do_not_unlock_if_synchronized);
1240 
1241   // check for synchronized methods
1242   // Must happen AFTER invocation_counter check and stack overflow check,
1243   // so method is not locked if overflows.
1244   if (synchronized) {
1245     lock_method();
1246   } else {
1247     // no synchronization necessary
1248 #ifdef ASSERT
1249     {
1250       Label L;
1251       __ ldrw(r0, access_flags);
1252       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1253       __ br(Assembler::EQ, L);
1254       __ stop("method needs synchronization");
1255       __ bind(L);
1256     }
1257 #endif
1258   }
1259 
1260   // start execution
1261 #ifdef ASSERT
1262   {
1263     Label L;
1264     const Address monitor_block_top(rfp,
1265                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1266     __ ldr(rscratch1, monitor_block_top);
1267     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1268     __ cmp(esp, rscratch1);
1269     __ br(Assembler::EQ, L);
1270     __ stop("broken stack frame setup in interpreter 1");
1271     __ bind(L);
1272   }
1273 #endif
1274 
1275   // jvmti support
1276   __ notify_method_entry();
1277 
1278   // work registers
1279   const Register t = r17;
1280   const Register result_handler = r19;
1281 
1282   // allocate space for parameters
1283   __ ldr(t, Address(rmethod, Method::const_offset()));
1284   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
1285 
1286   __ sub(rscratch1, esp, t, ext::uxtx, Interpreter::logStackElementSize);
1287   __ andr(sp, rscratch1, -16);
1288   __ mov(esp, rscratch1);
1289 
1290   // get signature handler
1291   {
1292     Label L;
1293     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1294     __ cbnz(t, L);
1295     __ call_VM(noreg,
1296                CAST_FROM_FN_PTR(address,
1297                                 InterpreterRuntime::prepare_native_call),
1298                rmethod);
1299     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1300     __ bind(L);
1301   }
1302 
1303   // call signature handler
1304   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
1305          "adjust this code");
1306   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == sp,
1307          "adjust this code");
1308   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
1309           "adjust this code");
1310 
1311   // The generated handlers do not touch rmethod (the method).
1312   // However, large signatures cannot be cached and are generated
1313   // each time here.  The slow-path generator can do a GC on return,
1314   // so we must reload it after the call.
1315   __ blr(t);
1316   __ get_method(rmethod);        // slow path can do a GC, reload rmethod
1317 
1318 
1319   // result handler is in r0
1320   // set result handler
1321   __ mov(result_handler, r0);
1322   // pass mirror handle if static call
1323   {
1324     Label L;
1325     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1326     __ tbz(t, exact_log2(JVM_ACC_STATIC), L);
1327     // get mirror
1328     __ load_mirror(t, rmethod, r10, rscratch2);
1329     // copy mirror into activation frame
1330     __ str(t, Address(rfp, frame::interpreter_frame_oop_temp_offset * wordSize));
1331     // pass handle to mirror
1332     __ add(c_rarg1, rfp, frame::interpreter_frame_oop_temp_offset * wordSize);
1333     __ bind(L);
1334   }
1335 
1336   // get native function entry point in r10
1337   {
1338     Label L;
1339     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1340     address unsatisfied = (SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1341     __ mov(rscratch2, unsatisfied);
1342     __ ldr(rscratch2, rscratch2);
1343     __ cmp(r10, rscratch2);
1344     __ br(Assembler::NE, L);
1345     __ call_VM(noreg,
1346                CAST_FROM_FN_PTR(address,
1347                                 InterpreterRuntime::prepare_native_call),
1348                rmethod);
1349     __ get_method(rmethod);
1350     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1351     __ bind(L);
1352   }
1353 
1354   // pass JNIEnv
1355   __ add(c_rarg0, rthread, in_bytes(JavaThread::jni_environment_offset()));
1356 
1357   // Set the last Java PC in the frame anchor to be the return address from
1358   // the call to the native method: this will allow the debugger to
1359   // generate an accurate stack trace.
1360   Label native_return;
1361   __ set_last_Java_frame(esp, rfp, native_return, rscratch1);
1362 
1363   // change thread state
1364 #ifdef ASSERT
1365   {
1366     Label L;
1367     __ ldrw(t, Address(rthread, JavaThread::thread_state_offset()));
1368     __ cmp(t, (u1)_thread_in_Java);
1369     __ br(Assembler::EQ, L);
1370     __ stop("Wrong thread state in native stub");
1371     __ bind(L);
1372   }
1373 #endif
1374 
1375   // Change state to native
1376   __ mov(rscratch1, _thread_in_native);
1377   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1378   __ stlrw(rscratch1, rscratch2);
1379 
1380   // Call the native method.
1381   __ blr(r10);
1382   __ bind(native_return);
1383   __ get_method(rmethod);
1384   // result potentially in r0 or v0
1385 
1386   // Restore cpu control state after JNI call
1387   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
1388 
1389   // make room for the pushes we're about to do
1390   __ sub(rscratch1, esp, 4 * wordSize);
1391   __ andr(sp, rscratch1, -16);
1392 
1393   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
1394   // in order to extract the result of a method call. If the order of these
1395   // pushes change or anything else is added to the stack then the code in
1396   // interpreter_frame_result must also change.
1397   __ push(dtos);
1398   __ push(ltos);
1399 
1400   __ verify_sve_vector_length();
1401 
1402   // change thread state
1403   __ mov(rscratch1, _thread_in_native_trans);
1404   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1405   __ stlrw(rscratch1, rscratch2);
1406 
1407   // Force this write out before the read below
1408   if (!UseSystemMemoryBarrier) {
1409     __ dmb(Assembler::ISH);
1410   }
1411 
1412   // check for safepoint operation in progress and/or pending suspend requests
1413   {
1414     Label L, Continue;
1415 
1416     // We need an acquire here to ensure that any subsequent load of the
1417     // global SafepointSynchronize::_state flag is ordered after this load
1418     // of the thread-local polling word.  We don't want this poll to
1419     // return false (i.e. not safepointing) and a later poll of the global
1420     // SafepointSynchronize::_state spuriously to return true.
1421     //
1422     // This is to avoid a race when we're in a native->Java transition
1423     // racing the code which wakes up from a safepoint.
1424     __ safepoint_poll(L, true /* at_return */, true /* acquire */, false /* in_nmethod */);
1425     __ ldrw(rscratch2, Address(rthread, JavaThread::suspend_flags_offset()));
1426     __ cbz(rscratch2, Continue);
1427     __ bind(L);
1428 
1429     // Don't use call_VM as it will see a possible pending exception
1430     // and forward it and never return here preventing us from
1431     // clearing _last_native_pc down below. So we do a runtime call by
1432     // hand.
1433     //
1434     __ mov(c_rarg0, rthread);
1435     __ mov(rscratch2, CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans));
1436     __ blr(rscratch2);
1437     __ get_method(rmethod);
1438     __ reinit_heapbase();
1439     __ bind(Continue);
1440   }
1441 
1442   // change thread state
1443   __ mov(rscratch1, _thread_in_Java);
1444   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1445   __ stlrw(rscratch1, rscratch2);
1446 
1447   // reset_last_Java_frame
1448   __ reset_last_Java_frame(true);
1449 
1450   if (CheckJNICalls) {
1451     // clear_pending_jni_exception_check
1452     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1453   }
1454 
1455   // reset handle block
1456   __ ldr(t, Address(rthread, JavaThread::active_handles_offset()));
1457   __ str(zr, Address(t, JNIHandleBlock::top_offset()));
1458 
1459   // If result is an oop unbox and store it in frame where gc will see it
1460   // and result handler will pick it up
1461 
1462   {
1463     Label no_oop;
1464     __ adr(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1465     __ cmp(t, result_handler);
1466     __ br(Assembler::NE, no_oop);
1467     // Unbox oop result, e.g. JNIHandles::resolve result.
1468     __ pop(ltos);
1469     __ resolve_jobject(r0, t, rscratch2);
1470     __ str(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
1471     // keep stack depth as expected by pushing oop which will eventually be discarded
1472     __ push(ltos);
1473     __ bind(no_oop);
1474   }
1475 
1476   {
1477     Label no_reguard;
1478     __ lea(rscratch1, Address(rthread, in_bytes(JavaThread::stack_guard_state_offset())));
1479     __ ldrw(rscratch1, Address(rscratch1));
1480     __ cmp(rscratch1, (u1)StackOverflow::stack_guard_yellow_reserved_disabled);
1481     __ br(Assembler::NE, no_reguard);
1482 
1483     __ push_call_clobbered_registers();
1484     __ mov(c_rarg0, rthread);
1485     __ mov(rscratch2, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
1486     __ blr(rscratch2);
1487     __ pop_call_clobbered_registers();
1488 
1489     __ bind(no_reguard);
1490   }
1491 
1492   // The method register is junk from after the thread_in_native transition
1493   // until here.  Also can't call_VM until the bcp has been
1494   // restored.  Need bcp for throwing exception below so get it now.
1495   __ get_method(rmethod);
1496 
1497   // restore bcp to have legal interpreter frame, i.e., bci == 0 <=>
1498   // rbcp == code_base()
1499   __ ldr(rbcp, Address(rmethod, Method::const_offset()));   // get ConstMethod*
1500   __ add(rbcp, rbcp, in_bytes(ConstMethod::codes_offset()));          // get codebase
1501   // handle exceptions (exception handling will handle unlocking!)
1502   {
1503     Label L;
1504     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
1505     __ cbz(rscratch1, L);
1506     // Note: At some point we may want to unify this with the code
1507     // used in call_VM_base(); i.e., we should use the
1508     // StubRoutines::forward_exception code. For now this doesn't work
1509     // here because the rsp is not correctly set at this point.
1510     __ MacroAssembler::call_VM(noreg,
1511                                CAST_FROM_FN_PTR(address,
1512                                InterpreterRuntime::throw_pending_exception));
1513     __ should_not_reach_here();
1514     __ bind(L);
1515   }
1516 
1517   // do unlocking if necessary
1518   {
1519     Label L;
1520     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1521     __ tbz(t, exact_log2(JVM_ACC_SYNCHRONIZED), L);
1522     // the code below should be shared with interpreter macro
1523     // assembler implementation
1524     {
1525       Label unlock;
1526       // BasicObjectLock will be first in list, since this is a
1527       // synchronized method. However, need to check that the object
1528       // has not been unlocked by an explicit monitorexit bytecode.
1529 
1530       // monitor expect in c_rarg1 for slow unlock path
1531       __ lea (c_rarg1, Address(rfp,   // address of first monitor
1532                                (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1533                                           wordSize - sizeof(BasicObjectLock))));
1534 
1535       __ ldr(t, Address(c_rarg1, BasicObjectLock::obj_offset()));
1536       __ cbnz(t, unlock);
1537 
1538       // Entry already unlocked, need to throw exception
1539       __ MacroAssembler::call_VM(noreg,
1540                                  CAST_FROM_FN_PTR(address,
1541                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1542       __ should_not_reach_here();
1543 
1544       __ bind(unlock);
1545       __ unlock_object(c_rarg1);
1546     }
1547     __ bind(L);
1548   }
1549 
1550   // jvmti support
1551   // Note: This must happen _after_ handling/throwing any exceptions since
1552   //       the exception handler code notifies the runtime of method exits
1553   //       too. If this happens before, method entry/exit notifications are
1554   //       not properly paired (was bug - gri 11/22/99).
1555   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1556 
1557   // restore potential result in r0:d0, call result handler to
1558   // restore potential result in ST0 & handle result
1559 
1560   __ pop(ltos);
1561   __ pop(dtos);
1562 
1563   __ blr(result_handler);
1564 
1565   // remove activation
1566   __ ldr(esp, Address(rfp,
1567                     frame::interpreter_frame_sender_sp_offset *
1568                     wordSize)); // get sender sp
1569   // remove frame anchor
1570   __ leave();
1571 
1572   // restore sender sp
1573   __ mov(sp, esp);
1574 
1575   __ ret(lr);
1576 
1577   if (inc_counter) {
1578     // Handle overflow of counter and compile method
1579     __ bind(invocation_counter_overflow);
1580     generate_counter_overflow(continue_after_compile);
1581   }
1582 
1583   return entry_point;
1584 }
1585 
1586 //
1587 // Generic interpreted method entry to (asm) interpreter
1588 //
1589 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1590   // determine code generation flags
1591   bool inc_counter  = UseCompiler || CountCompiledCalls;
1592 
1593   // rscratch1: sender sp
1594   address entry_point = __ pc();
1595 
1596   const Address constMethod(rmethod, Method::const_offset());
1597   const Address access_flags(rmethod, Method::access_flags_offset());
1598   const Address size_of_parameters(r3,
1599                                    ConstMethod::size_of_parameters_offset());
1600   const Address size_of_locals(r3, ConstMethod::size_of_locals_offset());
1601 
1602   // get parameter size (always needed)
1603   // need to load the const method first
1604   __ ldr(r3, constMethod);
1605   __ load_unsigned_short(r2, size_of_parameters);
1606 
1607   // r2: size of parameters
1608 
1609   __ load_unsigned_short(r3, size_of_locals); // get size of locals in words
1610   __ sub(r3, r3, r2); // r3 = no. of additional locals
1611 
1612   // see if we've got enough room on the stack for locals plus overhead.
1613   generate_stack_overflow_check();
1614 
1615   // compute beginning of parameters (rlocals)
1616   __ add(rlocals, esp, r2, ext::uxtx, 3);
1617   __ sub(rlocals, rlocals, wordSize);
1618 
1619   __ mov(rscratch1, esp);
1620 
1621   // r3 - # of additional locals
1622   // allocate space for locals
1623   // explicitly initialize locals
1624   // Initializing memory allocated for locals in the same direction as
1625   // the stack grows to ensure page initialization order according
1626   // to windows-aarch64 stack page growth requirement (see
1627   // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-160#stack)
1628   {
1629     Label exit, loop;
1630     __ ands(zr, r3, r3);
1631     __ br(Assembler::LE, exit); // do nothing if r3 <= 0
1632     __ bind(loop);
1633     __ str(zr, Address(__ pre(rscratch1, -wordSize)));
1634     __ sub(r3, r3, 1); // until everything initialized
1635     __ cbnz(r3, loop);
1636     __ bind(exit);
1637   }
1638 
1639   // Padding between locals and fixed part of activation frame to ensure
1640   // SP is always 16-byte aligned.
1641   __ andr(sp, rscratch1, -16);
1642 
1643   // And the base dispatch table
1644   __ get_dispatch();
1645 
1646   // initialize fixed part of activation frame
1647   generate_fixed_frame(false);
1648 
1649   // make sure method is not native & not abstract
1650 #ifdef ASSERT
1651   __ ldrw(r0, access_flags);
1652   {
1653     Label L;
1654     __ tst(r0, JVM_ACC_NATIVE);
1655     __ br(Assembler::EQ, L);
1656     __ stop("tried to execute native method as non-native");
1657     __ bind(L);
1658   }
1659  {
1660     Label L;
1661     __ tst(r0, JVM_ACC_ABSTRACT);
1662     __ br(Assembler::EQ, L);
1663     __ stop("tried to execute abstract method in interpreter");
1664     __ bind(L);
1665   }
1666 #endif
1667 
1668   // Since at this point in the method invocation the exception
1669   // handler would try to exit the monitor of synchronized methods
1670   // which hasn't been entered yet, we set the thread local variable
1671   // _do_not_unlock_if_synchronized to true. The remove_activation
1672   // will check this flag.
1673 
1674    const Address do_not_unlock_if_synchronized(rthread,
1675         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1676   __ mov(rscratch2, true);
1677   __ strb(rscratch2, do_not_unlock_if_synchronized);
1678 
1679   Register mdp = r3;
1680   __ profile_parameters_type(mdp, r1, r2);
1681 
1682   // increment invocation count & check for overflow
1683   Label invocation_counter_overflow;
1684   if (inc_counter) {
1685     generate_counter_incr(&invocation_counter_overflow);
1686   }
1687 
1688   Label continue_after_compile;
1689   __ bind(continue_after_compile);
1690 
1691   bang_stack_shadow_pages(false);
1692 
1693   // reset the _do_not_unlock_if_synchronized flag
1694   __ strb(zr, do_not_unlock_if_synchronized);
1695 
1696   // check for synchronized methods
1697   // Must happen AFTER invocation_counter check and stack overflow check,
1698   // so method is not locked if overflows.
1699   if (synchronized) {
1700     // Allocate monitor and lock method
1701     lock_method();
1702   } else {
1703     // no synchronization necessary
1704 #ifdef ASSERT
1705     {
1706       Label L;
1707       __ ldrw(r0, access_flags);
1708       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1709       __ br(Assembler::EQ, L);
1710       __ stop("method needs synchronization");
1711       __ bind(L);
1712     }
1713 #endif
1714   }
1715 
1716   // start execution
1717 #ifdef ASSERT
1718   {
1719     Label L;
1720      const Address monitor_block_top (rfp,
1721                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1722     __ ldr(rscratch1, monitor_block_top);
1723     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1724     __ cmp(esp, rscratch1);
1725     __ br(Assembler::EQ, L);
1726     __ stop("broken stack frame setup in interpreter 2");
1727     __ bind(L);
1728   }
1729 #endif
1730 
1731   // jvmti support
1732   __ notify_method_entry();
1733 
1734   __ dispatch_next(vtos);
1735 
1736   // invocation counter overflow
1737   if (inc_counter) {
1738     // Handle overflow of counter and compile method
1739     __ bind(invocation_counter_overflow);
1740     generate_counter_overflow(continue_after_compile);
1741   }
1742 
1743   return entry_point;
1744 }
1745 
1746 // Method entry for java.lang.Thread.currentThread
1747 address TemplateInterpreterGenerator::generate_currentThread() {
1748   address entry_point = __ pc();
1749 
1750   __ ldr(r0, Address(rthread, JavaThread::vthread_offset()));
1751   __ resolve_oop_handle(r0, rscratch1, rscratch2);
1752   __ ret(lr);
1753 
1754   return entry_point;
1755 }
1756 
1757 // Not supported
1758 address TemplateInterpreterGenerator::generate_Float_intBitsToFloat_entry() { return nullptr; }
1759 address TemplateInterpreterGenerator::generate_Float_floatToRawIntBits_entry() { return nullptr; }
1760 address TemplateInterpreterGenerator::generate_Double_longBitsToDouble_entry() { return nullptr; }
1761 address TemplateInterpreterGenerator::generate_Double_doubleToRawLongBits_entry() { return nullptr; }
1762 
1763 //-----------------------------------------------------------------------------
1764 // Exceptions
1765 
1766 void TemplateInterpreterGenerator::generate_throw_exception() {
1767   // Entry point in previous activation (i.e., if the caller was
1768   // interpreted)
1769   Interpreter::_rethrow_exception_entry = __ pc();
1770   // Restore sp to interpreter_frame_last_sp even though we are going
1771   // to empty the expression stack for the exception processing.
1772   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1773   // r0: exception
1774   // r3: return address/pc that threw exception
1775   __ restore_bcp();    // rbcp points to call/send
1776   __ restore_locals();
1777   __ restore_constant_pool_cache();
1778   __ reinit_heapbase();  // restore rheapbase as heapbase.
1779   __ get_dispatch();
1780 
1781   // Entry point for exceptions thrown within interpreter code
1782   Interpreter::_throw_exception_entry = __ pc();
1783   // If we came here via a NullPointerException on the receiver of a
1784   // method, rmethod may be corrupt.
1785   __ get_method(rmethod);
1786   // expression stack is undefined here
1787   // r0: exception
1788   // rbcp: exception bcp
1789   __ verify_oop(r0);
1790   __ mov(c_rarg1, r0);
1791 
1792   // expression stack must be empty before entering the VM in case of
1793   // an exception
1794   __ empty_expression_stack();
1795   // find exception handler address and preserve exception oop
1796   __ call_VM(r3,
1797              CAST_FROM_FN_PTR(address,
1798                           InterpreterRuntime::exception_handler_for_exception),
1799              c_rarg1);
1800 
1801   // Restore machine SP
1802   __ restore_sp_after_call();
1803 
1804   // r0: exception handler entry point
1805   // r3: preserved exception oop
1806   // rbcp: bcp for exception handler
1807   __ push_ptr(r3); // push exception which is now the only value on the stack
1808   __ br(r0); // jump to exception handler (may be _remove_activation_entry!)
1809 
1810   // If the exception is not handled in the current frame the frame is
1811   // removed and the exception is rethrown (i.e. exception
1812   // continuation is _rethrow_exception).
1813   //
1814   // Note: At this point the bci is still the bxi for the instruction
1815   // which caused the exception and the expression stack is
1816   // empty. Thus, for any VM calls at this point, GC will find a legal
1817   // oop map (with empty expression stack).
1818 
1819   //
1820   // JVMTI PopFrame support
1821   //
1822 
1823   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1824   __ empty_expression_stack();
1825   // Set the popframe_processing bit in pending_popframe_condition
1826   // indicating that we are currently handling popframe, so that
1827   // call_VMs that may happen later do not trigger new popframe
1828   // handling cycles.
1829   __ ldrw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1830   __ orr(r3, r3, JavaThread::popframe_processing_bit);
1831   __ strw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1832 
1833   {
1834     // Check to see whether we are returning to a deoptimized frame.
1835     // (The PopFrame call ensures that the caller of the popped frame is
1836     // either interpreted or compiled and deoptimizes it if compiled.)
1837     // In this case, we can't call dispatch_next() after the frame is
1838     // popped, but instead must save the incoming arguments and restore
1839     // them after deoptimization has occurred.
1840     //
1841     // Note that we don't compare the return PC against the
1842     // deoptimization blob's unpack entry because of the presence of
1843     // adapter frames in C2.
1844     Label caller_not_deoptimized;
1845     __ ldr(c_rarg1, Address(rfp, frame::return_addr_offset * wordSize));
1846     // This is a return address, so requires authenticating for PAC.
1847     __ authenticate_return_address(c_rarg1);
1848     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1849                                InterpreterRuntime::interpreter_contains), c_rarg1);
1850     __ cbnz(r0, caller_not_deoptimized);
1851 
1852     // Compute size of arguments for saving when returning to
1853     // deoptimized caller
1854     __ get_method(r0);
1855     __ ldr(r0, Address(r0, Method::const_offset()));
1856     __ load_unsigned_short(r0, Address(r0, in_bytes(ConstMethod::
1857                                                     size_of_parameters_offset())));
1858     __ lsl(r0, r0, Interpreter::logStackElementSize);
1859     __ restore_locals(); // XXX do we need this?
1860     __ sub(rlocals, rlocals, r0);
1861     __ add(rlocals, rlocals, wordSize);
1862     // Save these arguments
1863     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1864                                            Deoptimization::
1865                                            popframe_preserve_args),
1866                           rthread, r0, rlocals);
1867 
1868     __ remove_activation(vtos,
1869                          /* throw_monitor_exception */ false,
1870                          /* install_monitor_exception */ false,
1871                          /* notify_jvmdi */ false);
1872 
1873     // Inform deoptimization that it is responsible for restoring
1874     // these arguments
1875     __ mov(rscratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1876     __ strw(rscratch1, Address(rthread, JavaThread::popframe_condition_offset()));
1877 
1878     // Continue in deoptimization handler
1879     __ ret(lr);
1880 
1881     __ bind(caller_not_deoptimized);
1882   }
1883 
1884   __ remove_activation(vtos,
1885                        /* throw_monitor_exception */ false,
1886                        /* install_monitor_exception */ false,
1887                        /* notify_jvmdi */ false);
1888 
1889   // Restore the last_sp and null it out
1890   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1891   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1892   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1893 
1894   __ restore_bcp();
1895   __ restore_locals();
1896   __ restore_constant_pool_cache();
1897   __ get_method(rmethod);
1898   __ get_dispatch();
1899 
1900   // The method data pointer was incremented already during
1901   // call profiling. We have to restore the mdp for the current bcp.
1902   if (ProfileInterpreter) {
1903     __ set_method_data_pointer_for_bcp();
1904   }
1905 
1906   // Clear the popframe condition flag
1907   __ strw(zr, Address(rthread, JavaThread::popframe_condition_offset()));
1908   assert(JavaThread::popframe_inactive == 0, "fix popframe_inactive");
1909 
1910 #if INCLUDE_JVMTI
1911   {
1912     Label L_done;
1913 
1914     __ ldrb(rscratch1, Address(rbcp, 0));
1915     __ cmpw(rscratch1, Bytecodes::_invokestatic);
1916     __ br(Assembler::NE, L_done);
1917 
1918     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1919     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1920 
1921     __ ldr(c_rarg0, Address(rlocals, 0));
1922     __ call_VM(r0, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), c_rarg0, rmethod, rbcp);
1923 
1924     __ cbz(r0, L_done);
1925 
1926     __ str(r0, Address(esp, 0));
1927     __ bind(L_done);
1928   }
1929 #endif // INCLUDE_JVMTI
1930 
1931   // Restore machine SP
1932   __ restore_sp_after_call();
1933 
1934   __ dispatch_next(vtos);
1935   // end of PopFrame support
1936 
1937   Interpreter::_remove_activation_entry = __ pc();
1938 
1939   // preserve exception over this code sequence
1940   __ pop_ptr(r0);
1941   __ str(r0, Address(rthread, JavaThread::vm_result_offset()));
1942   // remove the activation (without doing throws on illegalMonitorExceptions)
1943   __ remove_activation(vtos, false, true, false);
1944   // restore exception
1945   __ get_vm_result(r0, rthread);
1946 
1947   // In between activations - previous activation type unknown yet
1948   // compute continuation point - the continuation point expects the
1949   // following registers set up:
1950   //
1951   // r0: exception
1952   // lr: return address/pc that threw exception
1953   // esp: expression stack of caller
1954   // rfp: fp of caller
1955   __ stp(r0, lr, Address(__ pre(sp, -2 * wordSize)));  // save exception & return address
1956   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1957                           SharedRuntime::exception_handler_for_return_address),
1958                         rthread, lr);
1959   __ mov(r1, r0);                               // save exception handler
1960   __ ldp(r0, lr, Address(__ post(sp, 2 * wordSize)));  // restore exception & return address
1961   // We might be returning to a deopt handler that expects r3 to
1962   // contain the exception pc
1963   __ mov(r3, lr);
1964   // Note that an "issuing PC" is actually the next PC after the call
1965   __ br(r1);                                    // jump to exception
1966                                                 // handler of caller
1967 }
1968 
1969 
1970 //
1971 // JVMTI ForceEarlyReturn support
1972 //
1973 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1974   address entry = __ pc();
1975 
1976   __ restore_bcp();
1977   __ restore_locals();
1978   __ empty_expression_stack();
1979   __ load_earlyret_value(state);
1980 
1981   __ ldr(rscratch1, Address(rthread, JavaThread::jvmti_thread_state_offset()));
1982   Address cond_addr(rscratch1, JvmtiThreadState::earlyret_state_offset());
1983 
1984   // Clear the earlyret state
1985   assert(JvmtiThreadState::earlyret_inactive == 0, "should be");
1986   __ str(zr, cond_addr);
1987 
1988   __ remove_activation(state,
1989                        false, /* throw_monitor_exception */
1990                        false, /* install_monitor_exception */
1991                        true); /* notify_jvmdi */
1992   __ ret(lr);
1993 
1994   return entry;
1995 } // end of ForceEarlyReturn support
1996 
1997 
1998 
1999 //-----------------------------------------------------------------------------
2000 // Helper for vtos entry point generation
2001 
2002 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2003                                                          address& bep,
2004                                                          address& cep,
2005                                                          address& sep,
2006                                                          address& aep,
2007                                                          address& iep,
2008                                                          address& lep,
2009                                                          address& fep,
2010                                                          address& dep,
2011                                                          address& vep) {
2012   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2013   Label L;
2014   aep = __ pc();  __ push_ptr();  __ b(L);
2015   fep = __ pc();  __ push_f();    __ b(L);
2016   dep = __ pc();  __ push_d();    __ b(L);
2017   lep = __ pc();  __ push_l();    __ b(L);
2018   bep = cep = sep =
2019   iep = __ pc();  __ push_i();
2020   vep = __ pc();
2021   __ bind(L);
2022   generate_and_dispatch(t);
2023 }
2024 
2025 //-----------------------------------------------------------------------------
2026 
2027 // Non-product code
2028 #ifndef PRODUCT
2029 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2030   address entry = __ pc();
2031 
2032   __ protect_return_address();
2033   __ push(lr);
2034   __ push(state);
2035   __ push(RegSet::range(r0, r15), sp);
2036   __ mov(c_rarg2, r0);  // Pass itos
2037   __ call_VM(noreg,
2038              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
2039              c_rarg1, c_rarg2, c_rarg3);
2040   __ pop(RegSet::range(r0, r15), sp);
2041   __ pop(state);
2042   __ pop(lr);
2043   __ authenticate_return_address();
2044   __ ret(lr);                                   // return from result handler
2045 
2046   return entry;
2047 }
2048 
2049 void TemplateInterpreterGenerator::count_bytecode() {
2050   __ mov(r10, (address) &BytecodeCounter::_counter_value);
2051   __ atomic_addw(noreg, 1, r10);
2052 }
2053 
2054 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2055   __ mov(r10, (address) &BytecodeHistogram::_counters[t->bytecode()]);
2056   __ atomic_addw(noreg, 1, r10);
2057 }
2058 
2059 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2060   // Calculate new index for counter:
2061   //   _index = (_index >> log2_number_of_codes) |
2062   //            (bytecode << log2_number_of_codes);
2063   Register index_addr = rscratch1;
2064   Register index = rscratch2;
2065   __ mov(index_addr, (address) &BytecodePairHistogram::_index);
2066   __ ldrw(index, index_addr);
2067   __ mov(r10,
2068          ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2069   __ orrw(index, r10, index, Assembler::LSR,
2070           BytecodePairHistogram::log2_number_of_codes);
2071   __ strw(index, index_addr);
2072 
2073   // Bump bucket contents:
2074   //   _counters[_index] ++;
2075   Register counter_addr = rscratch1;
2076   __ mov(r10, (address) &BytecodePairHistogram::_counters);
2077   __ lea(counter_addr, Address(r10, index, Address::lsl(LogBytesPerInt)));
2078   __ atomic_addw(noreg, 1, counter_addr);
2079 }
2080 
2081 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2082   // Call a little run-time stub to avoid blow-up for each bytecode.
2083   // The run-time runtime saves the right registers, depending on
2084   // the tosca in-state for the given template.
2085 
2086   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
2087          "entry must have been generated");
2088   __ bl(Interpreter::trace_code(t->tos_in()));
2089   __ reinit_heapbase();
2090 }
2091 
2092 
2093 void TemplateInterpreterGenerator::stop_interpreter_at() {
2094   Label L;
2095   __ push(rscratch1);
2096   __ mov(rscratch1, (address) &BytecodeCounter::_counter_value);
2097   __ ldr(rscratch1, Address(rscratch1));
2098   __ mov(rscratch2, StopInterpreterAt);
2099   __ cmpw(rscratch1, rscratch2);
2100   __ br(Assembler::NE, L);
2101   __ brk(0);
2102   __ bind(L);
2103   __ pop(rscratch1);
2104 }
2105 
2106 #endif // !PRODUCT