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 address TemplateInterpreterGenerator::generate_cont_resume_interpreter_adapter() {
 616   if (!Continuations::enabled()) return nullptr;
 617   address start = __ pc();
 618 
 619   // Restore rfp first since we need it to restore rest of registers
 620   __ leave();
 621 
 622   // Restore constant pool cache
 623   __ ldr(rcpool, Address(rfp, frame::interpreter_frame_cache_offset * wordSize));
 624 
 625   // Restore Java expression stack pointer
 626   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 627   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 628   // and NULL it as marker that esp is now tos until next java call
 629   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 630 
 631   // Restore machine SP
 632   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 633   __ lea(sp, Address(rfp, rscratch1, Address::lsl(LogBytesPerWord)));
 634 
 635   // Prepare for adjustment on return to call_VM_leaf_base()
 636   __ ldr(rmethod, Address(rfp, frame::interpreter_frame_method_offset * wordSize));
 637   __ stp(rscratch1, rmethod, Address(__ pre(sp, -2 * wordSize)));
 638 
 639   // Restore dispatch
 640   uint64_t offset;
 641   __ adrp(rdispatch, ExternalAddress((address)Interpreter::dispatch_table()), offset);
 642   __ add(rdispatch, rdispatch, offset);
 643 
 644   __ ret(lr);
 645 
 646   return start;
 647 }
 648 
 649 
 650 // Helpers for commoning out cases in the various type of method entries.
 651 //
 652 
 653 
 654 // increment invocation count & check for overflow
 655 //
 656 // Note: checking for negative value instead of overflow
 657 //       so we have a 'sticky' overflow test
 658 //
 659 // rmethod: method
 660 //
 661 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 662   Label done;
 663   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 664   int increment = InvocationCounter::count_increment;
 665   Label no_mdo;
 666   if (ProfileInterpreter) {
 667     // Are we profiling?
 668     __ ldr(r0, Address(rmethod, Method::method_data_offset()));
 669     __ cbz(r0, no_mdo);
 670     // Increment counter in the MDO
 671     const Address mdo_invocation_counter(r0, in_bytes(MethodData::invocation_counter_offset()) +
 672                                               in_bytes(InvocationCounter::counter_offset()));
 673     const Address mask(r0, in_bytes(MethodData::invoke_mask_offset()));
 674     __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rscratch1, rscratch2, false, Assembler::EQ, overflow);
 675     __ b(done);
 676   }
 677   __ bind(no_mdo);
 678   // Increment counter in MethodCounters
 679   const Address invocation_counter(rscratch2,
 680                 MethodCounters::invocation_counter_offset() +
 681                 InvocationCounter::counter_offset());
 682   __ get_method_counters(rmethod, rscratch2, done);
 683   const Address mask(rscratch2, in_bytes(MethodCounters::invoke_mask_offset()));
 684   __ increment_mask_and_jump(invocation_counter, increment, mask, rscratch1, r1, false, Assembler::EQ, overflow);
 685   __ bind(done);
 686 }
 687 
 688 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 689 
 690   // Asm interpreter on entry
 691   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 692   // Everything as it was on entry
 693 
 694   // InterpreterRuntime::frequency_counter_overflow takes two
 695   // arguments, the first (thread) is passed by call_VM, the second
 696   // indicates if the counter overflow occurs at a backwards branch
 697   // (null bcp).  We pass zero for it.  The call returns the address
 698   // of the verified entry point for the method or null if the
 699   // compilation did not complete (either went background or bailed
 700   // out).
 701   __ mov(c_rarg1, 0);
 702   __ call_VM(noreg,
 703              CAST_FROM_FN_PTR(address,
 704                               InterpreterRuntime::frequency_counter_overflow),
 705              c_rarg1);
 706 
 707   __ b(do_continue);
 708 }
 709 
 710 // See if we've got enough room on the stack for locals plus overhead
 711 // below JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 712 // without going through the signal handler, i.e., reserved and yellow zones
 713 // will not be made usable. The shadow zone must suffice to handle the
 714 // overflow.
 715 // The expression stack grows down incrementally, so the normal guard
 716 // page mechanism will work for that.
 717 //
 718 // NOTE: Since the additional locals are also always pushed (wasn't
 719 // obvious in generate_method_entry) so the guard should work for them
 720 // too.
 721 //
 722 // Args:
 723 //      r3: number of additional locals this frame needs (what we must check)
 724 //      rmethod: Method*
 725 //
 726 // Kills:
 727 //      r0
 728 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 729 
 730   // monitor entry size: see picture of stack set
 731   // (generate_method_entry) and frame_amd64.hpp
 732   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 733 
 734   // total overhead size: entry_size + (saved rbp through expr stack
 735   // bottom).  be sure to change this if you add/subtract anything
 736   // to/from the overhead area
 737   const int overhead_size =
 738     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 739 
 740   const size_t page_size = os::vm_page_size();
 741 
 742   Label after_frame_check;
 743 
 744   // see if the frame is greater than one page in size. If so,
 745   // then we need to verify there is enough stack space remaining
 746   // for the additional locals.
 747   //
 748   // Note that we use SUBS rather than CMP here because the immediate
 749   // field of this instruction may overflow.  SUBS can cope with this
 750   // because it is a macro that will expand to some number of MOV
 751   // instructions and a register operation.
 752   __ subs(rscratch1, r3, (page_size - overhead_size) / Interpreter::stackElementSize);
 753   __ br(Assembler::LS, after_frame_check);
 754 
 755   // compute rsp as if this were going to be the last frame on
 756   // the stack before the red zone
 757 
 758   // locals + overhead, in bytes
 759   __ mov(r0, overhead_size);
 760   __ add(r0, r0, r3, Assembler::LSL, Interpreter::logStackElementSize);  // 2 slots per parameter.
 761 
 762   const Address stack_limit(rthread, JavaThread::stack_overflow_limit_offset());
 763   __ ldr(rscratch1, stack_limit);
 764 
 765 #ifdef ASSERT
 766   Label limit_okay;
 767   // Verify that thread stack limit is non-zero.
 768   __ cbnz(rscratch1, limit_okay);
 769   __ stop("stack overflow limit is zero");
 770   __ bind(limit_okay);
 771 #endif
 772 
 773   // Add stack limit to locals.
 774   __ add(r0, r0, rscratch1);
 775 
 776   // Check against the current stack bottom.
 777   __ cmp(sp, r0);
 778   __ br(Assembler::HI, after_frame_check);
 779 
 780   // Remove the incoming args, peeling the machine SP back to where it
 781   // was in the caller.  This is not strictly necessary, but unless we
 782   // do so the stack frame may have a garbage FP; this ensures a
 783   // correct call stack that we can always unwind.  The ANDR should be
 784   // unnecessary because the sender SP in r19 is always aligned, but
 785   // it doesn't hurt.
 786   __ andr(sp, r19_sender_sp, -16);
 787 
 788   // Note: the restored frame is not necessarily interpreted.
 789   // Use the shared runtime version of the StackOverflowError.
 790   assert(StubRoutines::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 791   __ far_jump(RuntimeAddress(StubRoutines::throw_StackOverflowError_entry()));
 792 
 793   // all done with frame size check
 794   __ bind(after_frame_check);
 795 }
 796 
 797 // Allocate monitor and lock method (asm interpreter)
 798 //
 799 // Args:
 800 //      rmethod: Method*
 801 //      rlocals: locals
 802 //
 803 // Kills:
 804 //      r0
 805 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 806 //      rscratch1, rscratch2 (scratch regs)
 807 void TemplateInterpreterGenerator::lock_method() {
 808   // synchronize method
 809   const Address access_flags(rmethod, Method::access_flags_offset());
 810   const Address monitor_block_top(
 811         rfp,
 812         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 813   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 814 
 815 #ifdef ASSERT
 816   {
 817     Label L;
 818     __ ldrw(r0, access_flags);
 819     __ tst(r0, JVM_ACC_SYNCHRONIZED);
 820     __ br(Assembler::NE, L);
 821     __ stop("method doesn't need synchronization");
 822     __ bind(L);
 823   }
 824 #endif // ASSERT
 825 
 826   // get synchronization object
 827   {
 828     Label done;
 829     __ ldrw(r0, access_flags);
 830     __ tst(r0, JVM_ACC_STATIC);
 831     // get receiver (assume this is frequent case)
 832     __ ldr(r0, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 833     __ br(Assembler::EQ, done);
 834     __ load_mirror(r0, rmethod, r5, rscratch2);
 835 
 836 #ifdef ASSERT
 837     {
 838       Label L;
 839       __ cbnz(r0, L);
 840       __ stop("synchronization object is null");
 841       __ bind(L);
 842     }
 843 #endif // ASSERT
 844 
 845     __ bind(done);
 846   }
 847 
 848   // add space for monitor & lock
 849   __ check_extended_sp();
 850   __ sub(sp, sp, entry_size); // add space for a monitor entry
 851   __ sub(esp, esp, entry_size);
 852   __ sub(rscratch1, sp, rfp);
 853   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 854   __ str(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 855   __ sub(rscratch1, esp, rfp);
 856   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 857   __ str(rscratch1, monitor_block_top);  // set new monitor block top
 858 
 859   // store object
 860   __ str(r0, Address(esp, BasicObjectLock::obj_offset()));
 861   __ mov(c_rarg1, esp); // object address
 862   __ lock_object(c_rarg1);
 863 }
 864 
 865 // Generate a fixed interpreter frame. This is identical setup for
 866 // interpreted methods and for native methods hence the shared code.
 867 //
 868 // Args:
 869 //      lr: return address
 870 //      rmethod: Method*
 871 //      rlocals: pointer to locals
 872 //      rcpool: cp cache
 873 //      stack_pointer: previous sp
 874 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 875   // initialize fixed part of activation frame
 876   if (native_call) {
 877     __ sub(esp, sp, 14 *  wordSize);
 878     __ mov(rbcp, zr);
 879     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 880     __ stp(rscratch1, zr, Address(__ pre(sp, -14 * wordSize)));
 881     // add 2 zero-initialized slots for native calls
 882     __ stp(zr, zr, Address(sp, 12 * wordSize));
 883   } else {
 884     __ sub(esp, sp, 12 *  wordSize);
 885     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));    // get ConstMethod
 886     __ add(rbcp, rscratch1, in_bytes(ConstMethod::codes_offset())); // get codebase
 887     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 888     __ stp(rscratch1, rbcp, Address(__ pre(sp, -12 * wordSize)));
 889   }
 890 
 891   if (ProfileInterpreter) {
 892     Label method_data_continue;
 893     __ ldr(rscratch1, Address(rmethod, Method::method_data_offset()));
 894     __ cbz(rscratch1, method_data_continue);
 895     __ lea(rscratch1, Address(rscratch1, in_bytes(MethodData::data_offset())));
 896     __ bind(method_data_continue);
 897     __ stp(rscratch1, rmethod, Address(sp, 6 * wordSize));  // save Method* and mdp (method data pointer)
 898   } else {
 899     __ stp(zr, rmethod, Address(sp, 6 * wordSize));         // save Method* (no mdp)
 900   }
 901 
 902   __ protect_return_address();
 903   __ stp(rfp, lr, Address(sp, 10 * wordSize));
 904   __ lea(rfp, Address(sp, 10 * wordSize));
 905 
 906   __ ldr(rcpool, Address(rmethod, Method::const_offset()));
 907   __ ldr(rcpool, Address(rcpool, ConstMethod::constants_offset()));
 908   __ ldr(rcpool, Address(rcpool, ConstantPool::cache_offset()));
 909   __ sub(rscratch1, rlocals, rfp);
 910   __ lsr(rscratch1, rscratch1, Interpreter::logStackElementSize);   // rscratch1 = rlocals - fp();
 911   // Store relativized rlocals, see frame::interpreter_frame_locals().
 912   __ stp(rscratch1, rcpool, Address(sp, 2 * wordSize));
 913 
 914   // set sender sp
 915   // leave last_sp as null
 916   __ stp(zr, r19_sender_sp, Address(sp, 8 * wordSize));
 917 
 918   // Get mirror
 919   __ load_mirror(r10, rmethod, r5, rscratch2);
 920   if (! native_call) {
 921     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));
 922     __ ldrh(rscratch1, Address(rscratch1, ConstMethod::max_stack_offset()));
 923     __ add(rscratch1, rscratch1, MAX2(3, Method::extra_stack_entries()));
 924     __ sub(rscratch1, sp, rscratch1, ext::uxtw, 3);
 925     __ andr(rscratch1, rscratch1, -16);
 926     __ sub(rscratch2, rscratch1, rfp);
 927     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 928     // Store extended SP and mirror
 929     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 930     // Move SP out of the way
 931     __ mov(sp, rscratch1);
 932   } else {
 933     // Make sure there is room for the exception oop pushed in case method throws
 934     // an exception (see TemplateInterpreterGenerator::generate_throw_exception())
 935     __ sub(rscratch1, sp, 2 * wordSize);
 936     __ sub(rscratch2, rscratch1, rfp);
 937     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 938     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 939     __ mov(sp, rscratch1);
 940   }
 941 }
 942 
 943 // End of helpers
 944 
 945 // Various method entries
 946 //------------------------------------------------------------------------------------------------------------------------
 947 //
 948 //
 949 
 950 // Method entry for java.lang.ref.Reference.get.
 951 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 952   // Code: _aload_0, _getfield, _areturn
 953   // parameter size = 1
 954   //
 955   // The code that gets generated by this routine is split into 2 parts:
 956   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 957   //    2. The slow path - which is an expansion of the regular method entry.
 958   //
 959   // Notes:-
 960   // * In the G1 code we do not check whether we need to block for
 961   //   a safepoint. If G1 is enabled then we must execute the specialized
 962   //   code for Reference.get (except when the Reference object is null)
 963   //   so that we can log the value in the referent field with an SATB
 964   //   update buffer.
 965   //   If the code for the getfield template is modified so that the
 966   //   G1 pre-barrier code is executed when the current method is
 967   //   Reference.get() then going through the normal method entry
 968   //   will be fine.
 969   // * The G1 code can, however, check the receiver object (the instance
 970   //   of java.lang.Reference) and jump to the slow path if null. If the
 971   //   Reference object is null then we obviously cannot fetch the referent
 972   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 973   //   regular method entry code to generate the NPE.
 974   //
 975   // This code is based on generate_accessor_entry.
 976   //
 977   // rmethod: Method*
 978   // r19_sender_sp: senderSP must preserve for slow path, set SP to it on fast path
 979 
 980   // LR is live.  It must be saved around calls.
 981 
 982   address entry = __ pc();
 983 
 984   const int referent_offset = java_lang_ref_Reference::referent_offset();
 985 
 986   Label slow_path;
 987   const Register local_0 = c_rarg0;
 988   // Check if local 0 != null
 989   // If the receiver is null then it is OK to jump to the slow path.
 990   __ ldr(local_0, Address(esp, 0));
 991   __ cbz(local_0, slow_path);
 992 
 993   // Load the value of the referent field.
 994   const Address field_address(local_0, referent_offset);
 995   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 996   bs->load_at(_masm, IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT, local_0, field_address, /*tmp1*/ rscratch1, /*tmp2*/ rscratch2);
 997 
 998   // areturn
 999   __ andr(sp, r19_sender_sp, -16);  // done with stack
1000   __ ret(lr);
1001 
1002   // generate a vanilla interpreter entry as the slow path
1003   __ bind(slow_path);
1004   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
1005   return entry;
1006 
1007 }
1008 
1009 /**
1010  * Method entry for static native methods:
1011  *   int java.util.zip.CRC32.update(int crc, int b)
1012  */
1013 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
1014   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1015   address entry = __ pc();
1016 
1017   // rmethod: Method*
1018   // r19_sender_sp: senderSP must preserved for slow path
1019   // esp: args
1020 
1021   Label slow_path;
1022   // If we need a safepoint check, generate full interpreter entry.
1023   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
1024 
1025   // We don't generate local frame and don't align stack because
1026   // we call stub code and there is no safepoint on this path.
1027 
1028   // Load parameters
1029   const Register crc = c_rarg0;  // crc
1030   const Register val = c_rarg1;  // source java byte value
1031   const Register tbl = c_rarg2;  // scratch
1032 
1033   // Arguments are reversed on java expression stack
1034   __ ldrw(val, Address(esp, 0));              // byte value
1035   __ ldrw(crc, Address(esp, wordSize));       // Initial CRC
1036 
1037   uint64_t offset;
1038   __ adrp(tbl, ExternalAddress(StubRoutines::crc_table_addr()), offset);
1039   __ add(tbl, tbl, offset);
1040 
1041   __ mvnw(crc, crc); // ~crc
1042   __ update_byte_crc32(crc, val, tbl);
1043   __ mvnw(crc, crc); // ~crc
1044 
1045   // result in c_rarg0
1046 
1047   __ andr(sp, r19_sender_sp, -16);
1048   __ ret(lr);
1049 
1050   // generate a vanilla native entry as the slow path
1051   __ bind(slow_path);
1052   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1053   return entry;
1054 }
1055 
1056 /**
1057  * Method entry for static native methods:
1058  *   int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len)
1059  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
1060  */
1061 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1062   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1063   address entry = __ pc();
1064 
1065   // rmethod,: Method*
1066   // r19_sender_sp: senderSP must preserved for slow path
1067 
1068   Label slow_path;
1069   // If we need a safepoint check, generate full interpreter entry.
1070   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
1071 
1072   // We don't generate local frame and don't align stack because
1073   // we call stub code and there is no safepoint on this path.
1074 
1075   // Load parameters
1076   const Register crc = c_rarg0;  // crc
1077   const Register buf = c_rarg1;  // source java byte array address
1078   const Register len = c_rarg2;  // length
1079   const Register off = len;      // offset (never overlaps with 'len')
1080 
1081   // Arguments are reversed on java expression stack
1082   // Calculate address of start element
1083   if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) {
1084     __ ldr(buf, Address(esp, 2*wordSize)); // long buf
1085     __ ldrw(off, Address(esp, wordSize)); // offset
1086     __ add(buf, buf, off); // + offset
1087     __ ldrw(crc,   Address(esp, 4*wordSize)); // Initial CRC
1088   } else {
1089     __ ldr(buf, Address(esp, 2*wordSize)); // byte[] array
1090     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1091     __ ldrw(off, Address(esp, wordSize)); // offset
1092     __ add(buf, buf, off); // + offset
1093     __ ldrw(crc,   Address(esp, 3*wordSize)); // Initial CRC
1094   }
1095   // Can now load 'len' since we're finished with 'off'
1096   __ ldrw(len, Address(esp, 0x0)); // Length
1097 
1098   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1099 
1100   // We are frameless so we can just jump to the stub.
1101   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()));
1102 
1103   // generate a vanilla native entry as the slow path
1104   __ bind(slow_path);
1105   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1106   return entry;
1107 }
1108 
1109 /**
1110  * Method entry for intrinsic-candidate (non-native) methods:
1111  *   int java.util.zip.CRC32C.updateBytes(int crc, byte[] b, int off, int end)
1112  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
1113  * Unlike CRC32, CRC32C does not have any methods marked as native
1114  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1115  */
1116 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1117   assert(UseCRC32CIntrinsics, "this intrinsic is not supported");
1118   address entry = __ pc();
1119 
1120   // Prepare jump to stub using parameters from the stack
1121   const Register crc = c_rarg0; // initial crc
1122   const Register buf = c_rarg1; // source java byte array address
1123   const Register len = c_rarg2; // len argument to the kernel
1124 
1125   const Register end = len; // index of last element to process
1126   const Register off = crc; // offset
1127 
1128   __ ldrw(end, Address(esp)); // int end
1129   __ ldrw(off, Address(esp, wordSize)); // int offset
1130   __ sub(len, end, off);
1131   __ ldr(buf, Address(esp, 2*wordSize)); // byte[] buf | long buf
1132   __ add(buf, buf, off); // + offset
1133   if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) {
1134     __ ldrw(crc, Address(esp, 4*wordSize)); // long crc
1135   } else {
1136     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1137     __ ldrw(crc, Address(esp, 3*wordSize)); // long crc
1138   }
1139 
1140   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1141 
1142   // Jump to the stub.
1143   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32C()));
1144 
1145   return entry;
1146 }
1147 
1148 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1149   // See more discussion in stackOverflow.hpp.
1150 
1151   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
1152   const int page_size = (int)os::vm_page_size();
1153   const int n_shadow_pages = shadow_zone_size / page_size;
1154 
1155 #ifdef ASSERT
1156   Label L_good_limit;
1157   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1158   __ cbnz(rscratch1, L_good_limit);
1159   __ stop("shadow zone safe limit is not initialized");
1160   __ bind(L_good_limit);
1161 
1162   Label L_good_watermark;
1163   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1164   __ cbnz(rscratch1, L_good_watermark);
1165   __ stop("shadow zone growth watermark is not initialized");
1166   __ bind(L_good_watermark);
1167 #endif
1168 
1169   Label L_done;
1170 
1171   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1172   __ cmp(sp, rscratch1);
1173   __ br(Assembler::HI, L_done);
1174 
1175   for (int p = 1; p <= n_shadow_pages; p++) {
1176     __ sub(rscratch2, sp, p*page_size);
1177     __ str(zr, Address(rscratch2));
1178   }
1179 
1180   // Record the new watermark, but only if the update is above the safe limit.
1181   // Otherwise, the next time around the check above would pass the safe limit.
1182   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1183   __ cmp(sp, rscratch1);
1184   __ br(Assembler::LS, L_done);
1185   __ mov(rscratch1, sp);
1186   __ str(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1187 
1188   __ bind(L_done);
1189 }
1190 
1191 // Interpreter stub for calling a native method. (asm interpreter)
1192 // This sets up a somewhat different looking stack for calling the
1193 // native method than the typical interpreter frame setup.
1194 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1195   // determine code generation flags
1196   bool inc_counter  = UseCompiler || CountCompiledCalls;
1197 
1198   // r1: Method*
1199   // rscratch1: sender sp
1200 
1201   address entry_point = __ pc();
1202 
1203   const Address constMethod       (rmethod, Method::const_offset());
1204   const Address access_flags      (rmethod, Method::access_flags_offset());
1205   const Address size_of_parameters(r2, ConstMethod::
1206                                        size_of_parameters_offset());
1207 
1208   // get parameter size (always needed)
1209   __ ldr(r2, constMethod);
1210   __ load_unsigned_short(r2, size_of_parameters);
1211 
1212   // Native calls don't need the stack size check since they have no
1213   // expression stack and the arguments are already on the stack and
1214   // we only add a handful of words to the stack.
1215 
1216   // rmethod: Method*
1217   // r2: size of parameters
1218   // rscratch1: sender sp
1219 
1220   // for natives the size of locals is zero
1221 
1222   // compute beginning of parameters (rlocals)
1223   __ add(rlocals, esp, r2, ext::uxtx, 3);
1224   __ add(rlocals, rlocals, -wordSize);
1225 
1226   // Pull SP back to minimum size: this avoids holes in the stack
1227   __ andr(sp, esp, -16);
1228 
1229   // initialize fixed part of activation frame
1230   generate_fixed_frame(true);
1231 
1232   // make sure method is native & not abstract
1233 #ifdef ASSERT
1234   __ ldrw(r0, access_flags);
1235   {
1236     Label L;
1237     __ tst(r0, JVM_ACC_NATIVE);
1238     __ br(Assembler::NE, L);
1239     __ stop("tried to execute non-native method as native");
1240     __ bind(L);
1241   }
1242   {
1243     Label L;
1244     __ tst(r0, JVM_ACC_ABSTRACT);
1245     __ br(Assembler::EQ, L);
1246     __ stop("tried to execute abstract method in interpreter");
1247     __ bind(L);
1248   }
1249 #endif
1250 
1251   // Since at this point in the method invocation the exception
1252   // handler would try to exit the monitor of synchronized methods
1253   // which hasn't been entered yet, we set the thread local variable
1254   // _do_not_unlock_if_synchronized to true. The remove_activation
1255   // will check this flag.
1256 
1257    const Address do_not_unlock_if_synchronized(rthread,
1258         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1259   __ mov(rscratch2, true);
1260   __ strb(rscratch2, do_not_unlock_if_synchronized);
1261 
1262   // increment invocation count & check for overflow
1263   Label invocation_counter_overflow;
1264   if (inc_counter) {
1265     generate_counter_incr(&invocation_counter_overflow);
1266   }
1267 
1268   Label continue_after_compile;
1269   __ bind(continue_after_compile);
1270 
1271   bang_stack_shadow_pages(true);
1272 
1273   // reset the _do_not_unlock_if_synchronized flag
1274   __ strb(zr, do_not_unlock_if_synchronized);
1275 
1276   // check for synchronized methods
1277   // Must happen AFTER invocation_counter check and stack overflow check,
1278   // so method is not locked if overflows.
1279   if (synchronized) {
1280     lock_method();
1281   } else {
1282     // no synchronization necessary
1283 #ifdef ASSERT
1284     {
1285       Label L;
1286       __ ldrw(r0, access_flags);
1287       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1288       __ br(Assembler::EQ, L);
1289       __ stop("method needs synchronization");
1290       __ bind(L);
1291     }
1292 #endif
1293   }
1294 
1295   // start execution
1296 #ifdef ASSERT
1297   {
1298     Label L;
1299     const Address monitor_block_top(rfp,
1300                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1301     __ ldr(rscratch1, monitor_block_top);
1302     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1303     __ cmp(esp, rscratch1);
1304     __ br(Assembler::EQ, L);
1305     __ stop("broken stack frame setup in interpreter 1");
1306     __ bind(L);
1307   }
1308 #endif
1309 
1310   // jvmti support
1311   __ notify_method_entry();
1312 
1313   // work registers
1314   const Register t = r17;
1315   const Register result_handler = r19;
1316 
1317   // allocate space for parameters
1318   __ ldr(t, Address(rmethod, Method::const_offset()));
1319   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
1320 
1321   __ sub(rscratch1, esp, t, ext::uxtx, Interpreter::logStackElementSize);
1322   __ andr(sp, rscratch1, -16);
1323   __ mov(esp, rscratch1);
1324 
1325   // get signature handler
1326   {
1327     Label L;
1328     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1329     __ cbnz(t, L);
1330     __ call_VM(noreg,
1331                CAST_FROM_FN_PTR(address,
1332                                 InterpreterRuntime::prepare_native_call),
1333                rmethod);
1334     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1335     __ bind(L);
1336   }
1337 
1338   // call signature handler
1339   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
1340          "adjust this code");
1341   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == sp,
1342          "adjust this code");
1343   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
1344           "adjust this code");
1345 
1346   // The generated handlers do not touch rmethod (the method).
1347   // However, large signatures cannot be cached and are generated
1348   // each time here.  The slow-path generator can do a GC on return,
1349   // so we must reload it after the call.
1350   __ blr(t);
1351   __ get_method(rmethod);        // slow path can do a GC, reload rmethod
1352 
1353 
1354   // result handler is in r0
1355   // set result handler
1356   __ mov(result_handler, r0);
1357   __ str(r0, Address(rfp, frame::interpreter_frame_result_handler_offset * wordSize));
1358 
1359   // pass mirror handle if static call
1360   {
1361     Label L;
1362     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1363     __ tbz(t, exact_log2(JVM_ACC_STATIC), L);
1364     // get mirror
1365     __ load_mirror(t, rmethod, r10, rscratch2);
1366     // copy mirror into activation frame
1367     __ str(t, Address(rfp, frame::interpreter_frame_oop_temp_offset * wordSize));
1368     // pass handle to mirror
1369     __ add(c_rarg1, rfp, frame::interpreter_frame_oop_temp_offset * wordSize);
1370     __ bind(L);
1371   }
1372 
1373   // get native function entry point in r10
1374   {
1375     Label L;
1376     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1377     address unsatisfied = (SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1378     __ mov(rscratch2, unsatisfied);
1379     __ ldr(rscratch2, rscratch2);
1380     __ cmp(r10, rscratch2);
1381     __ br(Assembler::NE, L);
1382     __ call_VM(noreg,
1383                CAST_FROM_FN_PTR(address,
1384                                 InterpreterRuntime::prepare_native_call),
1385                rmethod);
1386     __ get_method(rmethod);
1387     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1388     __ bind(L);
1389   }
1390 
1391   // pass JNIEnv
1392   __ add(c_rarg0, rthread, in_bytes(JavaThread::jni_environment_offset()));
1393 
1394   // Set the last Java PC in the frame anchor to be the return address from
1395   // the call to the native method: this will allow the debugger to
1396   // generate an accurate stack trace.
1397   Label resume_pc;
1398   __ set_last_Java_frame(esp, rfp, resume_pc, rscratch1);
1399 
1400   // change thread state
1401 #ifdef ASSERT
1402   {
1403     Label L;
1404     __ ldrw(t, Address(rthread, JavaThread::thread_state_offset()));
1405     __ cmp(t, (u1)_thread_in_Java);
1406     __ br(Assembler::EQ, L);
1407     __ stop("Wrong thread state in native stub");
1408     __ bind(L);
1409   }
1410 #endif
1411 
1412   // Change state to native
1413   __ mov(rscratch1, _thread_in_native);
1414   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1415   __ stlrw(rscratch1, rscratch2);
1416 
1417   __ push_cont_fastpath();
1418 
1419   // Call the native method.
1420   __ blr(r10);
1421 
1422   __ pop_cont_fastpath();
1423 
1424   __ get_method(rmethod);
1425   // result potentially in r0 or v0
1426 
1427   // Restore cpu control state after JNI call
1428   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
1429 
1430   // make room for the pushes we're about to do
1431   __ sub(rscratch1, esp, 4 * wordSize);
1432   __ andr(sp, rscratch1, -16);
1433 
1434   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
1435   // in order to extract the result of a method call. If the order of these
1436   // pushes change or anything else is added to the stack then the code in
1437   // interpreter_frame_result must also change.
1438   __ push(dtos);
1439   __ push(ltos);
1440 
1441   __ verify_sve_vector_length();
1442 
1443   // change thread state
1444   __ mov(rscratch1, _thread_in_native_trans);
1445   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1446   __ stlrw(rscratch1, rscratch2);
1447 
1448   // Force this write out before the read below
1449   if (!UseSystemMemoryBarrier) {
1450     __ dmb(Assembler::ISH);
1451   }
1452 
1453   // check for safepoint operation in progress and/or pending suspend requests
1454   {
1455     Label L, Continue;
1456 
1457     // We need an acquire here to ensure that any subsequent load of the
1458     // global SafepointSynchronize::_state flag is ordered after this load
1459     // of the thread-local polling word.  We don't want this poll to
1460     // return false (i.e. not safepointing) and a later poll of the global
1461     // SafepointSynchronize::_state spuriously to return true.
1462     //
1463     // This is to avoid a race when we're in a native->Java transition
1464     // racing the code which wakes up from a safepoint.
1465     __ safepoint_poll(L, true /* at_return */, true /* acquire */, false /* in_nmethod */);
1466     __ ldrw(rscratch2, Address(rthread, JavaThread::suspend_flags_offset()));
1467     __ cbz(rscratch2, Continue);
1468     __ bind(L);
1469 
1470     // Don't use call_VM as it will see a possible pending exception
1471     // and forward it and never return here preventing us from
1472     // clearing _last_native_pc down below. So we do a runtime call by
1473     // hand.
1474     //
1475     __ mov(c_rarg0, rthread);
1476     __ mov(rscratch2, CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans));
1477     __ blr(rscratch2);
1478     __ get_method(rmethod);
1479     __ reinit_heapbase();
1480     __ bind(Continue);
1481   }
1482 
1483   // change thread state
1484   __ mov(rscratch1, _thread_in_Java);
1485   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1486   __ stlrw(rscratch1, rscratch2);
1487 
1488   // Check preemption for Object.wait()
1489   Label not_preempted;
1490   __ ldr(rscratch1, Address(rthread, JavaThread::preempt_alternate_return_offset()));
1491   __ cbz(rscratch1, not_preempted);
1492   __ str(zr, Address(rthread, JavaThread::preempt_alternate_return_offset()));
1493   __ br(rscratch1);
1494   __ bind(resume_pc);
1495   // On resume we need to set up stack as expected
1496   __ push(dtos);
1497   __ push(ltos);
1498   __ bind(not_preempted);
1499 
1500   // reset_last_Java_frame
1501   __ reset_last_Java_frame(true);
1502 
1503   if (CheckJNICalls) {
1504     // clear_pending_jni_exception_check
1505     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1506   }
1507 
1508   // reset handle block
1509   __ ldr(t, Address(rthread, JavaThread::active_handles_offset()));
1510   __ str(zr, Address(t, JNIHandleBlock::top_offset()));
1511 
1512   // If result is an oop unbox and store it in frame where gc will see it
1513   // and result handler will pick it up
1514 
1515   {
1516     Label no_oop;
1517     __ adr(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1518     __ ldr(result_handler, Address(rfp, frame::interpreter_frame_result_handler_offset*wordSize));
1519     __ cmp(t, result_handler);
1520     __ br(Assembler::NE, no_oop);
1521     // Unbox oop result, e.g. JNIHandles::resolve result.
1522     __ pop(ltos);
1523     __ resolve_jobject(r0, t, rscratch2);
1524     __ str(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
1525     // keep stack depth as expected by pushing oop which will eventually be discarded
1526     __ push(ltos);
1527     __ bind(no_oop);
1528   }
1529 
1530   {
1531     Label no_reguard;
1532     __ lea(rscratch1, Address(rthread, in_bytes(JavaThread::stack_guard_state_offset())));
1533     __ ldrw(rscratch1, Address(rscratch1));
1534     __ cmp(rscratch1, (u1)StackOverflow::stack_guard_yellow_reserved_disabled);
1535     __ br(Assembler::NE, no_reguard);
1536 
1537     __ push_call_clobbered_registers();
1538     __ mov(c_rarg0, rthread);
1539     __ mov(rscratch2, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
1540     __ blr(rscratch2);
1541     __ pop_call_clobbered_registers();
1542 
1543     __ bind(no_reguard);
1544   }
1545 
1546   // The method register is junk from after the thread_in_native transition
1547   // until here.  Also can't call_VM until the bcp has been
1548   // restored.  Need bcp for throwing exception below so get it now.
1549   __ get_method(rmethod);
1550 
1551   // restore bcp to have legal interpreter frame, i.e., bci == 0 <=>
1552   // rbcp == code_base()
1553   __ ldr(rbcp, Address(rmethod, Method::const_offset()));   // get ConstMethod*
1554   __ add(rbcp, rbcp, in_bytes(ConstMethod::codes_offset()));          // get codebase
1555   // handle exceptions (exception handling will handle unlocking!)
1556   {
1557     Label L;
1558     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
1559     __ cbz(rscratch1, L);
1560     // Note: At some point we may want to unify this with the code
1561     // used in call_VM_base(); i.e., we should use the
1562     // StubRoutines::forward_exception code. For now this doesn't work
1563     // here because the rsp is not correctly set at this point.
1564     __ MacroAssembler::call_VM(noreg,
1565                                CAST_FROM_FN_PTR(address,
1566                                InterpreterRuntime::throw_pending_exception));
1567     __ should_not_reach_here();
1568     __ bind(L);
1569   }
1570 
1571   // do unlocking if necessary
1572   {
1573     Label L;
1574     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1575     __ tbz(t, exact_log2(JVM_ACC_SYNCHRONIZED), L);
1576     // the code below should be shared with interpreter macro
1577     // assembler implementation
1578     {
1579       Label unlock;
1580       // BasicObjectLock will be first in list, since this is a
1581       // synchronized method. However, need to check that the object
1582       // has not been unlocked by an explicit monitorexit bytecode.
1583 
1584       // monitor expect in c_rarg1 for slow unlock path
1585       __ lea (c_rarg1, Address(rfp,   // address of first monitor
1586                                (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1587                                           wordSize - sizeof(BasicObjectLock))));
1588 
1589       __ ldr(t, Address(c_rarg1, BasicObjectLock::obj_offset()));
1590       __ cbnz(t, unlock);
1591 
1592       // Entry already unlocked, need to throw exception
1593       __ MacroAssembler::call_VM(noreg,
1594                                  CAST_FROM_FN_PTR(address,
1595                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1596       __ should_not_reach_here();
1597 
1598       __ bind(unlock);
1599       __ unlock_object(c_rarg1);
1600     }
1601     __ bind(L);
1602   }
1603 
1604   // jvmti support
1605   // Note: This must happen _after_ handling/throwing any exceptions since
1606   //       the exception handler code notifies the runtime of method exits
1607   //       too. If this happens before, method entry/exit notifications are
1608   //       not properly paired (was bug - gri 11/22/99).
1609   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1610 
1611   // restore potential result in r0:d0, call result handler to
1612   // restore potential result in ST0 & handle result
1613 
1614   __ pop(ltos);
1615   __ pop(dtos);
1616 
1617   __ blr(result_handler);
1618 
1619   // remove activation
1620   __ ldr(esp, Address(rfp,
1621                     frame::interpreter_frame_sender_sp_offset *
1622                     wordSize)); // get sender sp
1623   // remove frame anchor
1624   __ leave();
1625 
1626   // restore sender sp
1627   __ mov(sp, esp);
1628 
1629   __ ret(lr);
1630 
1631   if (inc_counter) {
1632     // Handle overflow of counter and compile method
1633     __ bind(invocation_counter_overflow);
1634     generate_counter_overflow(continue_after_compile);
1635   }
1636 
1637   return entry_point;
1638 }
1639 
1640 //
1641 // Generic interpreted method entry to (asm) interpreter
1642 //
1643 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1644   // determine code generation flags
1645   bool inc_counter  = UseCompiler || CountCompiledCalls;
1646 
1647   // rscratch1: sender sp
1648   address entry_point = __ pc();
1649 
1650   const Address constMethod(rmethod, Method::const_offset());
1651   const Address access_flags(rmethod, Method::access_flags_offset());
1652   const Address size_of_parameters(r3,
1653                                    ConstMethod::size_of_parameters_offset());
1654   const Address size_of_locals(r3, ConstMethod::size_of_locals_offset());
1655 
1656   // get parameter size (always needed)
1657   // need to load the const method first
1658   __ ldr(r3, constMethod);
1659   __ load_unsigned_short(r2, size_of_parameters);
1660 
1661   // r2: size of parameters
1662 
1663   __ load_unsigned_short(r3, size_of_locals); // get size of locals in words
1664   __ sub(r3, r3, r2); // r3 = no. of additional locals
1665 
1666   // see if we've got enough room on the stack for locals plus overhead.
1667   generate_stack_overflow_check();
1668 
1669   // compute beginning of parameters (rlocals)
1670   __ add(rlocals, esp, r2, ext::uxtx, 3);
1671   __ sub(rlocals, rlocals, wordSize);
1672 
1673   __ mov(rscratch1, esp);
1674 
1675   // r3 - # of additional locals
1676   // allocate space for locals
1677   // explicitly initialize locals
1678   // Initializing memory allocated for locals in the same direction as
1679   // the stack grows to ensure page initialization order according
1680   // to windows-aarch64 stack page growth requirement (see
1681   // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-160#stack)
1682   {
1683     Label exit, loop;
1684     __ ands(zr, r3, r3);
1685     __ br(Assembler::LE, exit); // do nothing if r3 <= 0
1686     __ bind(loop);
1687     __ str(zr, Address(__ pre(rscratch1, -wordSize)));
1688     __ sub(r3, r3, 1); // until everything initialized
1689     __ cbnz(r3, loop);
1690     __ bind(exit);
1691   }
1692 
1693   // Padding between locals and fixed part of activation frame to ensure
1694   // SP is always 16-byte aligned.
1695   __ andr(sp, rscratch1, -16);
1696 
1697   // And the base dispatch table
1698   __ get_dispatch();
1699 
1700   // initialize fixed part of activation frame
1701   generate_fixed_frame(false);
1702 
1703   // make sure method is not native & not abstract
1704 #ifdef ASSERT
1705   __ ldrw(r0, access_flags);
1706   {
1707     Label L;
1708     __ tst(r0, JVM_ACC_NATIVE);
1709     __ br(Assembler::EQ, L);
1710     __ stop("tried to execute native method as non-native");
1711     __ bind(L);
1712   }
1713  {
1714     Label L;
1715     __ tst(r0, JVM_ACC_ABSTRACT);
1716     __ br(Assembler::EQ, L);
1717     __ stop("tried to execute abstract method in interpreter");
1718     __ bind(L);
1719   }
1720 #endif
1721 
1722   // Since at this point in the method invocation the exception
1723   // handler would try to exit the monitor of synchronized methods
1724   // which hasn't been entered yet, we set the thread local variable
1725   // _do_not_unlock_if_synchronized to true. The remove_activation
1726   // will check this flag.
1727 
1728    const Address do_not_unlock_if_synchronized(rthread,
1729         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1730   __ mov(rscratch2, true);
1731   __ strb(rscratch2, do_not_unlock_if_synchronized);
1732 
1733   Register mdp = r3;
1734   __ profile_parameters_type(mdp, r1, r2);
1735 
1736   // increment invocation count & check for overflow
1737   Label invocation_counter_overflow;
1738   if (inc_counter) {
1739     generate_counter_incr(&invocation_counter_overflow);
1740   }
1741 
1742   Label continue_after_compile;
1743   __ bind(continue_after_compile);
1744 
1745   bang_stack_shadow_pages(false);
1746 
1747   // reset the _do_not_unlock_if_synchronized flag
1748   __ strb(zr, do_not_unlock_if_synchronized);
1749 
1750   // check for synchronized methods
1751   // Must happen AFTER invocation_counter check and stack overflow check,
1752   // so method is not locked if overflows.
1753   if (synchronized) {
1754     // Allocate monitor and lock method
1755     lock_method();
1756   } else {
1757     // no synchronization necessary
1758 #ifdef ASSERT
1759     {
1760       Label L;
1761       __ ldrw(r0, access_flags);
1762       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1763       __ br(Assembler::EQ, L);
1764       __ stop("method needs synchronization");
1765       __ bind(L);
1766     }
1767 #endif
1768   }
1769 
1770   // start execution
1771 #ifdef ASSERT
1772   {
1773     Label L;
1774      const Address monitor_block_top (rfp,
1775                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1776     __ ldr(rscratch1, monitor_block_top);
1777     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1778     __ cmp(esp, rscratch1);
1779     __ br(Assembler::EQ, L);
1780     __ stop("broken stack frame setup in interpreter 2");
1781     __ bind(L);
1782   }
1783 #endif
1784 
1785   // jvmti support
1786   __ notify_method_entry();
1787 
1788   __ dispatch_next(vtos);
1789 
1790   // invocation counter overflow
1791   if (inc_counter) {
1792     // Handle overflow of counter and compile method
1793     __ bind(invocation_counter_overflow);
1794     generate_counter_overflow(continue_after_compile);
1795   }
1796 
1797   return entry_point;
1798 }
1799 
1800 // Method entry for java.lang.Thread.currentThread
1801 address TemplateInterpreterGenerator::generate_currentThread() {
1802   address entry_point = __ pc();
1803 
1804   __ ldr(r0, Address(rthread, JavaThread::vthread_offset()));
1805   __ resolve_oop_handle(r0, rscratch1, rscratch2);
1806   __ ret(lr);
1807 
1808   return entry_point;
1809 }
1810 
1811 // Not supported
1812 address TemplateInterpreterGenerator::generate_Float_intBitsToFloat_entry() { return nullptr; }
1813 address TemplateInterpreterGenerator::generate_Float_floatToRawIntBits_entry() { return nullptr; }
1814 address TemplateInterpreterGenerator::generate_Double_longBitsToDouble_entry() { return nullptr; }
1815 address TemplateInterpreterGenerator::generate_Double_doubleToRawLongBits_entry() { return nullptr; }
1816 
1817 //-----------------------------------------------------------------------------
1818 // Exceptions
1819 
1820 void TemplateInterpreterGenerator::generate_throw_exception() {
1821   // Entry point in previous activation (i.e., if the caller was
1822   // interpreted)
1823   Interpreter::_rethrow_exception_entry = __ pc();
1824   // Restore sp to interpreter_frame_last_sp even though we are going
1825   // to empty the expression stack for the exception processing.
1826   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1827   // r0: exception
1828   // r3: return address/pc that threw exception
1829   __ restore_bcp();    // rbcp points to call/send
1830   __ restore_locals();
1831   __ restore_constant_pool_cache();
1832   __ reinit_heapbase();  // restore rheapbase as heapbase.
1833   __ get_dispatch();
1834 
1835   // Entry point for exceptions thrown within interpreter code
1836   Interpreter::_throw_exception_entry = __ pc();
1837   // If we came here via a NullPointerException on the receiver of a
1838   // method, rmethod may be corrupt.
1839   __ get_method(rmethod);
1840   // expression stack is undefined here
1841   // r0: exception
1842   // rbcp: exception bcp
1843   __ verify_oop(r0);
1844   __ mov(c_rarg1, r0);
1845 
1846   // expression stack must be empty before entering the VM in case of
1847   // an exception
1848   __ empty_expression_stack();
1849   // find exception handler address and preserve exception oop
1850   __ call_VM(r3,
1851              CAST_FROM_FN_PTR(address,
1852                           InterpreterRuntime::exception_handler_for_exception),
1853              c_rarg1);
1854 
1855   // Restore machine SP
1856   __ restore_sp_after_call();
1857 
1858   // r0: exception handler entry point
1859   // r3: preserved exception oop
1860   // rbcp: bcp for exception handler
1861   __ push_ptr(r3); // push exception which is now the only value on the stack
1862   __ br(r0); // jump to exception handler (may be _remove_activation_entry!)
1863 
1864   // If the exception is not handled in the current frame the frame is
1865   // removed and the exception is rethrown (i.e. exception
1866   // continuation is _rethrow_exception).
1867   //
1868   // Note: At this point the bci is still the bxi for the instruction
1869   // which caused the exception and the expression stack is
1870   // empty. Thus, for any VM calls at this point, GC will find a legal
1871   // oop map (with empty expression stack).
1872 
1873   //
1874   // JVMTI PopFrame support
1875   //
1876 
1877   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1878   __ empty_expression_stack();
1879   // Set the popframe_processing bit in pending_popframe_condition
1880   // indicating that we are currently handling popframe, so that
1881   // call_VMs that may happen later do not trigger new popframe
1882   // handling cycles.
1883   __ ldrw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1884   __ orr(r3, r3, JavaThread::popframe_processing_bit);
1885   __ strw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1886 
1887   {
1888     // Check to see whether we are returning to a deoptimized frame.
1889     // (The PopFrame call ensures that the caller of the popped frame is
1890     // either interpreted or compiled and deoptimizes it if compiled.)
1891     // In this case, we can't call dispatch_next() after the frame is
1892     // popped, but instead must save the incoming arguments and restore
1893     // them after deoptimization has occurred.
1894     //
1895     // Note that we don't compare the return PC against the
1896     // deoptimization blob's unpack entry because of the presence of
1897     // adapter frames in C2.
1898     Label caller_not_deoptimized;
1899     __ ldr(c_rarg1, Address(rfp, frame::return_addr_offset * wordSize));
1900     // This is a return address, so requires authenticating for PAC.
1901     __ authenticate_return_address(c_rarg1);
1902     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1903                                InterpreterRuntime::interpreter_contains), c_rarg1);
1904     __ cbnz(r0, caller_not_deoptimized);
1905 
1906     // Compute size of arguments for saving when returning to
1907     // deoptimized caller
1908     __ get_method(r0);
1909     __ ldr(r0, Address(r0, Method::const_offset()));
1910     __ load_unsigned_short(r0, Address(r0, in_bytes(ConstMethod::
1911                                                     size_of_parameters_offset())));
1912     __ lsl(r0, r0, Interpreter::logStackElementSize);
1913     __ restore_locals(); // XXX do we need this?
1914     __ sub(rlocals, rlocals, r0);
1915     __ add(rlocals, rlocals, wordSize);
1916     // Save these arguments
1917     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1918                                            Deoptimization::
1919                                            popframe_preserve_args),
1920                           rthread, r0, rlocals);
1921 
1922     __ remove_activation(vtos,
1923                          /* throw_monitor_exception */ false,
1924                          /* install_monitor_exception */ false,
1925                          /* notify_jvmdi */ false);
1926 
1927     // Inform deoptimization that it is responsible for restoring
1928     // these arguments
1929     __ mov(rscratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1930     __ strw(rscratch1, Address(rthread, JavaThread::popframe_condition_offset()));
1931 
1932     // Continue in deoptimization handler
1933     __ ret(lr);
1934 
1935     __ bind(caller_not_deoptimized);
1936   }
1937 
1938   __ remove_activation(vtos,
1939                        /* throw_monitor_exception */ false,
1940                        /* install_monitor_exception */ false,
1941                        /* notify_jvmdi */ false);
1942 
1943   // Restore the last_sp and null it out
1944   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1945   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1946   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1947 
1948   __ restore_bcp();
1949   __ restore_locals();
1950   __ restore_constant_pool_cache();
1951   __ get_method(rmethod);
1952   __ get_dispatch();
1953 
1954   // The method data pointer was incremented already during
1955   // call profiling. We have to restore the mdp for the current bcp.
1956   if (ProfileInterpreter) {
1957     __ set_method_data_pointer_for_bcp();
1958   }
1959 
1960   // Clear the popframe condition flag
1961   __ strw(zr, Address(rthread, JavaThread::popframe_condition_offset()));
1962   assert(JavaThread::popframe_inactive == 0, "fix popframe_inactive");
1963 
1964 #if INCLUDE_JVMTI
1965   {
1966     Label L_done;
1967 
1968     __ ldrb(rscratch1, Address(rbcp, 0));
1969     __ cmpw(rscratch1, Bytecodes::_invokestatic);
1970     __ br(Assembler::NE, L_done);
1971 
1972     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1973     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1974 
1975     __ ldr(c_rarg0, Address(rlocals, 0));
1976     __ call_VM(r0, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), c_rarg0, rmethod, rbcp);
1977 
1978     __ cbz(r0, L_done);
1979 
1980     __ str(r0, Address(esp, 0));
1981     __ bind(L_done);
1982   }
1983 #endif // INCLUDE_JVMTI
1984 
1985   // Restore machine SP
1986   __ restore_sp_after_call();
1987 
1988   __ dispatch_next(vtos);
1989   // end of PopFrame support
1990 
1991   Interpreter::_remove_activation_entry = __ pc();
1992 
1993   // preserve exception over this code sequence
1994   __ pop_ptr(r0);
1995   __ str(r0, Address(rthread, JavaThread::vm_result_offset()));
1996   // remove the activation (without doing throws on illegalMonitorExceptions)
1997   __ remove_activation(vtos, false, true, false);
1998   // restore exception
1999   __ get_vm_result(r0, rthread);
2000 
2001   // In between activations - previous activation type unknown yet
2002   // compute continuation point - the continuation point expects the
2003   // following registers set up:
2004   //
2005   // r0: exception
2006   // lr: return address/pc that threw exception
2007   // esp: expression stack of caller
2008   // rfp: fp of caller
2009   __ stp(r0, lr, Address(__ pre(sp, -2 * wordSize)));  // save exception & return address
2010   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
2011                           SharedRuntime::exception_handler_for_return_address),
2012                         rthread, lr);
2013   __ mov(r1, r0);                               // save exception handler
2014   __ ldp(r0, lr, Address(__ post(sp, 2 * wordSize)));  // restore exception & return address
2015   // We might be returning to a deopt handler that expects r3 to
2016   // contain the exception pc
2017   __ mov(r3, lr);
2018   // Note that an "issuing PC" is actually the next PC after the call
2019   __ br(r1);                                    // jump to exception
2020                                                 // handler of caller
2021 }
2022 
2023 
2024 //
2025 // JVMTI ForceEarlyReturn support
2026 //
2027 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
2028   address entry = __ pc();
2029 
2030   __ restore_bcp();
2031   __ restore_locals();
2032   __ empty_expression_stack();
2033   __ load_earlyret_value(state);
2034 
2035   __ ldr(rscratch1, Address(rthread, JavaThread::jvmti_thread_state_offset()));
2036   Address cond_addr(rscratch1, JvmtiThreadState::earlyret_state_offset());
2037 
2038   // Clear the earlyret state
2039   assert(JvmtiThreadState::earlyret_inactive == 0, "should be");
2040   __ str(zr, cond_addr);
2041 
2042   __ remove_activation(state,
2043                        false, /* throw_monitor_exception */
2044                        false, /* install_monitor_exception */
2045                        true); /* notify_jvmdi */
2046   __ ret(lr);
2047 
2048   return entry;
2049 } // end of ForceEarlyReturn support
2050 
2051 
2052 
2053 //-----------------------------------------------------------------------------
2054 // Helper for vtos entry point generation
2055 
2056 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2057                                                          address& bep,
2058                                                          address& cep,
2059                                                          address& sep,
2060                                                          address& aep,
2061                                                          address& iep,
2062                                                          address& lep,
2063                                                          address& fep,
2064                                                          address& dep,
2065                                                          address& vep) {
2066   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2067   Label L;
2068   aep = __ pc();  __ push_ptr();  __ b(L);
2069   fep = __ pc();  __ push_f();    __ b(L);
2070   dep = __ pc();  __ push_d();    __ b(L);
2071   lep = __ pc();  __ push_l();    __ b(L);
2072   bep = cep = sep =
2073   iep = __ pc();  __ push_i();
2074   vep = __ pc();
2075   __ bind(L);
2076   generate_and_dispatch(t);
2077 }
2078 
2079 //-----------------------------------------------------------------------------
2080 
2081 // Non-product code
2082 #ifndef PRODUCT
2083 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2084   address entry = __ pc();
2085 
2086   __ protect_return_address();
2087   __ push(lr);
2088   __ push(state);
2089   __ push(RegSet::range(r0, r15), sp);
2090   __ mov(c_rarg2, r0);  // Pass itos
2091   __ call_VM(noreg,
2092              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
2093              c_rarg1, c_rarg2, c_rarg3);
2094   __ pop(RegSet::range(r0, r15), sp);
2095   __ pop(state);
2096   __ pop(lr);
2097   __ authenticate_return_address();
2098   __ ret(lr);                                   // return from result handler
2099 
2100   return entry;
2101 }
2102 
2103 void TemplateInterpreterGenerator::count_bytecode() {
2104   __ mov(r10, (address) &BytecodeCounter::_counter_value);
2105   __ atomic_addw(noreg, 1, r10);
2106 }
2107 
2108 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2109   __ mov(r10, (address) &BytecodeHistogram::_counters[t->bytecode()]);
2110   __ atomic_addw(noreg, 1, r10);
2111 }
2112 
2113 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2114   // Calculate new index for counter:
2115   //   _index = (_index >> log2_number_of_codes) |
2116   //            (bytecode << log2_number_of_codes);
2117   Register index_addr = rscratch1;
2118   Register index = rscratch2;
2119   __ mov(index_addr, (address) &BytecodePairHistogram::_index);
2120   __ ldrw(index, index_addr);
2121   __ mov(r10,
2122          ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2123   __ orrw(index, r10, index, Assembler::LSR,
2124           BytecodePairHistogram::log2_number_of_codes);
2125   __ strw(index, index_addr);
2126 
2127   // Bump bucket contents:
2128   //   _counters[_index] ++;
2129   Register counter_addr = rscratch1;
2130   __ mov(r10, (address) &BytecodePairHistogram::_counters);
2131   __ lea(counter_addr, Address(r10, index, Address::lsl(LogBytesPerInt)));
2132   __ atomic_addw(noreg, 1, counter_addr);
2133 }
2134 
2135 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2136   // Call a little run-time stub to avoid blow-up for each bytecode.
2137   // The run-time runtime saves the right registers, depending on
2138   // the tosca in-state for the given template.
2139 
2140   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
2141          "entry must have been generated");
2142   __ bl(Interpreter::trace_code(t->tos_in()));
2143   __ reinit_heapbase();
2144 }
2145 
2146 
2147 void TemplateInterpreterGenerator::stop_interpreter_at() {
2148   Label L;
2149   __ push(rscratch1);
2150   __ mov(rscratch1, (address) &BytecodeCounter::_counter_value);
2151   __ ldr(rscratch1, Address(rscratch1));
2152   __ mov(rscratch2, StopInterpreterAt);
2153   __ cmpw(rscratch1, rscratch2);
2154   __ br(Assembler::NE, L);
2155   __ brk(0);
2156   __ bind(L);
2157   __ pop(rscratch1);
2158 }
2159 
2160 #endif // !PRODUCT