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