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