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