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