1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "interpreter/bytecodeHistogram.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/interpreterRuntime.hpp"
  30 #include "interpreter/interp_masm.hpp"
  31 #include "interpreter/templateInterpreterGenerator.hpp"
  32 #include "interpreter/templateTable.hpp"
  33 #include "oops/arrayOop.hpp"
  34 #include "oops/methodData.hpp"
  35 #include "oops/method.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "prims/jvmtiExport.hpp"
  38 #include "prims/jvmtiThreadState.hpp"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/deoptimization.hpp"
  41 #include "runtime/frame.inline.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #include "runtime/stubRoutines.hpp"
  44 #include "runtime/synchronizer.hpp"
  45 #include "runtime/timer.hpp"
  46 #include "runtime/vframeArray.hpp"
  47 #include "utilities/align.hpp"
  48 #include "utilities/debug.hpp"
  49 #include "utilities/macros.hpp"
  50 
  51 // Size of interpreter code.  Increase if too small.  Interpreter will
  52 // fail with a guarantee ("not enough space for interpreter generation");
  53 // if too small.
  54 // Run with +PrintInterpreter to get the VM to print out the size.
  55 // Max size with JVMTI
  56 // The sethi() instruction generates lots more instructions when shell
  57 // stack limit is unlimited, so that's why this is much bigger.
  58 int TemplateInterpreter::InterpreterCodeSize = 260 * K;
  59 
  60 // Generation of Interpreter
  61 //
  62 // The TemplateInterpreterGenerator generates the interpreter into Interpreter::_code.
  63 
  64 
  65 #define __ _masm->
  66 
  67 
  68 //----------------------------------------------------------------------------------------------------
  69 
  70 // LP64 passes floating point arguments in F1, F3, F5, etc. instead of
  71 // O0, O1, O2 etc..
  72 // Doubles are passed in D0, D2, D4
  73 // We store the signature of the first 16 arguments in the first argument
  74 // slot because it will be overwritten prior to calling the native
  75 // function, with the pointer to the JNIEnv.
  76 // If LP64 there can be up to 16 floating point arguments in registers
  77 // or 6 integer registers.
  78 address TemplateInterpreterGenerator::generate_slow_signature_handler() {
  79 
  80   enum {
  81     non_float  = 0,
  82     float_sig  = 1,
  83     double_sig = 2,
  84     sig_mask   = 3
  85   };
  86 
  87   address entry = __ pc();
  88   Argument argv(0, true);
  89 
  90   // We are in the jni transition frame. Save the last_java_frame corresponding to the
  91   // outer interpreter frame
  92   //
  93   __ set_last_Java_frame(FP, noreg);
  94   // make sure the interpreter frame we've pushed has a valid return pc
  95   __ mov(O7, I7);
  96   __ mov(Lmethod, G3_scratch);
  97   __ mov(Llocals, G4_scratch);
  98   __ save_frame(0);
  99   __ mov(G2_thread, L7_thread_cache);
 100   __ add(argv.address_in_frame(), O3);
 101   __ mov(G2_thread, O0);
 102   __ mov(G3_scratch, O1);
 103   __ call(CAST_FROM_FN_PTR(address, InterpreterRuntime::slow_signature_handler), relocInfo::runtime_call_type);
 104   __ delayed()->mov(G4_scratch, O2);
 105   __ mov(L7_thread_cache, G2_thread);
 106   __ reset_last_Java_frame();
 107 
 108 
 109   // load the register arguments (the C code packed them as varargs)
 110   Address Sig = argv.address_in_frame();        // Argument 0 holds the signature
 111   __ ld_ptr( Sig, G3_scratch );                   // Get register argument signature word into G3_scratch
 112   __ mov( G3_scratch, G4_scratch);
 113   __ srl( G4_scratch, 2, G4_scratch);             // Skip Arg 0
 114   Label done;
 115   for (Argument ldarg = argv.successor(); ldarg.is_float_register(); ldarg = ldarg.successor()) {
 116     Label NonFloatArg;
 117     Label LoadFloatArg;
 118     Label LoadDoubleArg;
 119     Label NextArg;
 120     Address a = ldarg.address_in_frame();
 121     __ andcc(G4_scratch, sig_mask, G3_scratch);
 122     __ br(Assembler::zero, false, Assembler::pt, NonFloatArg);
 123     __ delayed()->nop();
 124 
 125     __ cmp(G3_scratch, float_sig );
 126     __ br(Assembler::equal, false, Assembler::pt, LoadFloatArg);
 127     __ delayed()->nop();
 128 
 129     __ cmp(G3_scratch, double_sig );
 130     __ br(Assembler::equal, false, Assembler::pt, LoadDoubleArg);
 131     __ delayed()->nop();
 132 
 133     __ bind(NonFloatArg);
 134     // There are only 6 integer register arguments!
 135     if ( ldarg.is_register() )
 136       __ ld_ptr(ldarg.address_in_frame(), ldarg.as_register());
 137     else {
 138     // Optimization, see if there are any more args and get out prior to checking
 139     // all 16 float registers.  My guess is that this is rare.
 140     // If is_register is false, then we are done the first six integer args.
 141       __ br_null_short(G4_scratch, Assembler::pt, done);
 142     }
 143     __ ba(NextArg);
 144     __ delayed()->srl( G4_scratch, 2, G4_scratch );
 145 
 146     __ bind(LoadFloatArg);
 147     __ ldf( FloatRegisterImpl::S, a, ldarg.as_float_register(), 4);
 148     __ ba(NextArg);
 149     __ delayed()->srl( G4_scratch, 2, G4_scratch );
 150 
 151     __ bind(LoadDoubleArg);
 152     __ ldf( FloatRegisterImpl::D, a, ldarg.as_double_register() );
 153     __ ba(NextArg);
 154     __ delayed()->srl( G4_scratch, 2, G4_scratch );
 155 
 156     __ bind(NextArg);
 157   }
 158 
 159   __ bind(done);
 160   __ ret();
 161   __ delayed()->restore(O0, 0, Lscratch);  // caller's Lscratch gets the result handler
 162 
 163   return entry;
 164 }
 165 
 166 void TemplateInterpreterGenerator::generate_counter_overflow(Label& Lcontinue) {
 167 
 168   // Generate code to initiate compilation on the counter overflow.
 169 
 170   // InterpreterRuntime::frequency_counter_overflow takes two arguments,
 171   // the first indicates if the counter overflow occurs at a backwards branch (NULL bcp)
 172   // and the second is only used when the first is true.  We pass zero for both.
 173   // The call returns the address of the verified entry point for the method or NULL
 174   // if the compilation did not complete (either went background or bailed out).
 175   __ set((int)false, O2);
 176   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), O2, O2, true);
 177   // returns verified_entry_point or NULL
 178   // we ignore it in any case
 179   __ ba_short(Lcontinue);
 180 }
 181 
 182 
 183 // End of helpers
 184 
 185 // Various method entries
 186 
 187 // Abstract method entry
 188 // Attempt to execute abstract method. Throw exception
 189 //
 190 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
 191   address entry = __ pc();
 192   // abstract method entry
 193   // throw exception
 194   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
 195   // the call_VM checks for exception, so we should never return here.
 196   __ should_not_reach_here();
 197   return entry;
 198 }
 199 
 200 void TemplateInterpreterGenerator::save_native_result(void) {
 201   // result potentially in O0/O1: save it across calls
 202   const Address& l_tmp = InterpreterMacroAssembler::l_tmp;
 203 
 204   // result potentially in F0/F1: save it across calls
 205   const Address& d_tmp = InterpreterMacroAssembler::d_tmp;
 206 
 207   // save and restore any potential method result value around the unlocking operation
 208   __ stf(FloatRegisterImpl::D, F0, d_tmp);
 209   __ stx(O0, l_tmp);
 210 }
 211 
 212 void TemplateInterpreterGenerator::restore_native_result(void) {
 213   const Address& l_tmp = InterpreterMacroAssembler::l_tmp;
 214   const Address& d_tmp = InterpreterMacroAssembler::d_tmp;
 215 
 216   // Restore any method result value
 217   __ ldf(FloatRegisterImpl::D, d_tmp, F0);
 218   __ ldx(l_tmp, O0);
 219 }
 220 
 221 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 222   assert(!pass_oop || message == NULL, "either oop or message but not both");
 223   address entry = __ pc();
 224   // expression stack must be empty before entering the VM if an exception happened
 225   __ empty_expression_stack();
 226   // load exception object
 227   __ set((intptr_t)name, G3_scratch);
 228   if (pass_oop) {
 229     __ call_VM(Oexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception), G3_scratch, Otos_i);
 230   } else {
 231     __ set((intptr_t)message, G4_scratch);
 232     __ call_VM(Oexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception), G3_scratch, G4_scratch);
 233   }
 234   // throw exception
 235   assert(Interpreter::throw_exception_entry() != NULL, "generate it first");
 236   AddressLiteral thrower(Interpreter::throw_exception_entry());
 237   __ jump_to(thrower, G3_scratch);
 238   __ delayed()->nop();
 239   return entry;
 240 }
 241 
 242 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 243   address entry = __ pc();
 244   // expression stack must be empty before entering the VM if an exception
 245   // happened
 246   __ empty_expression_stack();
 247   // load exception object
 248   __ call_VM(Oexception,
 249              CAST_FROM_FN_PTR(address,
 250                               InterpreterRuntime::throw_ClassCastException),
 251              Otos_i);
 252   __ should_not_reach_here();
 253   return entry;
 254 }
 255 
 256 
 257 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char* name) {
 258   address entry = __ pc();
 259   // expression stack must be empty before entering the VM if an exception happened
 260   __ empty_expression_stack();
 261   // convention: expect aberrant index in register G3_scratch, then shuffle the
 262   // index to G4_scratch for the VM call
 263   __ mov(G3_scratch, G4_scratch);
 264   __ set((intptr_t)name, G3_scratch);
 265   __ call_VM(Oexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException), G3_scratch, G4_scratch);
 266   __ should_not_reach_here();
 267   return entry;
 268 }
 269 
 270 
 271 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
 272   address entry = __ pc();
 273   // expression stack must be empty before entering the VM if an exception happened
 274   __ empty_expression_stack();
 275   __ call_VM(Oexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_StackOverflowError));
 276   __ should_not_reach_here();
 277   return entry;
 278 }
 279 
 280 
 281 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 282   address entry = __ pc();
 283 
 284   if (state == atos) {
 285     __ profile_return_type(O0, G3_scratch, G1_scratch);
 286   }
 287 
 288   // The callee returns with the stack possibly adjusted by adapter transition
 289   // We remove that possible adjustment here.
 290   // All interpreter local registers are untouched. Any result is passed back
 291   // in the O0/O1 or float registers. Before continuing, the arguments must be
 292   // popped from the java expression stack; i.e., Lesp must be adjusted.
 293 
 294   __ mov(Llast_SP, SP);   // Remove any adapter added stack space.
 295 
 296   const Register cache = G3_scratch;
 297   const Register index  = G1_scratch;
 298   __ get_cache_and_index_at_bcp(cache, index, 1, index_size);
 299 
 300   const Register flags = cache;
 301   __ ld_ptr(cache, ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset(), flags);
 302   const Register parameter_size = flags;
 303   __ and3(flags, ConstantPoolCacheEntry::parameter_size_mask, parameter_size);  // argument size in words
 304   __ sll(parameter_size, Interpreter::logStackElementSize, parameter_size);     // each argument size in bytes
 305   __ add(Lesp, parameter_size, Lesp);                                           // pop arguments
 306 
 307   __ check_and_handle_popframe(Gtemp);
 308   __ check_and_handle_earlyret(Gtemp);
 309 
 310   __ dispatch_next(state, step);
 311 
 312   return entry;
 313 }
 314 
 315 
 316 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step, address continuation) {
 317   address entry = __ pc();
 318   __ get_constant_pool_cache(LcpoolCache); // load LcpoolCache
 319 #if INCLUDE_JVMCI
 320   // Check if we need to take lock at entry of synchronized method.  This can
 321   // only occur on method entry so emit it only for vtos with step 0.
 322   if (EnableJVMCI && state == vtos && step == 0) {
 323     Label L;
 324     Address pending_monitor_enter_addr(G2_thread, JavaThread::pending_monitorenter_offset());
 325     __ ldbool(pending_monitor_enter_addr, Gtemp);  // Load if pending monitor enter
 326     __ cmp_and_br_short(Gtemp, G0, Assembler::equal, Assembler::pn, L);
 327     // Clear flag.
 328     __ stbool(G0, pending_monitor_enter_addr);
 329     // Take lock.
 330     lock_method();
 331     __ bind(L);
 332   } else {
 333 #ifdef ASSERT
 334     if (EnableJVMCI) {
 335       Label L;
 336       Address pending_monitor_enter_addr(G2_thread, JavaThread::pending_monitorenter_offset());
 337       __ ldbool(pending_monitor_enter_addr, Gtemp);  // Load if pending monitor enter
 338       __ cmp_and_br_short(Gtemp, G0, Assembler::equal, Assembler::pn, L);
 339       __ stop("unexpected pending monitor in deopt entry");
 340       __ bind(L);
 341     }
 342 #endif
 343   }
 344 #endif
 345   { Label L;
 346     Address exception_addr(G2_thread, Thread::pending_exception_offset());
 347     __ ld_ptr(exception_addr, Gtemp);  // Load pending exception.
 348     __ br_null_short(Gtemp, Assembler::pt, L);
 349     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_pending_exception));
 350     __ should_not_reach_here();
 351     __ bind(L);
 352   }
 353   if (continuation == NULL) {
 354     __ dispatch_next(state, step);
 355   } else {
 356     __ jump_to_entry(continuation);
 357   }
 358   return entry;
 359 }
 360 
 361 // A result handler converts/unboxes a native call result into
 362 // a java interpreter/compiler result. The current frame is an
 363 // interpreter frame. The activation frame unwind code must be
 364 // consistent with that of TemplateTable::_return(...). In the
 365 // case of native methods, the caller's SP was not modified.
 366 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 367   address entry = __ pc();
 368   Register Itos_i  = Otos_i ->after_save();
 369   Register Itos_l  = Otos_l ->after_save();
 370   Register Itos_l1 = Otos_l1->after_save();
 371   Register Itos_l2 = Otos_l2->after_save();
 372   switch (type) {
 373     case T_BOOLEAN: __ subcc(G0, O0, G0); __ addc(G0, 0, Itos_i); break; // !0 => true; 0 => false
 374     case T_CHAR   : __ sll(O0, 16, O0); __ srl(O0, 16, Itos_i);   break; // cannot use and3, 0xFFFF too big as immediate value!
 375     case T_BYTE   : __ sll(O0, 24, O0); __ sra(O0, 24, Itos_i);   break;
 376     case T_SHORT  : __ sll(O0, 16, O0); __ sra(O0, 16, Itos_i);   break;
 377     case T_LONG   :
 378     case T_INT    : __ mov(O0, Itos_i);                         break;
 379     case T_VOID   : /* nothing to do */                         break;
 380     case T_FLOAT  : assert(F0 == Ftos_f, "fix this code" );     break;
 381     case T_DOUBLE : assert(F0 == Ftos_d, "fix this code" );     break;
 382     case T_OBJECT :
 383       __ ld_ptr(FP, (frame::interpreter_frame_oop_temp_offset*wordSize) + STACK_BIAS, Itos_i);
 384       __ verify_oop(Itos_i);
 385       break;
 386     default       : ShouldNotReachHere();
 387   }
 388   __ ret();                           // return from interpreter activation
 389   __ delayed()->restore(I5_savedSP, G0, SP);  // remove interpreter frame
 390   NOT_PRODUCT(__ emit_int32(0);)       // marker for disassembly
 391   return entry;
 392 }
 393 
 394 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 395   address entry = __ pc();
 396   __ push(state);
 397   __ call_VM(noreg, runtime_entry);
 398   __ dispatch_via(vtos, Interpreter::normal_table(vtos));
 399   return entry;
 400 }
 401 
 402 
 403 //
 404 // Helpers for commoning out cases in the various type of method entries.
 405 //
 406 
 407 // increment invocation count & check for overflow
 408 //
 409 // Note: checking for negative value instead of overflow
 410 //       so we have a 'sticky' overflow test
 411 //
 412 // Lmethod: method
 413 // ??: invocation counter
 414 //
 415 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
 416   // Note: In tiered we increment either counters in MethodCounters* or in
 417   // MDO depending if we're profiling or not.
 418   const Register G3_method_counters = G3_scratch;
 419   Label done;
 420 
 421   if (TieredCompilation) {
 422     const int increment = InvocationCounter::count_increment;
 423     Label no_mdo;
 424     if (ProfileInterpreter) {
 425       // If no method data exists, go to profile_continue.
 426       __ ld_ptr(Lmethod, Method::method_data_offset(), G4_scratch);
 427       __ br_null_short(G4_scratch, Assembler::pn, no_mdo);
 428       // Increment counter
 429       Address mdo_invocation_counter(G4_scratch,
 430                                      in_bytes(MethodData::invocation_counter_offset()) +
 431                                      in_bytes(InvocationCounter::counter_offset()));
 432       Address mask(G4_scratch, in_bytes(MethodData::invoke_mask_offset()));
 433       __ increment_mask_and_jump(mdo_invocation_counter, increment, mask,
 434                                  G3_scratch, Lscratch,
 435                                  Assembler::zero, overflow);
 436       __ ba_short(done);
 437     }
 438 
 439     // Increment counter in MethodCounters*
 440     __ bind(no_mdo);
 441     Address invocation_counter(G3_method_counters,
 442             in_bytes(MethodCounters::invocation_counter_offset()) +
 443             in_bytes(InvocationCounter::counter_offset()));
 444     __ get_method_counters(Lmethod, G3_method_counters, done);
 445     Address mask(G3_method_counters, in_bytes(MethodCounters::invoke_mask_offset()));
 446     __ increment_mask_and_jump(invocation_counter, increment, mask,
 447                                G4_scratch, Lscratch,
 448                                Assembler::zero, overflow);
 449     __ bind(done);
 450   } else { // not TieredCompilation
 451     // Update standard invocation counters
 452     __ get_method_counters(Lmethod, G3_method_counters, done);
 453     __ increment_invocation_counter(G3_method_counters, O0, G4_scratch);
 454     if (ProfileInterpreter) {
 455       Address interpreter_invocation_counter(G3_method_counters,
 456             in_bytes(MethodCounters::interpreter_invocation_counter_offset()));
 457       __ ld(interpreter_invocation_counter, G4_scratch);
 458       __ inc(G4_scratch);
 459       __ st(G4_scratch, interpreter_invocation_counter);
 460     }
 461 
 462     if (ProfileInterpreter && profile_method != NULL) {
 463       // Test to see if we should create a method data oop
 464       Address profile_limit(G3_method_counters, in_bytes(MethodCounters::interpreter_profile_limit_offset()));
 465       __ ld(profile_limit, G1_scratch);
 466       __ cmp_and_br_short(O0, G1_scratch, Assembler::lessUnsigned, Assembler::pn, *profile_method_continue);
 467 
 468       // if no method data exists, go to profile_method
 469       __ test_method_data_pointer(*profile_method);
 470     }
 471 
 472     Address invocation_limit(G3_method_counters, in_bytes(MethodCounters::interpreter_invocation_limit_offset()));
 473     __ ld(invocation_limit, G3_scratch);
 474     __ cmp(O0, G3_scratch);
 475     __ br(Assembler::greaterEqualUnsigned, false, Assembler::pn, *overflow); // Far distance
 476     __ delayed()->nop();
 477     __ bind(done);
 478   }
 479 }
 480 
 481 // Allocate monitor and lock method (asm interpreter)
 482 // ebx - Method*
 483 //
 484 void TemplateInterpreterGenerator::lock_method() {
 485   __ ld(Lmethod, in_bytes(Method::access_flags_offset()), O0);  // Load access flags.
 486 
 487 #ifdef ASSERT
 488  { Label ok;
 489    __ btst(JVM_ACC_SYNCHRONIZED, O0);
 490    __ br( Assembler::notZero, false, Assembler::pt, ok);
 491    __ delayed()->nop();
 492    __ stop("method doesn't need synchronization");
 493    __ bind(ok);
 494   }
 495 #endif // ASSERT
 496 
 497   // get synchronization object to O0
 498   { Label done;
 499     __ btst(JVM_ACC_STATIC, O0);
 500     __ br( Assembler::zero, true, Assembler::pt, done);
 501     __ delayed()->ld_ptr(Llocals, Interpreter::local_offset_in_bytes(0), O0); // get receiver for not-static case
 502 
 503     // lock the mirror, not the Klass*
 504     __ load_mirror(O0, Lmethod);
 505 
 506 #ifdef ASSERT
 507     __ tst(O0);
 508     __ breakpoint_trap(Assembler::zero, Assembler::ptr_cc);
 509 #endif // ASSERT
 510 
 511     __ bind(done);
 512   }
 513 
 514   __ add_monitor_to_stack(true, noreg, noreg);  // allocate monitor elem
 515   __ st_ptr( O0, Lmonitors, BasicObjectLock::obj_offset_in_bytes());   // store object
 516   // __ untested("lock_object from method entry");
 517   __ lock_object(Lmonitors, O0);
 518 }
 519 
 520 // See if we've got enough room on the stack for locals plus overhead below
 521 // JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 522 // without going through the signal handler, i.e., reserved and yellow zones
 523 // will not be made usable. The shadow zone must suffice to handle the
 524 // overflow.
 525 void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rframe_size,
 526                                                                  Register Rscratch) {
 527   const int page_size = os::vm_page_size();
 528   Label after_frame_check;
 529 
 530   assert_different_registers(Rframe_size, Rscratch);
 531 
 532   __ set(page_size, Rscratch);
 533   __ cmp_and_br_short(Rframe_size, Rscratch, Assembler::lessEqual, Assembler::pt, after_frame_check);
 534 
 535   // Get the stack overflow limit, and in debug, verify it is non-zero.
 536   __ ld_ptr(G2_thread, JavaThread::stack_overflow_limit_offset(), Rscratch);
 537 #ifdef ASSERT
 538   Label limit_ok;
 539   __ br_notnull_short(Rscratch, Assembler::pn, limit_ok);
 540   __ stop("stack overflow limit is zero in generate_stack_overflow_check");
 541   __ bind(limit_ok);
 542 #endif
 543 
 544   // Add in the size of the frame (which is the same as subtracting it from the
 545   // SP, which would take another register.
 546   __ add(Rscratch, Rframe_size, Rscratch);
 547 
 548   // The frame is greater than one page in size, so check against
 549   // the bottom of the stack.
 550   __ cmp_and_brx_short(SP, Rscratch, Assembler::greaterUnsigned, Assembler::pt, after_frame_check);
 551 
 552   // The stack will overflow, throw an exception.
 553 
 554   // Note that SP is restored to sender's sp (in the delay slot). This
 555   // is necessary if the sender's frame is an extended compiled frame
 556   // (see gen_c2i_adapter()) and safer anyway in case of JSR292
 557   // adaptations.
 558 
 559   // Note also that the restored frame is not necessarily interpreted.
 560   // Use the shared runtime version of the StackOverflowError.
 561   assert(StubRoutines::throw_StackOverflowError_entry() != NULL, "stub not yet generated");
 562   AddressLiteral stub(StubRoutines::throw_StackOverflowError_entry());
 563   __ jump_to(stub, Rscratch);
 564   __ delayed()->mov(O5_savedSP, SP);
 565 
 566   // If you get to here, then there is enough stack space.
 567   __ bind(after_frame_check);
 568 }
 569 
 570 
 571 //
 572 // Generate a fixed interpreter frame. This is identical setup for interpreted
 573 // methods and for native methods hence the shared code.
 574 
 575 
 576 //----------------------------------------------------------------------------------------------------
 577 // Stack frame layout
 578 //
 579 // When control flow reaches any of the entry types for the interpreter
 580 // the following holds ->
 581 //
 582 // C2 Calling Conventions:
 583 //
 584 // The entry code below assumes that the following registers are set
 585 // when coming in:
 586 //    G5_method: holds the Method* of the method to call
 587 //    Lesp:    points to the TOS of the callers expression stack
 588 //             after having pushed all the parameters
 589 //
 590 // The entry code does the following to setup an interpreter frame
 591 //   pop parameters from the callers stack by adjusting Lesp
 592 //   set O0 to Lesp
 593 //   compute X = (max_locals - num_parameters)
 594 //   bump SP up by X to accommodate the extra locals
 595 //   compute X = max_expression_stack
 596 //               + vm_local_words
 597 //               + 16 words of register save area
 598 //   save frame doing a save sp, -X, sp growing towards lower addresses
 599 //   set Lbcp, Lmethod, LcpoolCache
 600 //   set Llocals to i0
 601 //   set Lmonitors to FP - rounded_vm_local_words
 602 //   set Lesp to Lmonitors - 4
 603 //
 604 //  The frame has now been setup to do the rest of the entry code
 605 
 606 // Try this optimization:  Most method entries could live in a
 607 // "one size fits all" stack frame without all the dynamic size
 608 // calculations.  It might be profitable to do all this calculation
 609 // statically and approximately for "small enough" methods.
 610 
 611 //-----------------------------------------------------------------------------------------------
 612 
 613 // C1 Calling conventions
 614 //
 615 // Upon method entry, the following registers are setup:
 616 //
 617 // g2 G2_thread: current thread
 618 // g5 G5_method: method to activate
 619 // g4 Gargs  : pointer to last argument
 620 //
 621 //
 622 // Stack:
 623 //
 624 // +---------------+ <--- sp
 625 // |               |
 626 // : reg save area :
 627 // |               |
 628 // +---------------+ <--- sp + 0x40
 629 // |               |
 630 // : extra 7 slots :      note: these slots are not really needed for the interpreter (fix later)
 631 // |               |
 632 // +---------------+ <--- sp + 0x5c
 633 // |               |
 634 // :     free      :
 635 // |               |
 636 // +---------------+ <--- Gargs
 637 // |               |
 638 // :   arguments   :
 639 // |               |
 640 // +---------------+
 641 // |               |
 642 //
 643 //
 644 //
 645 // AFTER FRAME HAS BEEN SETUP for method interpretation the stack looks like:
 646 //
 647 // +---------------+ <--- sp
 648 // |               |
 649 // : reg save area :
 650 // |               |
 651 // +---------------+ <--- sp + 0x40
 652 // |               |
 653 // : extra 7 slots :      note: these slots are not really needed for the interpreter (fix later)
 654 // |               |
 655 // +---------------+ <--- sp + 0x5c
 656 // |               |
 657 // :               :
 658 // |               | <--- Lesp
 659 // +---------------+ <--- Lmonitors (fp - 0x18)
 660 // |   VM locals   |
 661 // +---------------+ <--- fp
 662 // |               |
 663 // : reg save area :
 664 // |               |
 665 // +---------------+ <--- fp + 0x40
 666 // |               |
 667 // : extra 7 slots :      note: these slots are not really needed for the interpreter (fix later)
 668 // |               |
 669 // +---------------+ <--- fp + 0x5c
 670 // |               |
 671 // :     free      :
 672 // |               |
 673 // +---------------+
 674 // |               |
 675 // : nonarg locals :
 676 // |               |
 677 // +---------------+
 678 // |               |
 679 // :   arguments   :
 680 // |               | <--- Llocals
 681 // +---------------+ <--- Gargs
 682 // |               |
 683 
 684 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 685   //
 686   //
 687   // The entry code sets up a new interpreter frame in 4 steps:
 688   //
 689   // 1) Increase caller's SP by for the extra local space needed:
 690   //    (check for overflow)
 691   //    Efficient implementation of xload/xstore bytecodes requires
 692   //    that arguments and non-argument locals are in a contiguously
 693   //    addressable memory block => non-argument locals must be
 694   //    allocated in the caller's frame.
 695   //
 696   // 2) Create a new stack frame and register window:
 697   //    The new stack frame must provide space for the standard
 698   //    register save area, the maximum java expression stack size,
 699   //    the monitor slots (0 slots initially), and some frame local
 700   //    scratch locations.
 701   //
 702   // 3) The following interpreter activation registers must be setup:
 703   //    Lesp       : expression stack pointer
 704   //    Lbcp       : bytecode pointer
 705   //    Lmethod    : method
 706   //    Llocals    : locals pointer
 707   //    Lmonitors  : monitor pointer
 708   //    LcpoolCache: constant pool cache
 709   //
 710   // 4) Initialize the non-argument locals if necessary:
 711   //    Non-argument locals may need to be initialized to NULL
 712   //    for GC to work. If the oop-map information is accurate
 713   //    (in the absence of the JSR problem), no initialization
 714   //    is necessary.
 715   //
 716   // (gri - 2/25/2000)
 717 
 718 
 719   int rounded_vm_local_words = align_up((int)frame::interpreter_frame_vm_local_words, WordsPerLong );
 720 
 721   const int extra_space =
 722     rounded_vm_local_words +                   // frame local scratch space
 723     Method::extra_stack_entries() +            // extra stack for jsr 292
 724     frame::memory_parameter_word_sp_offset +   // register save area
 725     (native_call ? frame::interpreter_frame_extra_outgoing_argument_words : 0);
 726 
 727   const Register Glocals_size = G3;
 728   const Register RconstMethod = Glocals_size;
 729   const Register Otmp1 = O3;
 730   const Register Otmp2 = O4;
 731   // Lscratch can't be used as a temporary because the call_stub uses
 732   // it to assert that the stack frame was setup correctly.
 733   const Address constMethod       (G5_method, Method::const_offset());
 734   const Address size_of_parameters(RconstMethod, ConstMethod::size_of_parameters_offset());
 735 
 736   __ ld_ptr( constMethod, RconstMethod );
 737   __ lduh( size_of_parameters, Glocals_size);
 738 
 739   // Gargs points to first local + BytesPerWord
 740   // Set the saved SP after the register window save
 741   //
 742   assert_different_registers(Gargs, Glocals_size, Gframe_size, O5_savedSP);
 743   __ sll(Glocals_size, Interpreter::logStackElementSize, Otmp1);
 744   __ add(Gargs, Otmp1, Gargs);
 745 
 746   if (native_call) {
 747     __ calc_mem_param_words( Glocals_size, Gframe_size );
 748     __ add( Gframe_size,  extra_space, Gframe_size);
 749     __ round_to( Gframe_size, WordsPerLong );
 750     __ sll( Gframe_size, LogBytesPerWord, Gframe_size );
 751 
 752     // Native calls don't need the stack size check since they have no
 753     // expression stack and the arguments are already on the stack and
 754     // we only add a handful of words to the stack.
 755   } else {
 756 
 757     //
 758     // Compute number of locals in method apart from incoming parameters
 759     //
 760     const Address size_of_locals(Otmp1, ConstMethod::size_of_locals_offset());
 761     __ ld_ptr(constMethod, Otmp1);
 762     __ lduh(size_of_locals, Otmp1);
 763     __ sub(Otmp1, Glocals_size, Glocals_size);
 764     __ round_to(Glocals_size, WordsPerLong);
 765     __ sll(Glocals_size, Interpreter::logStackElementSize, Glocals_size);
 766 
 767     // See if the frame is greater than one page in size. If so,
 768     // then we need to verify there is enough stack space remaining.
 769     // Frame_size = (max_stack + extra_space) * BytesPerWord;
 770     __ ld_ptr(constMethod, Gframe_size);
 771     __ lduh(Gframe_size, in_bytes(ConstMethod::max_stack_offset()), Gframe_size);
 772     __ add(Gframe_size, extra_space, Gframe_size);
 773     __ round_to(Gframe_size, WordsPerLong);
 774     __ sll(Gframe_size, Interpreter::logStackElementSize, Gframe_size);
 775 
 776     // Add in java locals size for stack overflow check only
 777     __ add(Gframe_size, Glocals_size, Gframe_size);
 778 
 779     const Register Otmp2 = O4;
 780     assert_different_registers(Otmp1, Otmp2, O5_savedSP);
 781     generate_stack_overflow_check(Gframe_size, Otmp1);
 782 
 783     __ sub(Gframe_size, Glocals_size, Gframe_size);
 784 
 785     //
 786     // bump SP to accommodate the extra locals
 787     //
 788     __ sub(SP, Glocals_size, SP);
 789   }
 790 
 791   //
 792   // now set up a stack frame with the size computed above
 793   //
 794   __ neg( Gframe_size );
 795   __ save( SP, Gframe_size, SP );
 796 
 797   //
 798   // now set up all the local cache registers
 799   //
 800   // NOTE: At this point, Lbyte_code/Lscratch has been modified. Note
 801   // that all present references to Lbyte_code initialize the register
 802   // immediately before use
 803   if (native_call) {
 804     __ mov(G0, Lbcp);
 805   } else {
 806     __ ld_ptr(G5_method, Method::const_offset(), Lbcp);
 807     __ add(Lbcp, in_bytes(ConstMethod::codes_offset()), Lbcp);
 808   }
 809   __ mov( G5_method, Lmethod);                 // set Lmethod
 810   // Get mirror and store it in the frame as GC root for this Method*
 811   Register mirror = LcpoolCache;
 812   __ load_mirror(mirror, Lmethod);
 813   __ st_ptr(mirror, FP, (frame::interpreter_frame_mirror_offset * wordSize) + STACK_BIAS);
 814   __ get_constant_pool_cache(LcpoolCache);     // set LcpoolCache
 815   __ sub(FP, rounded_vm_local_words * BytesPerWord, Lmonitors ); // set Lmonitors
 816   __ add(Lmonitors, STACK_BIAS, Lmonitors);    // Account for 64 bit stack bias
 817   __ sub(Lmonitors, BytesPerWord, Lesp);       // set Lesp
 818 
 819   // setup interpreter activation registers
 820   __ sub(Gargs, BytesPerWord, Llocals);        // set Llocals
 821 
 822   if (ProfileInterpreter) {
 823     __ set_method_data_pointer();
 824   }
 825 
 826 }
 827 
 828 // Method entry for java.lang.ref.Reference.get.
 829 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 830 #if INCLUDE_ALL_GCS
 831   // Code: _aload_0, _getfield, _areturn
 832   // parameter size = 1
 833   //
 834   // The code that gets generated by this routine is split into 2 parts:
 835   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 836   //    2. The slow path - which is an expansion of the regular method entry.
 837   //
 838   // Notes:-
 839   // * In the G1 code we do not check whether we need to block for
 840   //   a safepoint. If G1 is enabled then we must execute the specialized
 841   //   code for Reference.get (except when the Reference object is null)
 842   //   so that we can log the value in the referent field with an SATB
 843   //   update buffer.
 844   //   If the code for the getfield template is modified so that the
 845   //   G1 pre-barrier code is executed when the current method is
 846   //   Reference.get() then going through the normal method entry
 847   //   will be fine.
 848   // * The G1 code can, however, check the receiver object (the instance
 849   //   of java.lang.Reference) and jump to the slow path if null. If the
 850   //   Reference object is null then we obviously cannot fetch the referent
 851   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 852   //   regular method entry code to generate the NPE.
 853   //
 854   // This code is based on generate_accessor_enty.
 855 
 856   address entry = __ pc();
 857 
 858   const int referent_offset = java_lang_ref_Reference::referent_offset;
 859   guarantee(referent_offset > 0, "referent offset not initialized");
 860 
 861   if (UseG1GC) {
 862      Label slow_path;
 863 
 864     // In the G1 code we don't check if we need to reach a safepoint. We
 865     // continue and the thread will safepoint at the next bytecode dispatch.
 866 
 867     // Check if local 0 != NULL
 868     // If the receiver is null then it is OK to jump to the slow path.
 869     __ ld_ptr(Gargs, G0, Otos_i ); // get local 0
 870     // check if local 0 == NULL and go the slow path
 871     __ cmp_and_brx_short(Otos_i, 0, Assembler::equal, Assembler::pn, slow_path);
 872 
 873 
 874     // Load the value of the referent field.
 875     if (Assembler::is_simm13(referent_offset)) {
 876       __ load_heap_oop(Otos_i, referent_offset, Otos_i);
 877     } else {
 878       __ set(referent_offset, G3_scratch);
 879       __ load_heap_oop(Otos_i, G3_scratch, Otos_i);
 880     }
 881 
 882     // Generate the G1 pre-barrier code to log the value of
 883     // the referent field in an SATB buffer. Note with
 884     // these parameters the pre-barrier does not generate
 885     // the load of the previous value
 886 
 887     __ g1_write_barrier_pre(noreg /* obj */, noreg /* index */, 0 /* offset */,
 888                             Otos_i /* pre_val */,
 889                             G3_scratch /* tmp */,
 890                             true /* preserve_o_regs */);
 891 
 892     // _areturn
 893     __ retl();                      // return from leaf routine
 894     __ delayed()->mov(O5_savedSP, SP);
 895 
 896     // Generate regular method entry
 897     __ bind(slow_path);
 898     __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 899     return entry;
 900   }
 901 #endif // INCLUDE_ALL_GCS
 902 
 903   // If G1 is not enabled then attempt to go through the accessor entry point
 904   // Reference.get is an accessor
 905   return NULL;
 906 }
 907 
 908 /**
 909  * Method entry for static native methods:
 910  *   int java.util.zip.CRC32.update(int crc, int b)
 911  */
 912 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
 913 
 914   if (UseCRC32Intrinsics) {
 915     address entry = __ pc();
 916 
 917     Label L_slow_path;
 918     // If we need a safepoint check, generate full interpreter entry.
 919     __ safepoint_poll(L_slow_path, false, G2_thread, O2);
 920     __ delayed()->nop();
 921 
 922     // Load parameters
 923     const Register crc   = O0; // initial crc
 924     const Register val   = O1; // byte to update with
 925     const Register table = O2; // address of 256-entry lookup table
 926 
 927     __ ldub(Gargs, 3, val);
 928     __ lduw(Gargs, 8, crc);
 929 
 930     __ set(ExternalAddress(StubRoutines::crc_table_addr()), table);
 931 
 932     __ not1(crc); // ~crc
 933     __ clruwu(crc);
 934     __ update_byte_crc32(crc, val, table);
 935     __ not1(crc); // ~crc
 936 
 937     // result in O0
 938     __ retl();
 939     __ delayed()->nop();
 940 
 941     // generate a vanilla native entry as the slow path
 942     __ bind(L_slow_path);
 943     __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
 944     return entry;
 945   }
 946   return NULL;
 947 }
 948 
 949 /**
 950  * Method entry for static native methods:
 951  *   int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len)
 952  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
 953  */
 954 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
 955 
 956   if (UseCRC32Intrinsics) {
 957     address entry = __ pc();
 958 
 959     Label L_slow_path;
 960     // If we need a safepoint check, generate full interpreter entry.
 961 
 962     __ safepoint_poll(L_slow_path, false, G2_thread, O2);
 963     __ delayed()->nop();
 964 
 965     // Load parameters from the stack
 966     const Register crc    = O0; // initial crc
 967     const Register buf    = O1; // source java byte array address
 968     const Register len    = O2; // len
 969     const Register offset = O3; // offset
 970 
 971     // Arguments are reversed on java expression stack
 972     // Calculate address of start element
 973     if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) {
 974       __ lduw(Gargs, 0,  len);
 975       __ lduw(Gargs, 8,  offset);
 976       __ ldx( Gargs, 16, buf);
 977       __ lduw(Gargs, 32, crc);
 978       __ add(buf, offset, buf);
 979     } else {
 980       __ lduw(Gargs, 0,  len);
 981       __ lduw(Gargs, 8,  offset);
 982       __ ldx( Gargs, 16, buf);
 983       __ lduw(Gargs, 24, crc);
 984       __ add(buf, arrayOopDesc::base_offset_in_bytes(T_BYTE), buf); // account for the header size
 985       __ add(buf, offset, buf);
 986     }
 987 
 988     // Call the crc32 kernel
 989     __ MacroAssembler::save_thread(L7_thread_cache);
 990     __ kernel_crc32(crc, buf, len, O3);
 991     __ MacroAssembler::restore_thread(L7_thread_cache);
 992 
 993     // result in O0
 994     __ retl();
 995     __ delayed()->nop();
 996 
 997     // generate a vanilla native entry as the slow path
 998     __ bind(L_slow_path);
 999     __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1000     return entry;
1001   }
1002   return NULL;
1003 }
1004 
1005 /**
1006  * Method entry for intrinsic-candidate (non-native) methods:
1007  *   int java.util.zip.CRC32C.updateBytes(int crc, byte[] b, int off, int end)
1008  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
1009  * Unlike CRC32, CRC32C does not have any methods marked as native
1010  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1011  */
1012 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1013 
1014   if (UseCRC32CIntrinsics) {
1015     address entry = __ pc();
1016 
1017     // Load parameters from the stack
1018     const Register crc    = O0; // initial crc
1019     const Register buf    = O1; // source java byte array address
1020     const Register offset = O2; // offset
1021     const Register end    = O3; // index of last element to process
1022     const Register len    = O2; // len argument to the kernel
1023     const Register table  = O3; // crc32c lookup table address
1024 
1025     // Arguments are reversed on java expression stack
1026     // Calculate address of start element
1027     if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) {
1028       __ lduw(Gargs, 0,  end);
1029       __ lduw(Gargs, 8,  offset);
1030       __ ldx( Gargs, 16, buf);
1031       __ lduw(Gargs, 32, crc);
1032       __ add(buf, offset, buf);
1033       __ sub(end, offset, len);
1034     } else {
1035       __ lduw(Gargs, 0,  end);
1036       __ lduw(Gargs, 8,  offset);
1037       __ ldx( Gargs, 16, buf);
1038       __ lduw(Gargs, 24, crc);
1039       __ add(buf, arrayOopDesc::base_offset_in_bytes(T_BYTE), buf); // account for the header size
1040       __ add(buf, offset, buf);
1041       __ sub(end, offset, len);
1042     }
1043 
1044     // Call the crc32c kernel
1045     __ MacroAssembler::save_thread(L7_thread_cache);
1046     __ kernel_crc32c(crc, buf, len, table);
1047     __ MacroAssembler::restore_thread(L7_thread_cache);
1048 
1049     // result in O0
1050     __ retl();
1051     __ delayed()->nop();
1052 
1053     return entry;
1054   }
1055   return NULL;
1056 }
1057 
1058 /* Math routines only partially supported.
1059  *
1060  *   Providing support for fma (float/double) only.
1061  */
1062 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind)
1063 {
1064   if (!InlineIntrinsics) return NULL; // Generate a vanilla entry
1065 
1066   address entry = __ pc();
1067 
1068   switch (kind) {
1069     case Interpreter::java_lang_math_fmaF:
1070       if (UseFMA) {
1071         // float .fma(float a, float b, float c)
1072         const FloatRegister ra = F1;
1073         const FloatRegister rb = F2;
1074         const FloatRegister rc = F3;
1075         const FloatRegister rd = F0; // Result.
1076 
1077         __ ldf(FloatRegisterImpl::S, Gargs,  0, rc);
1078         __ ldf(FloatRegisterImpl::S, Gargs,  8, rb);
1079         __ ldf(FloatRegisterImpl::S, Gargs, 16, ra);
1080 
1081         __ fmadd(FloatRegisterImpl::S, ra, rb, rc, rd);
1082         __ retl();  // Result in F0 (rd).
1083         __ delayed()->mov(O5_savedSP, SP);
1084 
1085         return entry;
1086       }
1087       break;
1088     case Interpreter::java_lang_math_fmaD:
1089       if (UseFMA) {
1090         // double .fma(double a, double b, double c)
1091         const FloatRegister ra = F2; // D1
1092         const FloatRegister rb = F4; // D2
1093         const FloatRegister rc = F6; // D3
1094         const FloatRegister rd = F0; // D0 Result.
1095 
1096         __ ldf(FloatRegisterImpl::D, Gargs,  0, rc);
1097         __ ldf(FloatRegisterImpl::D, Gargs, 16, rb);
1098         __ ldf(FloatRegisterImpl::D, Gargs, 32, ra);
1099 
1100         __ fmadd(FloatRegisterImpl::D, ra, rb, rc, rd);
1101         __ retl();  // Result in D0 (rd).
1102         __ delayed()->mov(O5_savedSP, SP);
1103 
1104         return entry;
1105       }
1106       break;
1107     default:
1108       break;
1109   }
1110   return NULL;
1111 }
1112 
1113 // TODO: rather than touching all pages, check against stack_overflow_limit and bang yellow page to
1114 // generate exception
1115 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1116   // Quick & dirty stack overflow checking: bang the stack & handle trap.
1117   // Note that we do the banging after the frame is setup, since the exception
1118   // handling code expects to find a valid interpreter frame on the stack.
1119   // Doing the banging earlier fails if the caller frame is not an interpreter
1120   // frame.
1121   // (Also, the exception throwing code expects to unlock any synchronized
1122   // method receiver, so do the banging after locking the receiver.)
1123 
1124   // Bang each page in the shadow zone. We can't assume it's been done for
1125   // an interpreter frame with greater than a page of locals, so each page
1126   // needs to be checked.  Only true for non-native.
1127   if (UseStackBanging) {
1128     const int page_size = os::vm_page_size();
1129     const int n_shadow_pages = ((int)JavaThread::stack_shadow_zone_size()) / page_size;
1130     const int start_page = native_call ? n_shadow_pages : 1;
1131     for (int pages = start_page; pages <= n_shadow_pages; pages++) {
1132       __ bang_stack_with_offset(pages*page_size);
1133     }
1134   }
1135 }
1136 
1137 //
1138 // Interpreter stub for calling a native method. (asm interpreter)
1139 // This sets up a somewhat different looking stack for calling the native method
1140 // than the typical interpreter frame setup.
1141 //
1142 
1143 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1144   address entry = __ pc();
1145 
1146   // the following temporary registers are used during frame creation
1147   const Register Gtmp1 = G3_scratch ;
1148   const Register Gtmp2 = G1_scratch;
1149   bool inc_counter  = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1150 
1151   // make sure registers are different!
1152   assert_different_registers(G2_thread, G5_method, Gargs, Gtmp1, Gtmp2);
1153 
1154   const Address Laccess_flags(Lmethod, Method::access_flags_offset());
1155 
1156   const Register Glocals_size = G3;
1157   assert_different_registers(Glocals_size, G4_scratch, Gframe_size);
1158 
1159   // make sure method is native & not abstract
1160   // rethink these assertions - they can be simplified and shared (gri 2/25/2000)
1161 #ifdef ASSERT
1162   __ ld(G5_method, Method::access_flags_offset(), Gtmp1);
1163   { Label L;
1164     __ btst(JVM_ACC_NATIVE, Gtmp1);
1165     __ br(Assembler::notZero, false, Assembler::pt, L);
1166     __ delayed()->nop();
1167     __ stop("tried to execute non-native method as native");
1168     __ bind(L);
1169   }
1170   { Label L;
1171     __ btst(JVM_ACC_ABSTRACT, Gtmp1);
1172     __ br(Assembler::zero, false, Assembler::pt, L);
1173     __ delayed()->nop();
1174     __ stop("tried to execute abstract method as non-abstract");
1175     __ bind(L);
1176   }
1177 #endif // ASSERT
1178 
1179  // generate the code to allocate the interpreter stack frame
1180   generate_fixed_frame(true);
1181 
1182   //
1183   // No locals to initialize for native method
1184   //
1185 
1186   // this slot will be set later, we initialize it to null here just in
1187   // case we get a GC before the actual value is stored later
1188   __ st_ptr(G0, FP, (frame::interpreter_frame_oop_temp_offset * wordSize) + STACK_BIAS);
1189 
1190   const Address do_not_unlock_if_synchronized(G2_thread,
1191     JavaThread::do_not_unlock_if_synchronized_offset());
1192   // Since at this point in the method invocation the exception handler
1193   // would try to exit the monitor of synchronized methods which hasn't
1194   // been entered yet, we set the thread local variable
1195   // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1196   // runtime, exception handling i.e. unlock_if_synchronized_method will
1197   // check this thread local flag.
1198   // This flag has two effects, one is to force an unwind in the topmost
1199   // interpreter frame and not perform an unlock while doing so.
1200 
1201   __ movbool(true, G3_scratch);
1202   __ stbool(G3_scratch, do_not_unlock_if_synchronized);
1203 
1204   // increment invocation counter and check for overflow
1205   //
1206   // Note: checking for negative value instead of overflow
1207   //       so we have a 'sticky' overflow test (may be of
1208   //       importance as soon as we have true MT/MP)
1209   Label invocation_counter_overflow;
1210   Label Lcontinue;
1211   if (inc_counter) {
1212     generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
1213 
1214   }
1215   __ bind(Lcontinue);
1216 
1217   bang_stack_shadow_pages(true);
1218 
1219   // reset the _do_not_unlock_if_synchronized flag
1220   __ stbool(G0, do_not_unlock_if_synchronized);
1221 
1222   // check for synchronized methods
1223   // Must happen AFTER invocation_counter check and stack overflow check,
1224   // so method is not locked if overflows.
1225 
1226   if (synchronized) {
1227     lock_method();
1228   } else {
1229 #ifdef ASSERT
1230     { Label ok;
1231       __ ld(Laccess_flags, O0);
1232       __ btst(JVM_ACC_SYNCHRONIZED, O0);
1233       __ br( Assembler::zero, false, Assembler::pt, ok);
1234       __ delayed()->nop();
1235       __ stop("method needs synchronization");
1236       __ bind(ok);
1237     }
1238 #endif // ASSERT
1239   }
1240 
1241 
1242   // start execution
1243   __ verify_thread();
1244 
1245   // JVMTI support
1246   __ notify_method_entry();
1247 
1248   // native call
1249 
1250   // (note that O0 is never an oop--at most it is a handle)
1251   // It is important not to smash any handles created by this call,
1252   // until any oop handle in O0 is dereferenced.
1253 
1254   // (note that the space for outgoing params is preallocated)
1255 
1256   // get signature handler
1257   { Label L;
1258     Address signature_handler(Lmethod, Method::signature_handler_offset());
1259     __ ld_ptr(signature_handler, G3_scratch);
1260     __ br_notnull_short(G3_scratch, Assembler::pt, L);
1261     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), Lmethod);
1262     __ ld_ptr(signature_handler, G3_scratch);
1263     __ bind(L);
1264   }
1265 
1266   // Push a new frame so that the args will really be stored in
1267   // Copy a few locals across so the new frame has the variables
1268   // we need but these values will be dead at the jni call and
1269   // therefore not gc volatile like the values in the current
1270   // frame (Lmethod in particular)
1271 
1272   // Flush the method pointer to the register save area
1273   __ st_ptr(Lmethod, SP, (Lmethod->sp_offset_in_saved_window() * wordSize) + STACK_BIAS);
1274   __ mov(Llocals, O1);
1275 
1276   // calculate where the mirror handle body is allocated in the interpreter frame:
1277   __ add(FP, (frame::interpreter_frame_oop_temp_offset * wordSize) + STACK_BIAS, O2);
1278 
1279   // Calculate current frame size
1280   __ sub(SP, FP, O3);         // Calculate negative of current frame size
1281   __ save(SP, O3, SP);        // Allocate an identical sized frame
1282 
1283   // Note I7 has leftover trash. Slow signature handler will fill it in
1284   // should we get there. Normal jni call will set reasonable last_Java_pc
1285   // below (and fix I7 so the stack trace doesn't have a meaningless frame
1286   // in it).
1287 
1288   // Load interpreter frame's Lmethod into same register here
1289 
1290   __ ld_ptr(FP, (Lmethod->sp_offset_in_saved_window() * wordSize) + STACK_BIAS, Lmethod);
1291 
1292   __ mov(I1, Llocals);
1293   __ mov(I2, Lscratch2);     // save the address of the mirror
1294 
1295 
1296   // ONLY Lmethod and Llocals are valid here!
1297 
1298   // call signature handler, It will move the arg properly since Llocals in current frame
1299   // matches that in outer frame
1300 
1301   __ callr(G3_scratch, 0);
1302   __ delayed()->nop();
1303 
1304   // Result handler is in Lscratch
1305 
1306   // Reload interpreter frame's Lmethod since slow signature handler may block
1307   __ ld_ptr(FP, (Lmethod->sp_offset_in_saved_window() * wordSize) + STACK_BIAS, Lmethod);
1308 
1309   { Label not_static;
1310 
1311     __ ld(Laccess_flags, O0);
1312     __ btst(JVM_ACC_STATIC, O0);
1313     __ br( Assembler::zero, false, Assembler::pt, not_static);
1314     // get native function entry point(O0 is a good temp until the very end)
1315     __ delayed()->ld_ptr(Lmethod, in_bytes(Method::native_function_offset()), O0);
1316     // for static methods insert the mirror argument
1317     __ load_mirror(O1, Lmethod);
1318 #ifdef ASSERT
1319     if (!PrintSignatureHandlers)  // do not dirty the output with this
1320     { Label L;
1321       __ br_notnull_short(O1, Assembler::pt, L);
1322       __ stop("mirror is missing");
1323       __ bind(L);
1324     }
1325 #endif // ASSERT
1326     __ st_ptr(O1, Lscratch2, 0);
1327     __ mov(Lscratch2, O1);
1328     __ bind(not_static);
1329   }
1330 
1331   // At this point, arguments have been copied off of stack into
1332   // their JNI positions, which are O1..O5 and SP[68..].
1333   // Oops are boxed in-place on the stack, with handles copied to arguments.
1334   // The result handler is in Lscratch.  O0 will shortly hold the JNIEnv*.
1335 
1336 #ifdef ASSERT
1337   { Label L;
1338     __ br_notnull_short(O0, Assembler::pt, L);
1339     __ stop("native entry point is missing");
1340     __ bind(L);
1341   }
1342 #endif // ASSERT
1343 
1344   //
1345   // setup the frame anchor
1346   //
1347   // The scavenge function only needs to know that the PC of this frame is
1348   // in the interpreter method entry code, it doesn't need to know the exact
1349   // PC and hence we can use O7 which points to the return address from the
1350   // previous call in the code stream (signature handler function)
1351   //
1352   // The other trick is we set last_Java_sp to FP instead of the usual SP because
1353   // we have pushed the extra frame in order to protect the volatile register(s)
1354   // in that frame when we return from the jni call
1355   //
1356 
1357   __ set_last_Java_frame(FP, O7);
1358   __ mov(O7, I7);  // make dummy interpreter frame look like one above,
1359                    // not meaningless information that'll confuse me.
1360 
1361   // flush the windows now. We don't care about the current (protection) frame
1362   // only the outer frames
1363 
1364   __ flushw();
1365 
1366   // mark windows as flushed
1367   Address flags(G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::flags_offset());
1368   __ set(JavaFrameAnchor::flushed, G3_scratch);
1369   __ st(G3_scratch, flags);
1370 
1371   // Transition from _thread_in_Java to _thread_in_native. We are already safepoint ready.
1372 
1373   Address thread_state(G2_thread, JavaThread::thread_state_offset());
1374 #ifdef ASSERT
1375   { Label L;
1376     __ ld(thread_state, G3_scratch);
1377     __ cmp_and_br_short(G3_scratch, _thread_in_Java, Assembler::equal, Assembler::pt, L);
1378     __ stop("Wrong thread state in native stub");
1379     __ bind(L);
1380   }
1381 #endif // ASSERT
1382   __ set(_thread_in_native, G3_scratch);
1383   __ st(G3_scratch, thread_state);
1384 
1385   // Call the jni method, using the delay slot to set the JNIEnv* argument.
1386   __ save_thread(L7_thread_cache); // save Gthread
1387   __ callr(O0, 0);
1388   __ delayed()->
1389      add(L7_thread_cache, in_bytes(JavaThread::jni_environment_offset()), O0);
1390 
1391   // Back from jni method Lmethod in this frame is DEAD, DEAD, DEAD
1392 
1393   __ restore_thread(L7_thread_cache); // restore G2_thread
1394   __ reinit_heapbase();
1395 
1396   // must we block?
1397 
1398   // Block, if necessary, before resuming in _thread_in_Java state.
1399   // In order for GC to work, don't clear the last_Java_sp until after blocking.
1400   { Label no_block;
1401 
1402     // Switch thread to "native transition" state before reading the synchronization state.
1403     // This additional state is necessary because reading and testing the synchronization
1404     // state is not atomic w.r.t. GC, as this scenario demonstrates:
1405     //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1406     //     VM thread changes sync state to synchronizing and suspends threads for GC.
1407     //     Thread A is resumed to finish this native method, but doesn't block here since it
1408     //     didn't see any synchronization is progress, and escapes.
1409     __ set(_thread_in_native_trans, G3_scratch);
1410     __ st(G3_scratch, thread_state);
1411     if (os::is_MP()) {
1412       if (UseMembar) {
1413         // Force this write out before the read below
1414         __ membar(Assembler::StoreLoad);
1415       } else {
1416         // Write serialization page so VM thread can do a pseudo remote membar.
1417         // We use the current thread pointer to calculate a thread specific
1418         // offset to write to within the page. This minimizes bus traffic
1419         // due to cache line collision.
1420         __ serialize_memory(G2_thread, G1_scratch, G3_scratch);
1421       }
1422     }
1423 
1424     Label L;
1425     __ safepoint_poll(L, false, G2_thread, G3_scratch);
1426     __ delayed()->ld(G2_thread, JavaThread::suspend_flags_offset(), G3_scratch);
1427     __ cmp_and_br_short(G3_scratch, 0, Assembler::equal, Assembler::pt, no_block);
1428     __ bind(L);
1429 
1430     // Block.  Save any potential method result value before the operation and
1431     // use a leaf call to leave the last_Java_frame setup undisturbed.
1432     save_native_result();
1433     __ call_VM_leaf(L7_thread_cache,
1434                     CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans),
1435                     G2_thread);
1436 
1437     // Restore any method result value
1438     restore_native_result();
1439     __ bind(no_block);
1440   }
1441 
1442   // Clear the frame anchor now
1443 
1444   __ reset_last_Java_frame();
1445 
1446   // Move the result handler address
1447   __ mov(Lscratch, G3_scratch);
1448   // return possible result to the outer frame
1449   __ restore(O0, G0, O0);
1450 
1451   // Move result handler to expected register
1452   __ mov(G3_scratch, Lscratch);
1453 
1454   // Back in normal (native) interpreter frame. State is thread_in_native_trans
1455   // switch to thread_in_Java.
1456 
1457   __ set(_thread_in_Java, G3_scratch);
1458   __ st(G3_scratch, thread_state);
1459 
1460   if (CheckJNICalls) {
1461     // clear_pending_jni_exception_check
1462     __ st_ptr(G0, G2_thread, JavaThread::pending_jni_exception_check_fn_offset());
1463   }
1464 
1465   // reset handle block
1466   __ ld_ptr(G2_thread, JavaThread::active_handles_offset(), G3_scratch);
1467   __ st(G0, G3_scratch, JNIHandleBlock::top_offset_in_bytes());
1468 
1469   // If we have an oop result store it where it will be safe for any further gc
1470   // until we return now that we've released the handle it might be protected by
1471 
1472   { Label no_oop, store_result;
1473 
1474     __ set((intptr_t)AbstractInterpreter::result_handler(T_OBJECT), G3_scratch);
1475     __ cmp_and_brx_short(G3_scratch, Lscratch, Assembler::notEqual, Assembler::pt, no_oop);
1476     // Unbox oop result, e.g. JNIHandles::resolve value in O0.
1477     __ br_null(O0, false, Assembler::pn, store_result); // Use NULL as-is.
1478     __ delayed()->andcc(O0, JNIHandles::weak_tag_mask, G0); // Test for jweak
1479     __ brx(Assembler::zero, true, Assembler::pt, store_result);
1480     __ delayed()->ld_ptr(O0, 0, O0); // Maybe resolve (untagged) jobject.
1481     // Resolve jweak.
1482     __ ld_ptr(O0, -JNIHandles::weak_tag_value, O0);
1483 #if INCLUDE_ALL_GCS
1484     if (UseG1GC) {
1485       __ g1_write_barrier_pre(noreg /* obj */,
1486                               noreg /* index */,
1487                               0 /* offset */,
1488                               O0 /* pre_val */,
1489                               G3_scratch /* tmp */,
1490                               true /* preserve_o_regs */);
1491     }
1492 #endif // INCLUDE_ALL_GCS
1493     __ bind(store_result);
1494     // Store it where gc will look for it and result handler expects it.
1495     __ st_ptr(O0, FP, (frame::interpreter_frame_oop_temp_offset*wordSize) + STACK_BIAS);
1496 
1497     __ bind(no_oop);
1498 
1499   }
1500 
1501 
1502   // handle exceptions (exception handling will handle unlocking!)
1503   { Label L;
1504     Address exception_addr(G2_thread, Thread::pending_exception_offset());
1505     __ ld_ptr(exception_addr, Gtemp);
1506     __ br_null_short(Gtemp, Assembler::pt, L);
1507     // Note: This could be handled more efficiently since we know that the native
1508     //       method doesn't have an exception handler. We could directly return
1509     //       to the exception handler for the caller.
1510     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_pending_exception));
1511     __ should_not_reach_here();
1512     __ bind(L);
1513   }
1514 
1515   // JVMTI support (preserves thread register)
1516   __ notify_method_exit(true, ilgl, InterpreterMacroAssembler::NotifyJVMTI);
1517 
1518   if (synchronized) {
1519     // save and restore any potential method result value around the unlocking operation
1520     save_native_result();
1521 
1522     __ add( __ top_most_monitor(), O1);
1523     __ unlock_object(O1);
1524 
1525     restore_native_result();
1526   }
1527 
1528   // dispose of return address and remove activation
1529 #ifdef ASSERT
1530   { Label ok;
1531     __ cmp_and_brx_short(I5_savedSP, FP, Assembler::greaterEqualUnsigned, Assembler::pt, ok);
1532     __ stop("bad I5_savedSP value");
1533     __ should_not_reach_here();
1534     __ bind(ok);
1535   }
1536 #endif
1537   __ jmp(Lscratch, 0);
1538   __ delayed()->nop();
1539 
1540   if (inc_counter) {
1541     // handle invocation counter overflow
1542     __ bind(invocation_counter_overflow);
1543     generate_counter_overflow(Lcontinue);
1544   }
1545 
1546   return entry;
1547 }
1548 
1549 
1550 // Generic method entry to (asm) interpreter
1551 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1552   address entry = __ pc();
1553 
1554   bool inc_counter  = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1555 
1556   // the following temporary registers are used during frame creation
1557   const Register Gtmp1 = G3_scratch ;
1558   const Register Gtmp2 = G1_scratch;
1559 
1560   // make sure registers are different!
1561   assert_different_registers(G2_thread, G5_method, Gargs, Gtmp1, Gtmp2);
1562 
1563   const Address constMethod       (G5_method, Method::const_offset());
1564   // Seems like G5_method is live at the point this is used. So we could make this look consistent
1565   // and use in the asserts.
1566   const Address access_flags      (Lmethod,   Method::access_flags_offset());
1567 
1568   const Register Glocals_size = G3;
1569   assert_different_registers(Glocals_size, G4_scratch, Gframe_size);
1570 
1571   // make sure method is not native & not abstract
1572   // rethink these assertions - they can be simplified and shared (gri 2/25/2000)
1573 #ifdef ASSERT
1574   __ ld(G5_method, Method::access_flags_offset(), Gtmp1);
1575   { Label L;
1576     __ btst(JVM_ACC_NATIVE, Gtmp1);
1577     __ br(Assembler::zero, false, Assembler::pt, L);
1578     __ delayed()->nop();
1579     __ stop("tried to execute native method as non-native");
1580     __ bind(L);
1581   }
1582   { Label L;
1583     __ btst(JVM_ACC_ABSTRACT, Gtmp1);
1584     __ br(Assembler::zero, false, Assembler::pt, L);
1585     __ delayed()->nop();
1586     __ stop("tried to execute abstract method as non-abstract");
1587     __ bind(L);
1588   }
1589 #endif // ASSERT
1590 
1591   // generate the code to allocate the interpreter stack frame
1592 
1593   generate_fixed_frame(false);
1594 
1595   //
1596   // Code to initialize the extra (i.e. non-parm) locals
1597   //
1598   Register init_value = noreg;    // will be G0 if we must clear locals
1599   // The way the code was setup before zerolocals was always true for vanilla java entries.
1600   // It could only be false for the specialized entries like accessor or empty which have
1601   // no extra locals so the testing was a waste of time and the extra locals were always
1602   // initialized. We removed this extra complication to already over complicated code.
1603 
1604   init_value = G0;
1605   Label clear_loop;
1606 
1607   const Register RconstMethod = O1;
1608   const Address size_of_parameters(RconstMethod, ConstMethod::size_of_parameters_offset());
1609   const Address size_of_locals    (RconstMethod, ConstMethod::size_of_locals_offset());
1610 
1611   // NOTE: If you change the frame layout, this code will need to
1612   // be updated!
1613   __ ld_ptr( constMethod, RconstMethod );
1614   __ lduh( size_of_locals, O2 );
1615   __ lduh( size_of_parameters, O1 );
1616   __ sll( O2, Interpreter::logStackElementSize, O2);
1617   __ sll( O1, Interpreter::logStackElementSize, O1 );
1618   __ sub( Llocals, O2, O2 );
1619   __ sub( Llocals, O1, O1 );
1620 
1621   __ bind( clear_loop );
1622   __ inc( O2, wordSize );
1623 
1624   __ cmp( O2, O1 );
1625   __ brx( Assembler::lessEqualUnsigned, true, Assembler::pt, clear_loop );
1626   __ delayed()->st_ptr( init_value, O2, 0 );
1627 
1628   const Address do_not_unlock_if_synchronized(G2_thread,
1629     JavaThread::do_not_unlock_if_synchronized_offset());
1630   // Since at this point in the method invocation the exception handler
1631   // would try to exit the monitor of synchronized methods which hasn't
1632   // been entered yet, we set the thread local variable
1633   // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1634   // runtime, exception handling i.e. unlock_if_synchronized_method will
1635   // check this thread local flag.
1636   __ movbool(true, G3_scratch);
1637   __ stbool(G3_scratch, do_not_unlock_if_synchronized);
1638 
1639   __ profile_parameters_type(G1_scratch, G3_scratch, G4_scratch, Lscratch);
1640   // increment invocation counter and check for overflow
1641   //
1642   // Note: checking for negative value instead of overflow
1643   //       so we have a 'sticky' overflow test (may be of
1644   //       importance as soon as we have true MT/MP)
1645   Label invocation_counter_overflow;
1646   Label profile_method;
1647   Label profile_method_continue;
1648   Label Lcontinue;
1649   if (inc_counter) {
1650     generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
1651     if (ProfileInterpreter) {
1652       __ bind(profile_method_continue);
1653     }
1654   }
1655   __ bind(Lcontinue);
1656 
1657   bang_stack_shadow_pages(false);
1658 
1659   // reset the _do_not_unlock_if_synchronized flag
1660   __ stbool(G0, do_not_unlock_if_synchronized);
1661 
1662   // check for synchronized methods
1663   // Must happen AFTER invocation_counter check and stack overflow check,
1664   // so method is not locked if overflows.
1665 
1666   if (synchronized) {
1667     lock_method();
1668   } else {
1669 #ifdef ASSERT
1670     { Label ok;
1671       __ ld(access_flags, O0);
1672       __ btst(JVM_ACC_SYNCHRONIZED, O0);
1673       __ br( Assembler::zero, false, Assembler::pt, ok);
1674       __ delayed()->nop();
1675       __ stop("method needs synchronization");
1676       __ bind(ok);
1677     }
1678 #endif // ASSERT
1679   }
1680 
1681   // start execution
1682 
1683   __ verify_thread();
1684 
1685   // jvmti support
1686   __ notify_method_entry();
1687 
1688   // start executing instructions
1689   __ dispatch_next(vtos);
1690 
1691 
1692   if (inc_counter) {
1693     if (ProfileInterpreter) {
1694       // We have decided to profile this method in the interpreter
1695       __ bind(profile_method);
1696 
1697       __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1698       __ set_method_data_pointer_for_bcp();
1699       __ ba_short(profile_method_continue);
1700     }
1701 
1702     // handle invocation counter overflow
1703     __ bind(invocation_counter_overflow);
1704     generate_counter_overflow(Lcontinue);
1705   }
1706 
1707   return entry;
1708 }
1709 
1710 //----------------------------------------------------------------------------------------------------
1711 // Exceptions
1712 void TemplateInterpreterGenerator::generate_throw_exception() {
1713 
1714   // Entry point in previous activation (i.e., if the caller was interpreted)
1715   Interpreter::_rethrow_exception_entry = __ pc();
1716   // O0: exception
1717 
1718   // entry point for exceptions thrown within interpreter code
1719   Interpreter::_throw_exception_entry = __ pc();
1720   __ verify_thread();
1721   // expression stack is undefined here
1722   // O0: exception, i.e. Oexception
1723   // Lbcp: exception bcp
1724   __ verify_oop(Oexception);
1725 
1726 
1727   // expression stack must be empty before entering the VM in case of an exception
1728   __ empty_expression_stack();
1729   // find exception handler address and preserve exception oop
1730   // call C routine to find handler and jump to it
1731   __ call_VM(O1, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Oexception);
1732   __ push_ptr(O1); // push exception for exception handler bytecodes
1733 
1734   __ JMP(O0, 0); // jump to exception handler (may be remove activation entry!)
1735   __ delayed()->nop();
1736 
1737 
1738   // if the exception is not handled in the current frame
1739   // the frame is removed and the exception is rethrown
1740   // (i.e. exception continuation is _rethrow_exception)
1741   //
1742   // Note: At this point the bci is still the bxi for the instruction which caused
1743   //       the exception and the expression stack is empty. Thus, for any VM calls
1744   //       at this point, GC will find a legal oop map (with empty expression stack).
1745 
1746   // in current activation
1747   // tos: exception
1748   // Lbcp: exception bcp
1749 
1750   //
1751   // JVMTI PopFrame support
1752   //
1753 
1754   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1755   Address popframe_condition_addr(G2_thread, JavaThread::popframe_condition_offset());
1756   // Set the popframe_processing bit in popframe_condition indicating that we are
1757   // currently handling popframe, so that call_VMs that may happen later do not trigger new
1758   // popframe handling cycles.
1759 
1760   __ ld(popframe_condition_addr, G3_scratch);
1761   __ or3(G3_scratch, JavaThread::popframe_processing_bit, G3_scratch);
1762   __ stw(G3_scratch, popframe_condition_addr);
1763 
1764   // Empty the expression stack, as in normal exception handling
1765   __ empty_expression_stack();
1766   __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
1767 
1768   {
1769     // Check to see whether we are returning to a deoptimized frame.
1770     // (The PopFrame call ensures that the caller of the popped frame is
1771     // either interpreted or compiled and deoptimizes it if compiled.)
1772     // In this case, we can't call dispatch_next() after the frame is
1773     // popped, but instead must save the incoming arguments and restore
1774     // them after deoptimization has occurred.
1775     //
1776     // Note that we don't compare the return PC against the
1777     // deoptimization blob's unpack entry because of the presence of
1778     // adapter frames in C2.
1779     Label caller_not_deoptimized;
1780     __ call_VM_leaf(L7_thread_cache, CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), I7);
1781     __ br_notnull_short(O0, Assembler::pt, caller_not_deoptimized);
1782 
1783     const Register Gtmp1 = G3_scratch;
1784     const Register Gtmp2 = G1_scratch;
1785     const Register RconstMethod = Gtmp1;
1786     const Address constMethod(Lmethod, Method::const_offset());
1787     const Address size_of_parameters(RconstMethod, ConstMethod::size_of_parameters_offset());
1788 
1789     // Compute size of arguments for saving when returning to deoptimized caller
1790     __ ld_ptr(constMethod, RconstMethod);
1791     __ lduh(size_of_parameters, Gtmp1);
1792     __ sll(Gtmp1, Interpreter::logStackElementSize, Gtmp1);
1793     __ sub(Llocals, Gtmp1, Gtmp2);
1794     __ add(Gtmp2, wordSize, Gtmp2);
1795     // Save these arguments
1796     __ call_VM_leaf(L7_thread_cache, CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), G2_thread, Gtmp1, Gtmp2);
1797     // Inform deoptimization that it is responsible for restoring these arguments
1798     __ set(JavaThread::popframe_force_deopt_reexecution_bit, Gtmp1);
1799     Address popframe_condition_addr(G2_thread, JavaThread::popframe_condition_offset());
1800     __ st(Gtmp1, popframe_condition_addr);
1801 
1802     // Return from the current method
1803     // The caller's SP was adjusted upon method entry to accomodate
1804     // the callee's non-argument locals. Undo that adjustment.
1805     __ ret();
1806     __ delayed()->restore(I5_savedSP, G0, SP);
1807 
1808     __ bind(caller_not_deoptimized);
1809   }
1810 
1811   // Clear the popframe condition flag
1812   __ stw(G0 /* popframe_inactive */, popframe_condition_addr);
1813 
1814   // Get out of the current method (how this is done depends on the particular compiler calling
1815   // convention that the interpreter currently follows)
1816   // The caller's SP was adjusted upon method entry to accomodate
1817   // the callee's non-argument locals. Undo that adjustment.
1818   __ restore(I5_savedSP, G0, SP);
1819   // The method data pointer was incremented already during
1820   // call profiling. We have to restore the mdp for the current bcp.
1821   if (ProfileInterpreter) {
1822     __ set_method_data_pointer_for_bcp();
1823   }
1824 
1825 #if INCLUDE_JVMTI
1826   { Label L_done;
1827 
1828     __ ldub(Address(Lbcp, 0), G1_scratch);  // Load current bytecode
1829     __ cmp_and_br_short(G1_scratch, Bytecodes::_invokestatic, Assembler::notEqual, Assembler::pn, L_done);
1830 
1831     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1832     // Detect such a case in the InterpreterRuntime function and return the member name argument, or NULL.
1833 
1834     __ call_VM(G1_scratch, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), I0, Lmethod, Lbcp);
1835 
1836     __ br_null(G1_scratch, false, Assembler::pn, L_done);
1837     __ delayed()->nop();
1838 
1839     __ st_ptr(G1_scratch, Lesp, wordSize);
1840     __ bind(L_done);
1841   }
1842 #endif // INCLUDE_JVMTI
1843 
1844   // Resume bytecode interpretation at the current bcp
1845   __ dispatch_next(vtos);
1846   // end of JVMTI PopFrame support
1847 
1848   Interpreter::_remove_activation_entry = __ pc();
1849 
1850   // preserve exception over this code sequence (remove activation calls the vm, but oopmaps are not correct here)
1851   __ pop_ptr(Oexception);                                  // get exception
1852 
1853   // Intel has the following comment:
1854   //// remove the activation (without doing throws on illegalMonitorExceptions)
1855   // They remove the activation without checking for bad monitor state.
1856   // %%% We should make sure this is the right semantics before implementing.
1857 
1858   __ set_vm_result(Oexception);
1859   __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false);
1860 
1861   __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI);
1862 
1863   __ get_vm_result(Oexception);
1864   __ verify_oop(Oexception);
1865 
1866   const int return_reg_adjustment = frame::pc_return_offset;
1867   Address issuing_pc_addr(I7, return_reg_adjustment);
1868 
1869   // We are done with this activation frame; find out where to go next.
1870   // The continuation point will be an exception handler, which expects
1871   // the following registers set up:
1872   //
1873   // Oexception: exception
1874   // Oissuing_pc: the local call that threw exception
1875   // Other On: garbage
1876   // In/Ln:  the contents of the caller's register window
1877   //
1878   // We do the required restore at the last possible moment, because we
1879   // need to preserve some state across a runtime call.
1880   // (Remember that the caller activation is unknown--it might not be
1881   // interpreted, so things like Lscratch are useless in the caller.)
1882 
1883   // Although the Intel version uses call_C, we can use the more
1884   // compact call_VM.  (The only real difference on SPARC is a
1885   // harmlessly ignored [re]set_last_Java_frame, compared with
1886   // the Intel code which lacks this.)
1887   __ mov(Oexception,      Oexception ->after_save());  // get exception in I0 so it will be on O0 after restore
1888   __ add(issuing_pc_addr, Oissuing_pc->after_save());  // likewise set I1 to a value local to the caller
1889   __ super_call_VM_leaf(L7_thread_cache,
1890                         CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1891                         G2_thread, Oissuing_pc->after_save());
1892 
1893   // The caller's SP was adjusted upon method entry to accomodate
1894   // the callee's non-argument locals. Undo that adjustment.
1895   __ JMP(O0, 0);                         // return exception handler in caller
1896   __ delayed()->restore(I5_savedSP, G0, SP);
1897 
1898   // (same old exception object is already in Oexception; see above)
1899   // Note that an "issuing PC" is actually the next PC after the call
1900 }
1901 
1902 
1903 //
1904 // JVMTI ForceEarlyReturn support
1905 //
1906 
1907 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1908   address entry = __ pc();
1909 
1910   __ empty_expression_stack();
1911   __ load_earlyret_value(state);
1912 
1913   __ ld_ptr(G2_thread, JavaThread::jvmti_thread_state_offset(), G3_scratch);
1914   Address cond_addr(G3_scratch, JvmtiThreadState::earlyret_state_offset());
1915 
1916   // Clear the earlyret state
1917   __ stw(G0 /* JvmtiThreadState::earlyret_inactive */, cond_addr);
1918 
1919   __ remove_activation(state,
1920                        /* throw_monitor_exception */ false,
1921                        /* install_monitor_exception */ false);
1922 
1923   // The caller's SP was adjusted upon method entry to accomodate
1924   // the callee's non-argument locals. Undo that adjustment.
1925   __ ret();                             // return to caller
1926   __ delayed()->restore(I5_savedSP, G0, SP);
1927 
1928   return entry;
1929 } // end of JVMTI ForceEarlyReturn support
1930 
1931 
1932 //------------------------------------------------------------------------------------------------------------------------
1933 // Helper for vtos entry point generation
1934 
1935 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t, address& bep, address& cep, address& sep, address& aep, address& iep, address& lep, address& fep, address& dep, address& vep) {
1936   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1937   Label L;
1938   aep = __ pc(); __ push_ptr(); __ ba_short(L);
1939   fep = __ pc(); __ push_f();   __ ba_short(L);
1940   dep = __ pc(); __ push_d();   __ ba_short(L);
1941   lep = __ pc(); __ push_l();   __ ba_short(L);
1942   iep = __ pc(); __ push_i();
1943   bep = cep = sep = iep;                        // there aren't any
1944   vep = __ pc(); __ bind(L);                    // fall through
1945   generate_and_dispatch(t);
1946 }
1947 
1948 // --------------------------------------------------------------------------------
1949 
1950 // Non-product code
1951 #ifndef PRODUCT
1952 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1953   address entry = __ pc();
1954 
1955   __ push(state);
1956   __ mov(O7, Lscratch); // protect return address within interpreter
1957 
1958   // Pass a 0 (not used in sparc) and the top of stack to the bytecode tracer
1959   __ mov( Otos_l2, G3_scratch );
1960   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode), G0, Otos_l1, G3_scratch);
1961   __ mov(Lscratch, O7); // restore return address
1962   __ pop(state);
1963   __ retl();
1964   __ delayed()->nop();
1965 
1966   return entry;
1967 }
1968 
1969 
1970 // helpers for generate_and_dispatch
1971 
1972 void TemplateInterpreterGenerator::count_bytecode() {
1973   __ inc_counter(&BytecodeCounter::_counter_value, G3_scratch, G4_scratch);
1974 }
1975 
1976 
1977 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1978   __ inc_counter(&BytecodeHistogram::_counters[t->bytecode()], G3_scratch, G4_scratch);
1979 }
1980 
1981 
1982 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1983   AddressLiteral index   (&BytecodePairHistogram::_index);
1984   AddressLiteral counters((address) &BytecodePairHistogram::_counters);
1985 
1986   // get index, shift out old bytecode, bring in new bytecode, and store it
1987   // _index = (_index >> log2_number_of_codes) |
1988   //          (bytecode << log2_number_of_codes);
1989 
1990   __ load_contents(index, G4_scratch);
1991   __ srl( G4_scratch, BytecodePairHistogram::log2_number_of_codes, G4_scratch );
1992   __ set( ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes,  G3_scratch );
1993   __ or3( G3_scratch,  G4_scratch, G4_scratch );
1994   __ store_contents(G4_scratch, index, G3_scratch);
1995 
1996   // bump bucket contents
1997   // _counters[_index] ++;
1998 
1999   __ set(counters, G3_scratch);                       // loads into G3_scratch
2000   __ sll( G4_scratch, LogBytesPerWord, G4_scratch );  // Index is word address
2001   __ add (G3_scratch, G4_scratch, G3_scratch);        // Add in index
2002   __ ld (G3_scratch, 0, G4_scratch);
2003   __ inc (G4_scratch);
2004   __ st (G4_scratch, 0, G3_scratch);
2005 }
2006 
2007 
2008 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2009   // Call a little run-time stub to avoid blow-up for each bytecode.
2010   // The run-time runtime saves the right registers, depending on
2011   // the tosca in-state for the given template.
2012   address entry = Interpreter::trace_code(t->tos_in());
2013   guarantee(entry != NULL, "entry must have been generated");
2014   __ call(entry, relocInfo::none);
2015   __ delayed()->nop();
2016 }
2017 
2018 
2019 void TemplateInterpreterGenerator::stop_interpreter_at() {
2020   AddressLiteral counter(&BytecodeCounter::_counter_value);
2021   __ load_contents(counter, G3_scratch);
2022   AddressLiteral stop_at(&StopInterpreterAt);
2023   __ load_ptr_contents(stop_at, G4_scratch);
2024   __ cmp(G3_scratch, G4_scratch);
2025   __ breakpoint_trap(Assembler::equal, Assembler::icc);
2026 }
2027 #endif // not PRODUCT