1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2013, 2014 SAP AG. 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 #ifndef CC_INTERP
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "interpreter/bytecodeHistogram.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "interpreter/interpreterGenerator.hpp"
  32 #include "interpreter/interpreterRuntime.hpp"
  33 #include "interpreter/templateTable.hpp"
  34 #include "oops/arrayOop.hpp"
  35 #include "oops/methodData.hpp"
  36 #include "oops/method.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "prims/jvmtiThreadState.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/deoptimization.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/stubRoutines.hpp"
  45 #include "runtime/synchronizer.hpp"
  46 #include "runtime/timer.hpp"
  47 #include "runtime/vframeArray.hpp"
  48 #include "utilities/debug.hpp"
  49 #include "utilities/macros.hpp"
  50 
  51 #undef __
  52 #define __ _masm->
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #else
  57 #define BLOCK_COMMENT(str) __ block_comment(str)
  58 #endif
  59 
  60 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  61 
  62 //-----------------------------------------------------------------------------
  63 
  64 // Actually we should never reach here since we do stack overflow checks before pushing any frame.
  65 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
  66   address entry = __ pc();
  67   __ unimplemented("generate_StackOverflowError_handler");
  68   return entry;
  69 }
  70 
  71 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char* name) {
  72   address entry = __ pc();
  73   __ empty_expression_stack();
  74   __ load_const_optimized(R4_ARG2, (address) name);
  75   // Index is in R17_tos.
  76   __ mr(R5_ARG3, R17_tos);
  77   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException));
  78   return entry;
  79 }
  80 
  81 #if 0
  82 // Call special ClassCastException constructor taking object to cast
  83 // and target class as arguments.
  84 address TemplateInterpreterGenerator::generate_ClassCastException_verbose_handler() {
  85   address entry = __ pc();
  86 
  87   // Expression stack must be empty before entering the VM if an
  88   // exception happened.
  89   __ empty_expression_stack();
  90 
  91   // Thread will be loaded to R3_ARG1.
  92   // Target class oop is in register R5_ARG3 by convention!
  93   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException_verbose, R17_tos, R5_ARG3));
  94   // Above call must not return here since exception pending.
  95   DEBUG_ONLY(__ should_not_reach_here();)
  96   return entry;
  97 }
  98 #endif
  99 
 100 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 101   address entry = __ pc();
 102   // Expression stack must be empty before entering the VM if an
 103   // exception happened.
 104   __ empty_expression_stack();
 105 
 106   // Load exception object.
 107   // Thread will be loaded to R3_ARG1.
 108   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException), R17_tos);
 109 #ifdef ASSERT
 110   // Above call must not return here since exception pending.
 111   __ should_not_reach_here();
 112 #endif
 113   return entry;
 114 }
 115 
 116 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 117   address entry = __ pc();
 118   //__ untested("generate_exception_handler_common");
 119   Register Rexception = R17_tos;
 120 
 121   // Expression stack must be empty before entering the VM if an exception happened.
 122   __ empty_expression_stack();
 123 
 124   __ load_const_optimized(R4_ARG2, (address) name, R11_scratch1);
 125   if (pass_oop) {
 126     __ mr(R5_ARG3, Rexception);
 127     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception), false);
 128   } else {
 129     __ load_const_optimized(R5_ARG3, (address) message, R11_scratch1);
 130     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception), false);
 131   }
 132 
 133   // Throw exception.
 134   __ mr(R3_ARG1, Rexception);
 135   __ load_const_optimized(R11_scratch1, Interpreter::throw_exception_entry(), R12_scratch2);
 136   __ mtctr(R11_scratch1);
 137   __ bctr();
 138 
 139   return entry;
 140 }
 141 
 142 address TemplateInterpreterGenerator::generate_continuation_for(TosState state) {
 143   address entry = __ pc();
 144   __ unimplemented("generate_continuation_for");
 145   return entry;
 146 }
 147 
 148 // This entry is returned to when a call returns to the interpreter.
 149 // When we arrive here, we expect that the callee stack frame is already popped.
 150 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 151   address entry = __ pc();
 152 
 153   // Move the value out of the return register back to the TOS cache of current frame.
 154   switch (state) {
 155     case ltos:
 156     case btos:
 157     case ctos:
 158     case stos:
 159     case atos:
 160     case itos: __ mr(R17_tos, R3_RET); break;   // RET -> TOS cache
 161     case ftos:
 162     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 163     case vtos: break;                           // Nothing to do, this was a void return.
 164     default  : ShouldNotReachHere();
 165   }
 166 
 167   __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
 168   __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
 169   __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
 170 
 171   // Compiled code destroys templateTableBase, reload.
 172   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
 173 
 174   const Register cache = R11_scratch1;
 175   const Register size  = R12_scratch2;
 176   __ get_cache_and_index_at_bcp(cache, 1, index_size);
 177 
 178   // Get least significant byte of 64 bit value:
 179 #if defined(VM_LITTLE_ENDIAN)
 180   __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()), cache);
 181 #else
 182   __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()) + 7, cache);
 183 #endif
 184   __ sldi(size, size, Interpreter::logStackElementSize);
 185   __ add(R15_esp, R15_esp, size);
 186   __ dispatch_next(state, step);
 187   return entry;
 188 }
 189 
 190 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step) {
 191   address entry = __ pc();
 192   // If state != vtos, we're returning from a native method, which put it's result
 193   // into the result register. So move the value out of the return register back
 194   // to the TOS cache of current frame.
 195 
 196   switch (state) {
 197     case ltos:
 198     case btos:
 199     case ctos:
 200     case stos:
 201     case atos:
 202     case itos: __ mr(R17_tos, R3_RET); break;   // GR_RET -> TOS cache
 203     case ftos:
 204     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 205     case vtos: break;                           // Nothing to do, this was a void return.
 206     default  : ShouldNotReachHere();
 207   }
 208 
 209   // Load LcpoolCache @@@ should be already set!
 210   __ get_constant_pool_cache(R27_constPoolCache);
 211 
 212   // Handle a pending exception, fall through if none.
 213   __ check_and_forward_exception(R11_scratch1, R12_scratch2);
 214 
 215   // Start executing bytecodes.
 216   __ dispatch_next(state, step);
 217 
 218   return entry;
 219 }
 220 
 221 // A result handler converts the native result into java format.
 222 // Use the shared code between c++ and template interpreter.
 223 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 224   return AbstractInterpreterGenerator::generate_result_handler_for(type);
 225 }
 226 
 227 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 228   address entry = __ pc();
 229 
 230   __ push(state);
 231   __ call_VM(noreg, runtime_entry);
 232   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 233 
 234   return entry;
 235 }
 236 
 237 // Helpers for commoning out cases in the various type of method entries.
 238 
 239 // Increment invocation count & check for overflow.
 240 //
 241 // Note: checking for negative value instead of overflow
 242 //       so we have a 'sticky' overflow test.
 243 //
 244 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
 245   // Note: In tiered we increment either counters in method or in MDO depending if we're profiling or not.
 246   Register Rscratch1   = R11_scratch1;
 247   Register Rscratch2   = R12_scratch2;
 248   Register R3_counters = R3_ARG1;
 249   Label done;
 250 
 251   if (TieredCompilation) {
 252     const int increment = InvocationCounter::count_increment;
 253     const int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift;
 254     Label no_mdo;
 255     if (ProfileInterpreter) {
 256       const Register Rmdo = Rscratch1;
 257       // If no method data exists, go to profile_continue.
 258       __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
 259       __ cmpdi(CCR0, Rmdo, 0);
 260       __ beq(CCR0, no_mdo);
 261 
 262       // Increment backedge counter in the MDO.
 263       const int mdo_bc_offs = in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 264       __ lwz(Rscratch2, mdo_bc_offs, Rmdo);
 265       __ addi(Rscratch2, Rscratch2, increment);
 266       __ stw(Rscratch2, mdo_bc_offs, Rmdo);
 267       __ load_const_optimized(Rscratch1, mask, R0);
 268       __ and_(Rscratch1, Rscratch2, Rscratch1);
 269       __ bne(CCR0, done);
 270       __ b(*overflow);
 271     }
 272 
 273     // Increment counter in MethodCounters*.
 274     const int mo_bc_offs = in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 275     __ bind(no_mdo);
 276     __ get_method_counters(R19_method, R3_counters, done);
 277     __ lwz(Rscratch2, mo_bc_offs, R3_counters);
 278     __ addi(Rscratch2, Rscratch2, increment);
 279     __ stw(Rscratch2, mo_bc_offs, R3_counters);
 280     __ load_const_optimized(Rscratch1, mask, R0);
 281     __ and_(Rscratch1, Rscratch2, Rscratch1);
 282     __ beq(CCR0, *overflow);
 283 
 284     __ bind(done);
 285 
 286   } else {
 287 
 288     // Update standard invocation counters.
 289     Register Rsum_ivc_bec = R4_ARG2;
 290     __ get_method_counters(R19_method, R3_counters, done);
 291     __ increment_invocation_counter(R3_counters, Rsum_ivc_bec, R12_scratch2);
 292     // Increment interpreter invocation counter.
 293     if (ProfileInterpreter) {  // %%% Merge this into methodDataOop.
 294       __ lwz(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
 295       __ addi(R12_scratch2, R12_scratch2, 1);
 296       __ stw(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
 297     }
 298     // Check if we must create a method data obj.
 299     if (ProfileInterpreter && profile_method != NULL) {
 300       const Register profile_limit = Rscratch1;
 301       int pl_offs = __ load_const_optimized(profile_limit, &InvocationCounter::InterpreterProfileLimit, R0, true);
 302       __ lwz(profile_limit, pl_offs, profile_limit);
 303       // Test to see if we should create a method data oop.
 304       __ cmpw(CCR0, Rsum_ivc_bec, profile_limit);
 305       __ blt(CCR0, *profile_method_continue);
 306       // If no method data exists, go to profile_method.
 307       __ test_method_data_pointer(*profile_method);
 308     }
 309     // Finally check for counter overflow.
 310     if (overflow) {
 311       const Register invocation_limit = Rscratch1;
 312       int il_offs = __ load_const_optimized(invocation_limit, &InvocationCounter::InterpreterInvocationLimit, R0, true);
 313       __ lwz(invocation_limit, il_offs, invocation_limit);
 314       assert(4 == sizeof(InvocationCounter::InterpreterInvocationLimit), "unexpected field size");
 315       __ cmpw(CCR0, Rsum_ivc_bec, invocation_limit);
 316       __ bge(CCR0, *overflow);
 317     }
 318 
 319     __ bind(done);
 320   }
 321 }
 322 
 323 // Generate code to initiate compilation on invocation counter overflow.
 324 void TemplateInterpreterGenerator::generate_counter_overflow(Label& continue_entry) {
 325   // Generate code to initiate compilation on the counter overflow.
 326 
 327   // InterpreterRuntime::frequency_counter_overflow takes one arguments,
 328   // which indicates if the counter overflow occurs at a backwards branch (NULL bcp)
 329   // We pass zero in.
 330   // The call returns the address of the verified entry point for the method or NULL
 331   // if the compilation did not complete (either went background or bailed out).
 332   //
 333   // Unlike the C++ interpreter above: Check exceptions!
 334   // Assumption: Caller must set the flag "do_not_unlock_if_sychronized" if the monitor of a sync'ed
 335   // method has not yet been created. Thus, no unlocking of a non-existing monitor can occur.
 336 
 337   __ li(R4_ARG2, 0);
 338   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
 339 
 340   // Returns verified_entry_point or NULL.
 341   // We ignore it in any case.
 342   __ b(continue_entry);
 343 }
 344 
 345 void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rmem_frame_size, Register Rscratch1) {
 346   assert_different_registers(Rmem_frame_size, Rscratch1);
 347   __ generate_stack_overflow_check_with_compare_and_throw(Rmem_frame_size, Rscratch1);
 348 }
 349 
 350 void TemplateInterpreterGenerator::unlock_method(bool check_exceptions) {
 351   __ unlock_object(R26_monitor, check_exceptions);
 352 }
 353 
 354 // Lock the current method, interpreter register window must be set up!
 355 void TemplateInterpreterGenerator::lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded) {
 356   const Register Robj_to_lock = Rscratch2;
 357 
 358   {
 359     if (!flags_preloaded) {
 360       __ lwz(Rflags, method_(access_flags));
 361     }
 362 
 363 #ifdef ASSERT
 364     // Check if methods needs synchronization.
 365     {
 366       Label Lok;
 367       __ testbitdi(CCR0, R0, Rflags, JVM_ACC_SYNCHRONIZED_BIT);
 368       __ btrue(CCR0,Lok);
 369       __ stop("method doesn't need synchronization");
 370       __ bind(Lok);
 371     }
 372 #endif // ASSERT
 373   }
 374 
 375   // Get synchronization object to Rscratch2.
 376   {
 377     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 378     Label Lstatic;
 379     Label Ldone;
 380 
 381     __ testbitdi(CCR0, R0, Rflags, JVM_ACC_STATIC_BIT);
 382     __ btrue(CCR0, Lstatic);
 383 
 384     // Non-static case: load receiver obj from stack and we're done.
 385     __ ld(Robj_to_lock, R18_locals);
 386     __ b(Ldone);
 387 
 388     __ bind(Lstatic); // Static case: Lock the java mirror
 389     __ ld(Robj_to_lock, in_bytes(Method::const_offset()), R19_method);
 390     __ ld(Robj_to_lock, in_bytes(ConstMethod::constants_offset()), Robj_to_lock);
 391     __ ld(Robj_to_lock, ConstantPool::pool_holder_offset_in_bytes(), Robj_to_lock);
 392     __ ld(Robj_to_lock, mirror_offset, Robj_to_lock);
 393 
 394     __ bind(Ldone);
 395     __ verify_oop(Robj_to_lock);
 396   }
 397 
 398   // Got the oop to lock => execute!
 399   __ add_monitor_to_stack(true, Rscratch1, R0);
 400 
 401   __ std(Robj_to_lock, BasicObjectLock::obj_offset_in_bytes(), R26_monitor);
 402   __ lock_object(R26_monitor, Robj_to_lock);
 403 }
 404 
 405 // Generate a fixed interpreter frame for pure interpreter
 406 // and I2N native transition frames.
 407 //
 408 // Before (stack grows downwards):
 409 //
 410 //         |  ...         |
 411 //         |------------- |
 412 //         |  java arg0   |
 413 //         |  ...         |
 414 //         |  java argn   |
 415 //         |              |   <-   R15_esp
 416 //         |              |
 417 //         |--------------|
 418 //         | abi_112      |
 419 //         |              |   <-   R1_SP
 420 //         |==============|
 421 //
 422 //
 423 // After:
 424 //
 425 //         |  ...         |
 426 //         |  java arg0   |<-   R18_locals
 427 //         |  ...         |
 428 //         |  java argn   |
 429 //         |--------------|
 430 //         |              |
 431 //         |  java locals |
 432 //         |              |
 433 //         |--------------|
 434 //         |  abi_48      |
 435 //         |==============|
 436 //         |              |
 437 //         |   istate     |
 438 //         |              |
 439 //         |--------------|
 440 //         |   monitor    |<-   R26_monitor
 441 //         |--------------|
 442 //         |              |<-   R15_esp
 443 //         | expression   |
 444 //         | stack        |
 445 //         |              |
 446 //         |--------------|
 447 //         |              |
 448 //         | abi_112      |<-   R1_SP
 449 //         |==============|
 450 //
 451 // The top most frame needs an abi space of 112 bytes. This space is needed,
 452 // since we call to c. The c function may spill their arguments to the caller
 453 // frame. When we call to java, we don't need these spill slots. In order to save
 454 // space on the stack, we resize the caller. However, java local reside in
 455 // the caller frame and the frame has to be increased. The frame_size for the
 456 // current frame was calculated based on max_stack as size for the expression
 457 // stack. At the call, just a part of the expression stack might be used.
 458 // We don't want to waste this space and cut the frame back accordingly.
 459 // The resulting amount for resizing is calculated as follows:
 460 // resize =   (number_of_locals - number_of_arguments) * slot_size
 461 //          + (R1_SP - R15_esp) + 48
 462 //
 463 // The size for the callee frame is calculated:
 464 // framesize = 112 + max_stack + monitor + state_size
 465 //
 466 // maxstack:   Max number of slots on the expression stack, loaded from the method.
 467 // monitor:    We statically reserve room for one monitor object.
 468 // state_size: We save the current state of the interpreter to this area.
 469 //
 470 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals) {
 471   Register parent_frame_resize = R6_ARG4, // Frame will grow by this number of bytes.
 472            top_frame_size      = R7_ARG5,
 473            Rconst_method       = R8_ARG6;
 474 
 475   assert_different_registers(Rsize_of_parameters, Rsize_of_locals, parent_frame_resize, top_frame_size);
 476 
 477   __ ld(Rconst_method, method_(const));
 478   __ lhz(Rsize_of_parameters /* number of params */,
 479          in_bytes(ConstMethod::size_of_parameters_offset()), Rconst_method);
 480   if (native_call) {
 481     // If we're calling a native method, we reserve space for the worst-case signature
 482     // handler varargs vector, which is max(Argument::n_register_parameters, parameter_count+2).
 483     // We add two slots to the parameter_count, one for the jni
 484     // environment and one for a possible native mirror.
 485     Label skip_native_calculate_max_stack;
 486     __ addi(top_frame_size, Rsize_of_parameters, 2);
 487     __ cmpwi(CCR0, top_frame_size, Argument::n_register_parameters);
 488     __ bge(CCR0, skip_native_calculate_max_stack);
 489     __ li(top_frame_size, Argument::n_register_parameters);
 490     __ bind(skip_native_calculate_max_stack);
 491     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 492     __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
 493     __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 494     assert(Rsize_of_locals == noreg, "Rsize_of_locals not initialized"); // Only relevant value is Rsize_of_parameters.
 495   } else {
 496     __ lhz(Rsize_of_locals /* number of params */, in_bytes(ConstMethod::size_of_locals_offset()), Rconst_method);
 497     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 498     __ sldi(Rsize_of_locals, Rsize_of_locals, Interpreter::logStackElementSize);
 499     __ lhz(top_frame_size, in_bytes(ConstMethod::max_stack_offset()), Rconst_method);
 500     __ sub(R11_scratch1, Rsize_of_locals, Rsize_of_parameters); // >=0
 501     __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 502     __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
 503     __ add(parent_frame_resize, parent_frame_resize, R11_scratch1);
 504   }
 505 
 506   // Compute top frame size.
 507   __ addi(top_frame_size, top_frame_size, frame::abi_reg_args_size + frame::ijava_state_size);
 508 
 509   // Cut back area between esp and max_stack.
 510   __ addi(parent_frame_resize, parent_frame_resize, frame::abi_minframe_size - Interpreter::stackElementSize);
 511 
 512   __ round_to(top_frame_size, frame::alignment_in_bytes);
 513   __ round_to(parent_frame_resize, frame::alignment_in_bytes);
 514   // parent_frame_resize = (locals-parameters) - (ESP-SP-ABI48) Rounded to frame alignment size.
 515   // Enlarge by locals-parameters (not in case of native_call), shrink by ESP-SP-ABI48.
 516 
 517   {
 518     // --------------------------------------------------------------------------
 519     // Stack overflow check
 520 
 521     Label cont;
 522     __ add(R11_scratch1, parent_frame_resize, top_frame_size);
 523     generate_stack_overflow_check(R11_scratch1, R12_scratch2);
 524   }
 525 
 526   // Set up interpreter state registers.
 527 
 528   __ add(R18_locals, R15_esp, Rsize_of_parameters);
 529   __ ld(R27_constPoolCache, in_bytes(ConstMethod::constants_offset()), Rconst_method);
 530   __ ld(R27_constPoolCache, ConstantPool::cache_offset_in_bytes(), R27_constPoolCache);
 531 
 532   // Set method data pointer.
 533   if (ProfileInterpreter) {
 534     Label zero_continue;
 535     __ ld(R28_mdx, method_(method_data));
 536     __ cmpdi(CCR0, R28_mdx, 0);
 537     __ beq(CCR0, zero_continue);
 538     __ addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
 539     __ bind(zero_continue);
 540   }
 541 
 542   if (native_call) {
 543     __ li(R14_bcp, 0); // Must initialize.
 544   } else {
 545     __ add(R14_bcp, in_bytes(ConstMethod::codes_offset()), Rconst_method);
 546   }
 547 
 548   // Resize parent frame.
 549   __ mflr(R12_scratch2);
 550   __ neg(parent_frame_resize, parent_frame_resize);
 551   __ resize_frame(parent_frame_resize, R11_scratch1);
 552   __ std(R12_scratch2, _abi(lr), R1_SP);
 553 
 554   __ addi(R26_monitor, R1_SP, - frame::ijava_state_size);
 555   __ addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
 556 
 557   // Store values.
 558   // R15_esp, R14_bcp, R26_monitor, R28_mdx are saved at java calls
 559   // in InterpreterMacroAssembler::call_from_interpreter.
 560   __ std(R19_method, _ijava_state_neg(method), R1_SP);
 561   __ std(R21_sender_SP, _ijava_state_neg(sender_sp), R1_SP);
 562   __ std(R27_constPoolCache, _ijava_state_neg(cpoolCache), R1_SP);
 563   __ std(R18_locals, _ijava_state_neg(locals), R1_SP);
 564 
 565   // Note: esp, bcp, monitor, mdx live in registers. Hence, the correct version can only
 566   // be found in the frame after save_interpreter_state is done. This is always true
 567   // for non-top frames. But when a signal occurs, dumping the top frame can go wrong,
 568   // because e.g. frame::interpreter_frame_bcp() will not access the correct value
 569   // (Enhanced Stack Trace).
 570   // The signal handler does not save the interpreter state into the frame.
 571   __ li(R0, 0);
 572 #ifdef ASSERT
 573   // Fill remaining slots with constants.
 574   __ load_const_optimized(R11_scratch1, 0x5afe);
 575   __ load_const_optimized(R12_scratch2, 0xdead);
 576 #endif
 577   // We have to initialize some frame slots for native calls (accessed by GC).
 578   if (native_call) {
 579     __ std(R26_monitor, _ijava_state_neg(monitors), R1_SP);
 580     __ std(R14_bcp, _ijava_state_neg(bcp), R1_SP);
 581     if (ProfileInterpreter) { __ std(R28_mdx, _ijava_state_neg(mdx), R1_SP); }
 582   }
 583 #ifdef ASSERT
 584   else {
 585     __ std(R12_scratch2, _ijava_state_neg(monitors), R1_SP);
 586     __ std(R12_scratch2, _ijava_state_neg(bcp), R1_SP);
 587     __ std(R12_scratch2, _ijava_state_neg(mdx), R1_SP);
 588   }
 589   __ std(R11_scratch1, _ijava_state_neg(ijava_reserved), R1_SP);
 590   __ std(R12_scratch2, _ijava_state_neg(esp), R1_SP);
 591   __ std(R12_scratch2, _ijava_state_neg(lresult), R1_SP);
 592   __ std(R12_scratch2, _ijava_state_neg(fresult), R1_SP);
 593 #endif
 594   __ subf(R12_scratch2, top_frame_size, R1_SP);
 595   __ std(R0, _ijava_state_neg(oop_tmp), R1_SP);
 596   __ std(R12_scratch2, _ijava_state_neg(top_frame_sp), R1_SP);
 597 
 598   // Push top frame.
 599   __ push_frame(top_frame_size, R11_scratch1);
 600 }
 601 
 602 // End of helpers
 603 
 604 // ============================================================================
 605 // Various method entries
 606 //
 607 
 608 // Empty method, generate a very fast return. We must skip this entry if
 609 // someone's debugging, indicated by the flag
 610 // "interp_mode" in the Thread obj.
 611 // Note: empty methods are generated mostly methods that do assertions, which are
 612 // disabled in the "java opt build".
 613 address TemplateInterpreterGenerator::generate_empty_entry(void) {
 614   if (!UseFastEmptyMethods) {
 615     NOT_PRODUCT(__ should_not_reach_here();)
 616     return Interpreter::entry_for_kind(Interpreter::zerolocals);
 617   }
 618 
 619   Label Lslow_path;
 620   const Register Rjvmti_mode = R11_scratch1;
 621   address entry = __ pc();
 622 
 623   __ lwz(Rjvmti_mode, thread_(interp_only_mode));
 624   __ cmpwi(CCR0, Rjvmti_mode, 0);
 625   __ bne(CCR0, Lslow_path); // jvmti_mode!=0
 626 
 627   // Noone's debuggin: Simply return.
 628   // Pop c2i arguments (if any) off when we return.
 629 #ifdef ASSERT
 630     __ ld(R9_ARG7, 0, R1_SP);
 631     __ ld(R10_ARG8, 0, R21_sender_SP);
 632     __ cmpd(CCR0, R9_ARG7, R10_ARG8);
 633     __ asm_assert_eq("backlink", 0x545);
 634 #endif // ASSERT
 635   __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
 636 
 637   // And we're done.
 638   __ blr();
 639 
 640   __ bind(Lslow_path);
 641   __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
 642   __ flush();
 643 
 644   return entry;
 645 }
 646 
 647 // Support abs and sqrt like in compiler.
 648 // For others we can use a normal (native) entry.
 649 
 650 inline bool math_entry_available(AbstractInterpreter::MethodKind kind) {
 651   // Provide math entry with debugging on demand.
 652   // Note: Debugging changes which code will get executed:
 653   // Debugging or disabled InlineIntrinsics: java method will get interpreted and performs a native call.
 654   // Not debugging and enabled InlineIntrinics: processor instruction will get used.
 655   // Result might differ slightly due to rounding etc.
 656   if (!InlineIntrinsics && (!FLAG_IS_ERGO(InlineIntrinsics))) return false; // Generate a vanilla entry.
 657 
 658   return ((kind==Interpreter::java_lang_math_sqrt && VM_Version::has_fsqrt()) ||
 659           (kind==Interpreter::java_lang_math_abs));
 660 }
 661 
 662 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
 663   if (!math_entry_available(kind)) {
 664     NOT_PRODUCT(__ should_not_reach_here();)
 665     return Interpreter::entry_for_kind(Interpreter::zerolocals);
 666   }
 667 
 668   Label Lslow_path;
 669   const Register Rjvmti_mode = R11_scratch1;
 670   address entry = __ pc();
 671 
 672   // Provide math entry with debugging on demand.
 673   __ lwz(Rjvmti_mode, thread_(interp_only_mode));
 674   __ cmpwi(CCR0, Rjvmti_mode, 0);
 675   __ bne(CCR0, Lslow_path); // jvmti_mode!=0
 676 
 677   __ lfd(F1_RET, Interpreter::stackElementSize, R15_esp);
 678 
 679   // Pop c2i arguments (if any) off when we return.
 680 #ifdef ASSERT
 681   __ ld(R9_ARG7, 0, R1_SP);
 682   __ ld(R10_ARG8, 0, R21_sender_SP);
 683   __ cmpd(CCR0, R9_ARG7, R10_ARG8);
 684   __ asm_assert_eq("backlink", 0x545);
 685 #endif // ASSERT
 686   __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
 687 
 688   if (kind == Interpreter::java_lang_math_sqrt) {
 689     __ fsqrt(F1_RET, F1_RET);
 690   } else if (kind == Interpreter::java_lang_math_abs) {
 691     __ fabs(F1_RET, F1_RET);
 692   } else {
 693     ShouldNotReachHere();
 694   }
 695 
 696   // And we're done.
 697   __ blr();
 698 
 699   // Provide slow path for JVMTI case.
 700   __ bind(Lslow_path);
 701   __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R12_scratch2);
 702   __ flush();
 703 
 704   return entry;
 705 }
 706 
 707 // Interpreter stub for calling a native method. (asm interpreter)
 708 // This sets up a somewhat different looking stack for calling the
 709 // native method than the typical interpreter frame setup.
 710 //
 711 // On entry:
 712 //   R19_method    - method
 713 //   R16_thread    - JavaThread*
 714 //   R15_esp       - intptr_t* sender tos
 715 //
 716 //   abstract stack (grows up)
 717 //     [  IJava (caller of JNI callee)  ]  <-- ASP
 718 //        ...
 719 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
 720 
 721   address entry = __ pc();
 722 
 723   const bool inc_counter = UseCompiler || CountCompiledCalls;
 724 
 725   // -----------------------------------------------------------------------------
 726   // Allocate a new frame that represents the native callee (i2n frame).
 727   // This is not a full-blown interpreter frame, but in particular, the
 728   // following registers are valid after this:
 729   // - R19_method
 730   // - R18_local (points to start of argumuments to native function)
 731   //
 732   //   abstract stack (grows up)
 733   //     [  IJava (caller of JNI callee)  ]  <-- ASP
 734   //        ...
 735 
 736   const Register signature_handler_fd = R11_scratch1;
 737   const Register pending_exception    = R0;
 738   const Register result_handler_addr  = R31;
 739   const Register native_method_fd     = R11_scratch1;
 740   const Register access_flags         = R22_tmp2;
 741   const Register active_handles       = R11_scratch1; // R26_monitor saved to state.
 742   const Register sync_state           = R12_scratch2;
 743   const Register sync_state_addr      = sync_state;   // Address is dead after use.
 744   const Register suspend_flags        = R11_scratch1;
 745 
 746   //=============================================================================
 747   // Allocate new frame and initialize interpreter state.
 748 
 749   Label exception_return;
 750   Label exception_return_sync_check;
 751   Label stack_overflow_return;
 752 
 753   // Generate new interpreter state and jump to stack_overflow_return in case of
 754   // a stack overflow.
 755   //generate_compute_interpreter_state(stack_overflow_return);
 756 
 757   Register size_of_parameters = R22_tmp2;
 758 
 759   generate_fixed_frame(true, size_of_parameters, noreg /* unused */);
 760 
 761   //=============================================================================
 762   // Increment invocation counter. On overflow, entry to JNI method
 763   // will be compiled.
 764   Label invocation_counter_overflow, continue_after_compile;
 765   if (inc_counter) {
 766     if (synchronized) {
 767       // Since at this point in the method invocation the exception handler
 768       // would try to exit the monitor of synchronized methods which hasn't
 769       // been entered yet, we set the thread local variable
 770       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
 771       // runtime, exception handling i.e. unlock_if_synchronized_method will
 772       // check this thread local flag.
 773       // This flag has two effects, one is to force an unwind in the topmost
 774       // interpreter frame and not perform an unlock while doing so.
 775       __ li(R0, 1);
 776       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
 777     }
 778     generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
 779 
 780     __ BIND(continue_after_compile);
 781     // Reset the _do_not_unlock_if_synchronized flag.
 782     if (synchronized) {
 783       __ li(R0, 0);
 784       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
 785     }
 786   }
 787 
 788   // access_flags = method->access_flags();
 789   // Load access flags.
 790   assert(access_flags->is_nonvolatile(),
 791          "access_flags must be in a non-volatile register");
 792   // Type check.
 793   assert(4 == sizeof(AccessFlags), "unexpected field size");
 794   __ lwz(access_flags, method_(access_flags));
 795 
 796   // We don't want to reload R19_method and access_flags after calls
 797   // to some helper functions.
 798   assert(R19_method->is_nonvolatile(),
 799          "R19_method must be a non-volatile register");
 800 
 801   // Check for synchronized methods. Must happen AFTER invocation counter
 802   // check, so method is not locked if counter overflows.
 803 
 804   if (synchronized) {
 805     lock_method(access_flags, R11_scratch1, R12_scratch2, true);
 806 
 807     // Update monitor in state.
 808     __ ld(R11_scratch1, 0, R1_SP);
 809     __ std(R26_monitor, _ijava_state_neg(monitors), R11_scratch1);
 810   }
 811 
 812   // jvmti/jvmpi support
 813   __ notify_method_entry();
 814 
 815   //=============================================================================
 816   // Get and call the signature handler.
 817 
 818   __ ld(signature_handler_fd, method_(signature_handler));
 819   Label call_signature_handler;
 820 
 821   __ cmpdi(CCR0, signature_handler_fd, 0);
 822   __ bne(CCR0, call_signature_handler);
 823 
 824   // Method has never been called. Either generate a specialized
 825   // handler or point to the slow one.
 826   //
 827   // Pass parameter 'false' to avoid exception check in call_VM.
 828   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), R19_method, false);
 829 
 830   // Check for an exception while looking up the target method. If we
 831   // incurred one, bail.
 832   __ ld(pending_exception, thread_(pending_exception));
 833   __ cmpdi(CCR0, pending_exception, 0);
 834   __ bne(CCR0, exception_return_sync_check); // Has pending exception.
 835 
 836   // Reload signature handler, it may have been created/assigned in the meanwhile.
 837   __ ld(signature_handler_fd, method_(signature_handler));
 838   __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
 839 
 840   __ BIND(call_signature_handler);
 841 
 842   // Before we call the signature handler we push a new frame to
 843   // protect the interpreter frame volatile registers when we return
 844   // from jni but before we can get back to Java.
 845 
 846   // First set the frame anchor while the SP/FP registers are
 847   // convenient and the slow signature handler can use this same frame
 848   // anchor.
 849 
 850   // We have a TOP_IJAVA_FRAME here, which belongs to us.
 851   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
 852 
 853   // Now the interpreter frame (and its call chain) have been
 854   // invalidated and flushed. We are now protected against eager
 855   // being enabled in native code. Even if it goes eager the
 856   // registers will be reloaded as clean and we will invalidate after
 857   // the call so no spurious flush should be possible.
 858 
 859   // Call signature handler and pass locals address.
 860   //
 861   // Our signature handlers copy required arguments to the C stack
 862   // (outgoing C args), R3_ARG1 to R10_ARG8, and FARG1 to FARG13.
 863   __ mr(R3_ARG1, R18_locals);
 864 #if !defined(ABI_ELFv2)
 865   __ ld(signature_handler_fd, 0, signature_handler_fd);
 866 #endif
 867 
 868   __ call_stub(signature_handler_fd);
 869 
 870   // Remove the register parameter varargs slots we allocated in
 871   // compute_interpreter_state. SP+16 ends up pointing to the ABI
 872   // outgoing argument area.
 873   //
 874   // Not needed on PPC64.
 875   //__ add(SP, SP, Argument::n_register_parameters*BytesPerWord);
 876 
 877   assert(result_handler_addr->is_nonvolatile(), "result_handler_addr must be in a non-volatile register");
 878   // Save across call to native method.
 879   __ mr(result_handler_addr, R3_RET);
 880 
 881   __ isync(); // Acquire signature handler before trying to fetch the native entry point and klass mirror.
 882 
 883   // Set up fixed parameters and call the native method.
 884   // If the method is static, get mirror into R4_ARG2.
 885   {
 886     Label method_is_not_static;
 887     // Access_flags is non-volatile and still, no need to restore it.
 888 
 889     // Restore access flags.
 890     __ testbitdi(CCR0, R0, access_flags, JVM_ACC_STATIC_BIT);
 891     __ bfalse(CCR0, method_is_not_static);
 892 
 893     // constants = method->constants();
 894     __ ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
 895     __ ld(R11_scratch1, in_bytes(ConstMethod::constants_offset()), R11_scratch1);
 896     // pool_holder = method->constants()->pool_holder();
 897     __ ld(R11_scratch1/*pool_holder*/, ConstantPool::pool_holder_offset_in_bytes(),
 898           R11_scratch1/*constants*/);
 899 
 900     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 901 
 902     // mirror = pool_holder->klass_part()->java_mirror();
 903     __ ld(R0/*mirror*/, mirror_offset, R11_scratch1/*pool_holder*/);
 904     // state->_native_mirror = mirror;
 905 
 906     __ ld(R11_scratch1, 0, R1_SP);
 907     __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
 908     // R4_ARG2 = &state->_oop_temp;
 909     __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
 910     __ BIND(method_is_not_static);
 911   }
 912 
 913   // At this point, arguments have been copied off the stack into
 914   // their JNI positions. Oops are boxed in-place on the stack, with
 915   // handles copied to arguments. The result handler address is in a
 916   // register.
 917 
 918   // Pass JNIEnv address as first parameter.
 919   __ addir(R3_ARG1, thread_(jni_environment));
 920 
 921   // Load the native_method entry before we change the thread state.
 922   __ ld(native_method_fd, method_(native_function));
 923 
 924   //=============================================================================
 925   // Transition from _thread_in_Java to _thread_in_native. As soon as
 926   // we make this change the safepoint code needs to be certain that
 927   // the last Java frame we established is good. The pc in that frame
 928   // just needs to be near here not an actual return address.
 929 
 930   // We use release_store_fence to update values like the thread state, where
 931   // we don't want the current thread to continue until all our prior memory
 932   // accesses (including the new thread state) are visible to other threads.
 933   __ li(R0, _thread_in_native);
 934   __ release();
 935 
 936   // TODO PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
 937   __ stw(R0, thread_(thread_state));
 938 
 939   if (UseMembar) {
 940     __ fence();
 941   }
 942 
 943   //=============================================================================
 944   // Call the native method. Argument registers must not have been
 945   // overwritten since "__ call_stub(signature_handler);" (except for
 946   // ARG1 and ARG2 for static methods).
 947   __ call_c(native_method_fd);
 948 
 949   __ li(R0, 0);
 950   __ ld(R11_scratch1, 0, R1_SP);
 951   __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
 952   __ stfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
 953   __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1); // reset
 954 
 955   // Note: C++ interpreter needs the following here:
 956   // The frame_manager_lr field, which we use for setting the last
 957   // java frame, gets overwritten by the signature handler. Restore
 958   // it now.
 959   //__ get_PC_trash_LR(R11_scratch1);
 960   //__ std(R11_scratch1, _top_ijava_frame_abi(frame_manager_lr), R1_SP);
 961 
 962   // Because of GC R19_method may no longer be valid.
 963 
 964   // Block, if necessary, before resuming in _thread_in_Java state.
 965   // In order for GC to work, don't clear the last_Java_sp until after
 966   // blocking.
 967 
 968   //=============================================================================
 969   // Switch thread to "native transition" state before reading the
 970   // synchronization state. This additional state is necessary
 971   // because reading and testing the synchronization state is not
 972   // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
 973   // in _thread_in_native state, loads _not_synchronized and is
 974   // preempted. VM thread changes sync state to synchronizing and
 975   // suspends threads for GC. Thread A is resumed to finish this
 976   // native method, but doesn't block here since it didn't see any
 977   // synchronization in progress, and escapes.
 978 
 979   // We use release_store_fence to update values like the thread state, where
 980   // we don't want the current thread to continue until all our prior memory
 981   // accesses (including the new thread state) are visible to other threads.
 982   __ li(R0/*thread_state*/, _thread_in_native_trans);
 983   __ release();
 984   __ stw(R0/*thread_state*/, thread_(thread_state));
 985   if (UseMembar) {
 986     __ fence();
 987   }
 988   // Write serialization page so that the VM thread can do a pseudo remote
 989   // membar. We use the current thread pointer to calculate a thread
 990   // specific offset to write to within the page. This minimizes bus
 991   // traffic due to cache line collision.
 992   else {
 993     __ serialize_memory(R16_thread, R11_scratch1, R12_scratch2);
 994   }
 995 
 996   // Now before we return to java we must look for a current safepoint
 997   // (a new safepoint can not start since we entered native_trans).
 998   // We must check here because a current safepoint could be modifying
 999   // the callers registers right this moment.
1000 
1001   // Acquire isn't strictly necessary here because of the fence, but
1002   // sync_state is declared to be volatile, so we do it anyway
1003   // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
1004   int sync_state_offs = __ load_const_optimized(sync_state_addr, SafepointSynchronize::address_of_state(), /*temp*/R0, true);
1005 
1006   // TODO PPC port assert(4 == SafepointSynchronize::sz_state(), "unexpected field size");
1007   __ lwz(sync_state, sync_state_offs, sync_state_addr);
1008 
1009   // TODO PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
1010   __ lwz(suspend_flags, thread_(suspend_flags));
1011 
1012   Label sync_check_done;
1013   Label do_safepoint;
1014   // No synchronization in progress nor yet synchronized.
1015   __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
1016   // Not suspended.
1017   __ cmpwi(CCR1, suspend_flags, 0);
1018 
1019   __ bne(CCR0, do_safepoint);
1020   __ beq(CCR1, sync_check_done);
1021   __ bind(do_safepoint);
1022   __ isync();
1023   // Block. We do the call directly and leave the current
1024   // last_Java_frame setup undisturbed. We must save any possible
1025   // native result across the call. No oop is present.
1026 
1027   __ mr(R3_ARG1, R16_thread);
1028 #if defined(ABI_ELFv2)
1029   __ call_c(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans),
1030             relocInfo::none);
1031 #else
1032   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, JavaThread::check_special_condition_for_native_trans),
1033             relocInfo::none);
1034 #endif
1035 
1036   __ bind(sync_check_done);
1037 
1038   //=============================================================================
1039   // <<<<<< Back in Interpreter Frame >>>>>
1040 
1041   // We are in thread_in_native_trans here and back in the normal
1042   // interpreter frame. We don't have to do anything special about
1043   // safepoints and we can switch to Java mode anytime we are ready.
1044 
1045   // Note: frame::interpreter_frame_result has a dependency on how the
1046   // method result is saved across the call to post_method_exit. For
1047   // native methods it assumes that the non-FPU/non-void result is
1048   // saved in _native_lresult and a FPU result in _native_fresult. If
1049   // this changes then the interpreter_frame_result implementation
1050   // will need to be updated too.
1051 
1052   // On PPC64, we have stored the result directly after the native call.
1053 
1054   //=============================================================================
1055   // Back in Java
1056 
1057   // We use release_store_fence to update values like the thread state, where
1058   // we don't want the current thread to continue until all our prior memory
1059   // accesses (including the new thread state) are visible to other threads.
1060   __ li(R0/*thread_state*/, _thread_in_Java);
1061   __ release();
1062   __ stw(R0/*thread_state*/, thread_(thread_state));
1063   if (UseMembar) {
1064     __ fence();
1065   }
1066 
1067   __ reset_last_Java_frame();
1068 
1069   // Jvmdi/jvmpi support. Whether we've got an exception pending or
1070   // not, and whether unlocking throws an exception or not, we notify
1071   // on native method exit. If we do have an exception, we'll end up
1072   // in the caller's context to handle it, so if we don't do the
1073   // notify here, we'll drop it on the floor.
1074   __ notify_method_exit(true/*native method*/,
1075                         ilgl /*illegal state (not used for native methods)*/,
1076                         InterpreterMacroAssembler::NotifyJVMTI,
1077                         false /*check_exceptions*/);
1078 
1079   //=============================================================================
1080   // Handle exceptions
1081 
1082   if (synchronized) {
1083     // Don't check for exceptions since we're still in the i2n frame. Do that
1084     // manually afterwards.
1085     unlock_method(false);
1086   }
1087 
1088   // Reset active handles after returning from native.
1089   // thread->active_handles()->clear();
1090   __ ld(active_handles, thread_(active_handles));
1091   // TODO PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
1092   __ li(R0, 0);
1093   __ stw(R0, JNIHandleBlock::top_offset_in_bytes(), active_handles);
1094 
1095   Label exception_return_sync_check_already_unlocked;
1096   __ ld(R0/*pending_exception*/, thread_(pending_exception));
1097   __ cmpdi(CCR0, R0/*pending_exception*/, 0);
1098   __ bne(CCR0, exception_return_sync_check_already_unlocked);
1099 
1100   //-----------------------------------------------------------------------------
1101   // No exception pending.
1102 
1103   // Move native method result back into proper registers and return.
1104   // Invoke result handler (may unbox/promote).
1105   __ ld(R11_scratch1, 0, R1_SP);
1106   __ ld(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1107   __ lfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1108   __ call_stub(result_handler_addr);
1109 
1110   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
1111 
1112   // Must use the return pc which was loaded from the caller's frame
1113   // as the VM uses return-pc-patching for deoptimization.
1114   __ mtlr(R0);
1115   __ blr();
1116 
1117   //-----------------------------------------------------------------------------
1118   // An exception is pending. We call into the runtime only if the
1119   // caller was not interpreted. If it was interpreted the
1120   // interpreter will do the correct thing. If it isn't interpreted
1121   // (call stub/compiled code) we will change our return and continue.
1122 
1123   __ BIND(exception_return_sync_check);
1124 
1125   if (synchronized) {
1126     // Don't check for exceptions since we're still in the i2n frame. Do that
1127     // manually afterwards.
1128     unlock_method(false);
1129   }
1130   __ BIND(exception_return_sync_check_already_unlocked);
1131 
1132   const Register return_pc = R31;
1133 
1134   __ ld(return_pc, 0, R1_SP);
1135   __ ld(return_pc, _abi(lr), return_pc);
1136 
1137   // Get the address of the exception handler.
1138   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1139                   R16_thread,
1140                   return_pc /* return pc */);
1141   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, noreg, R11_scratch1, R12_scratch2);
1142 
1143   // Load the PC of the the exception handler into LR.
1144   __ mtlr(R3_RET);
1145 
1146   // Load exception into R3_ARG1 and clear pending exception in thread.
1147   __ ld(R3_ARG1/*exception*/, thread_(pending_exception));
1148   __ li(R4_ARG2, 0);
1149   __ std(R4_ARG2, thread_(pending_exception));
1150 
1151   // Load the original return pc into R4_ARG2.
1152   __ mr(R4_ARG2/*issuing_pc*/, return_pc);
1153 
1154   // Return to exception handler.
1155   __ blr();
1156 
1157   //=============================================================================
1158   // Counter overflow.
1159 
1160   if (inc_counter) {
1161     // Handle invocation counter overflow.
1162     __ bind(invocation_counter_overflow);
1163 
1164     generate_counter_overflow(continue_after_compile);
1165   }
1166 
1167   return entry;
1168 }
1169 
1170 // Generic interpreted method entry to (asm) interpreter.
1171 //
1172 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1173   bool inc_counter = UseCompiler || CountCompiledCalls;
1174   address entry = __ pc();
1175   // Generate the code to allocate the interpreter stack frame.
1176   Register Rsize_of_parameters = R4_ARG2, // Written by generate_fixed_frame.
1177            Rsize_of_locals     = R5_ARG3; // Written by generate_fixed_frame.
1178 
1179   generate_fixed_frame(false, Rsize_of_parameters, Rsize_of_locals);
1180 
1181 #ifdef FAST_DISPATCH
1182   __ unimplemented("Fast dispatch in generate_normal_entry");
1183 #if 0
1184   __ set((intptr_t)Interpreter::dispatch_table(), IdispatchTables);
1185   // Set bytecode dispatch table base.
1186 #endif
1187 #endif
1188 
1189   // --------------------------------------------------------------------------
1190   // Zero out non-parameter locals.
1191   // Note: *Always* zero out non-parameter locals as Sparc does. It's not
1192   // worth to ask the flag, just do it.
1193   Register Rslot_addr = R6_ARG4,
1194            Rnum       = R7_ARG5;
1195   Label Lno_locals, Lzero_loop;
1196 
1197   // Set up the zeroing loop.
1198   __ subf(Rnum, Rsize_of_parameters, Rsize_of_locals);
1199   __ subf(Rslot_addr, Rsize_of_parameters, R18_locals);
1200   __ srdi_(Rnum, Rnum, Interpreter::logStackElementSize);
1201   __ beq(CCR0, Lno_locals);
1202   __ li(R0, 0);
1203   __ mtctr(Rnum);
1204 
1205   // The zero locals loop.
1206   __ bind(Lzero_loop);
1207   __ std(R0, 0, Rslot_addr);
1208   __ addi(Rslot_addr, Rslot_addr, -Interpreter::stackElementSize);
1209   __ bdnz(Lzero_loop);
1210 
1211   __ bind(Lno_locals);
1212 
1213   // --------------------------------------------------------------------------
1214   // Counter increment and overflow check.
1215   Label invocation_counter_overflow,
1216         profile_method,
1217         profile_method_continue;
1218   if (inc_counter || ProfileInterpreter) {
1219 
1220     Register Rdo_not_unlock_if_synchronized_addr = R11_scratch1;
1221     if (synchronized) {
1222       // Since at this point in the method invocation the exception handler
1223       // would try to exit the monitor of synchronized methods which hasn't
1224       // been entered yet, we set the thread local variable
1225       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1226       // runtime, exception handling i.e. unlock_if_synchronized_method will
1227       // check this thread local flag.
1228       // This flag has two effects, one is to force an unwind in the topmost
1229       // interpreter frame and not perform an unlock while doing so.
1230       __ li(R0, 1);
1231       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1232     }
1233     // Increment invocation counter and check for overflow.
1234     if (inc_counter) {
1235       generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
1236     }
1237 
1238     __ bind(profile_method_continue);
1239 
1240     // Reset the _do_not_unlock_if_synchronized flag.
1241     if (synchronized) {
1242       __ li(R0, 0);
1243       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1244     }
1245   }
1246 
1247   // --------------------------------------------------------------------------
1248   // Locking of synchronized methods. Must happen AFTER invocation_counter
1249   // check and stack overflow check, so method is not locked if overflows.
1250   if (synchronized) {
1251     lock_method(R3_ARG1, R4_ARG2, R5_ARG3);
1252   }
1253 #ifdef ASSERT
1254   else {
1255     Label Lok;
1256     __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1257     __ andi_(R0, R0, JVM_ACC_SYNCHRONIZED);
1258     __ asm_assert_eq("method needs synchronization", 0x8521);
1259     __ bind(Lok);
1260   }
1261 #endif // ASSERT
1262 
1263   __ verify_thread();
1264 
1265   // --------------------------------------------------------------------------
1266   // JVMTI support
1267   __ notify_method_entry();
1268 
1269   // --------------------------------------------------------------------------
1270   // Start executing instructions.
1271   __ dispatch_next(vtos);
1272 
1273   // --------------------------------------------------------------------------
1274   // Out of line counter overflow and MDO creation code.
1275   if (ProfileInterpreter) {
1276     // We have decided to profile this method in the interpreter.
1277     __ bind(profile_method);
1278     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1279     __ set_method_data_pointer_for_bcp();
1280     __ b(profile_method_continue);
1281   }
1282 
1283   if (inc_counter) {
1284     // Handle invocation counter overflow.
1285     __ bind(invocation_counter_overflow);
1286     generate_counter_overflow(profile_method_continue);
1287   }
1288   return entry;
1289 }
1290 
1291 // =============================================================================
1292 // Entry points
1293 
1294 address AbstractInterpreterGenerator::generate_method_entry(
1295                                         AbstractInterpreter::MethodKind kind) {
1296   // Determine code generation flags.
1297   bool synchronized = false;
1298   address entry_point = NULL;
1299 
1300   switch (kind) {
1301   case Interpreter::zerolocals             :                                                                             break;
1302   case Interpreter::zerolocals_synchronized: synchronized = true;                                                        break;
1303   case Interpreter::native                 : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(false); break;
1304   case Interpreter::native_synchronized    : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(true);  break;
1305   case Interpreter::empty                  : entry_point = ((InterpreterGenerator*) this)->generate_empty_entry();       break;
1306   case Interpreter::accessor               : entry_point = ((InterpreterGenerator*) this)->generate_accessor_entry();    break;
1307   case Interpreter::abstract               : entry_point = ((InterpreterGenerator*) this)->generate_abstract_entry();    break;
1308 
1309   case Interpreter::java_lang_math_sin     : // fall thru
1310   case Interpreter::java_lang_math_cos     : // fall thru
1311   case Interpreter::java_lang_math_tan     : // fall thru
1312   case Interpreter::java_lang_math_abs     : // fall thru
1313   case Interpreter::java_lang_math_log     : // fall thru
1314   case Interpreter::java_lang_math_log10   : // fall thru
1315   case Interpreter::java_lang_math_sqrt    : // fall thru
1316   case Interpreter::java_lang_math_pow     : // fall thru
1317   case Interpreter::java_lang_math_exp     : entry_point = ((InterpreterGenerator*) this)->generate_math_entry(kind);    break;
1318   case Interpreter::java_lang_ref_reference_get
1319                                            : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
1320   default                                  : ShouldNotReachHere();                                                       break;
1321   }
1322 
1323   if (entry_point) {
1324     return entry_point;
1325   }
1326 
1327   return ((InterpreterGenerator*) this)->generate_normal_entry(synchronized);
1328 }
1329 
1330 // These should never be compiled since the interpreter will prefer
1331 // the compiled version to the intrinsic version.
1332 bool AbstractInterpreter::can_be_compiled(methodHandle m) {
1333   return !math_entry_available(method_kind(m));
1334 }
1335 
1336 // How much stack a method activation needs in stack slots.
1337 // We must calc this exactly like in generate_fixed_frame.
1338 // Note: This returns the conservative size assuming maximum alignment.
1339 int AbstractInterpreter::size_top_interpreter_activation(Method* method) {
1340   const int max_alignment_size = 2;
1341   const int abi_scratch = frame::abi_reg_args_size;
1342   return method->max_locals() + method->max_stack() +
1343          frame::interpreter_frame_monitor_size() + max_alignment_size + abi_scratch;
1344 }
1345 
1346 // Returns number of stackElementWords needed for the interpreter frame with the
1347 // given sections.
1348 // This overestimates the stack by one slot in case of alignments.
1349 int AbstractInterpreter::size_activation(int max_stack,
1350                                          int temps,
1351                                          int extra_args,
1352                                          int monitors,
1353                                          int callee_params,
1354                                          int callee_locals,
1355                                          bool is_top_frame) {
1356   // Note: This calculation must exactly parallel the frame setup
1357   // in AbstractInterpreterGenerator::generate_method_entry.
1358   assert(Interpreter::stackElementWords == 1, "sanity");
1359   const int max_alignment_space = StackAlignmentInBytes / Interpreter::stackElementSize;
1360   const int abi_scratch = is_top_frame ? (frame::abi_reg_args_size / Interpreter::stackElementSize) :
1361                                          (frame::abi_minframe_size / Interpreter::stackElementSize);
1362   const int size =
1363     max_stack                                                +
1364     (callee_locals - callee_params)                          +
1365     monitors * frame::interpreter_frame_monitor_size()       +
1366     max_alignment_space                                      +
1367     abi_scratch                                              +
1368     frame::ijava_state_size / Interpreter::stackElementSize;
1369 
1370   // Fixed size of an interpreter frame, align to 16-byte.
1371   return (size & -2);
1372 }
1373 
1374 // Fills a sceletal interpreter frame generated during deoptimizations.
1375 //
1376 // Parameters:
1377 //
1378 // interpreter_frame != NULL:
1379 //   set up the method, locals, and monitors.
1380 //   The frame interpreter_frame, if not NULL, is guaranteed to be the
1381 //   right size, as determined by a previous call to this method.
1382 //   It is also guaranteed to be walkable even though it is in a skeletal state
1383 //
1384 // is_top_frame == true:
1385 //   We're processing the *oldest* interpreter frame!
1386 //
1387 // pop_frame_extra_args:
1388 //   If this is != 0 we are returning to a deoptimized frame by popping
1389 //   off the callee frame. We want to re-execute the call that called the
1390 //   callee interpreted, but since the return to the interpreter would pop
1391 //   the arguments off advance the esp by dummy popframe_extra_args slots.
1392 //   Popping off those will establish the stack layout as it was before the call.
1393 //
1394 void AbstractInterpreter::layout_activation(Method* method,
1395                                             int tempcount,
1396                                             int popframe_extra_args,
1397                                             int moncount,
1398                                             int caller_actual_parameters,
1399                                             int callee_param_count,
1400                                             int callee_locals_count,
1401                                             frame* caller,
1402                                             frame* interpreter_frame,
1403                                             bool is_top_frame,
1404                                             bool is_bottom_frame) {
1405 
1406   const int abi_scratch = is_top_frame ? (frame::abi_reg_args_size / Interpreter::stackElementSize) :
1407                                          (frame::abi_minframe_size / Interpreter::stackElementSize);
1408 
1409   intptr_t* locals_base  = (caller->is_interpreted_frame()) ?
1410     caller->interpreter_frame_esp() + caller_actual_parameters :
1411     caller->sp() + method->max_locals() - 1 + (frame::abi_minframe_size / Interpreter::stackElementSize) ;
1412 
1413   intptr_t* monitor_base = caller->sp() - frame::ijava_state_size / Interpreter::stackElementSize ;
1414   intptr_t* monitor      = monitor_base - (moncount * frame::interpreter_frame_monitor_size());
1415   intptr_t* esp_base     = monitor - 1;
1416   intptr_t* esp          = esp_base - tempcount - popframe_extra_args;
1417   intptr_t* sp           = (intptr_t *) (((intptr_t) (esp_base - callee_locals_count + callee_param_count - method->max_stack()- abi_scratch)) & -StackAlignmentInBytes);
1418   intptr_t* sender_sp    = caller->sp() + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
1419   intptr_t* top_frame_sp = is_top_frame ? sp : sp + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
1420 
1421   interpreter_frame->interpreter_frame_set_method(method);
1422   interpreter_frame->interpreter_frame_set_locals(locals_base);
1423   interpreter_frame->interpreter_frame_set_cpcache(method->constants()->cache());
1424   interpreter_frame->interpreter_frame_set_esp(esp);
1425   interpreter_frame->interpreter_frame_set_monitor_end((BasicObjectLock *)monitor);
1426   interpreter_frame->interpreter_frame_set_top_frame_sp(top_frame_sp);
1427   if (!is_bottom_frame) {
1428     interpreter_frame->interpreter_frame_set_sender_sp(sender_sp);
1429   }
1430 }
1431 
1432 // =============================================================================
1433 // Exceptions
1434 
1435 void TemplateInterpreterGenerator::generate_throw_exception() {
1436   Register Rexception    = R17_tos,
1437            Rcontinuation = R3_RET;
1438 
1439   // --------------------------------------------------------------------------
1440   // Entry point if an method returns with a pending exception (rethrow).
1441   Interpreter::_rethrow_exception_entry = __ pc();
1442   {
1443     __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
1444     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
1445     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
1446 
1447     // Compiled code destroys templateTableBase, reload.
1448     __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
1449   }
1450 
1451   // Entry point if a interpreted method throws an exception (throw).
1452   Interpreter::_throw_exception_entry = __ pc();
1453   {
1454     __ mr(Rexception, R3_RET);
1455 
1456     __ verify_thread();
1457     __ verify_oop(Rexception);
1458 
1459     // Expression stack must be empty before entering the VM in case of an exception.
1460     __ empty_expression_stack();
1461     // Find exception handler address and preserve exception oop.
1462     // Call C routine to find handler and jump to it.
1463     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Rexception);
1464     __ mtctr(Rcontinuation);
1465     // Push exception for exception handler bytecodes.
1466     __ push_ptr(Rexception);
1467 
1468     // Jump to exception handler (may be remove activation entry!).
1469     __ bctr();
1470   }
1471 
1472   // If the exception is not handled in the current frame the frame is
1473   // removed and the exception is rethrown (i.e. exception
1474   // continuation is _rethrow_exception).
1475   //
1476   // Note: At this point the bci is still the bxi for the instruction
1477   // which caused the exception and the expression stack is
1478   // empty. Thus, for any VM calls at this point, GC will find a legal
1479   // oop map (with empty expression stack).
1480 
1481   // In current activation
1482   // tos: exception
1483   // bcp: exception bcp
1484 
1485   // --------------------------------------------------------------------------
1486   // JVMTI PopFrame support
1487 
1488   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1489   {
1490     // Set the popframe_processing bit in popframe_condition indicating that we are
1491     // currently handling popframe, so that call_VMs that may happen later do not
1492     // trigger new popframe handling cycles.
1493     __ lwz(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1494     __ ori(R11_scratch1, R11_scratch1, JavaThread::popframe_processing_bit);
1495     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1496 
1497     // Empty the expression stack, as in normal exception handling.
1498     __ empty_expression_stack();
1499     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
1500 
1501     // Check to see whether we are returning to a deoptimized frame.
1502     // (The PopFrame call ensures that the caller of the popped frame is
1503     // either interpreted or compiled and deoptimizes it if compiled.)
1504     // Note that we don't compare the return PC against the
1505     // deoptimization blob's unpack entry because of the presence of
1506     // adapter frames in C2.
1507     Label Lcaller_not_deoptimized;
1508     Register return_pc = R3_ARG1;
1509     __ ld(return_pc, 0, R1_SP);
1510     __ ld(return_pc, _abi(lr), return_pc);
1511     __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), return_pc);
1512     __ cmpdi(CCR0, R3_RET, 0);
1513     __ bne(CCR0, Lcaller_not_deoptimized);
1514 
1515     // The deoptimized case.
1516     // In this case, we can't call dispatch_next() after the frame is
1517     // popped, but instead must save the incoming arguments and restore
1518     // them after deoptimization has occurred.
1519     __ ld(R4_ARG2, in_bytes(Method::const_offset()), R19_method);
1520     __ lhz(R4_ARG2 /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), R4_ARG2);
1521     __ slwi(R4_ARG2, R4_ARG2, Interpreter::logStackElementSize);
1522     __ addi(R5_ARG3, R18_locals, Interpreter::stackElementSize);
1523     __ subf(R5_ARG3, R4_ARG2, R5_ARG3);
1524     // Save these arguments.
1525     __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), R16_thread, R4_ARG2, R5_ARG3);
1526 
1527     // Inform deoptimization that it is responsible for restoring these arguments.
1528     __ load_const_optimized(R11_scratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1529     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1530 
1531     // Return from the current method into the deoptimization blob. Will eventually
1532     // end up in the deopt interpeter entry, deoptimization prepared everything that
1533     // we will reexecute the call that called us.
1534     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*reload return_pc*/ return_pc, R11_scratch1, R12_scratch2);
1535     __ mtlr(return_pc);
1536     __ blr();
1537 
1538     // The non-deoptimized case.
1539     __ bind(Lcaller_not_deoptimized);
1540 
1541     // Clear the popframe condition flag.
1542     __ li(R0, 0);
1543     __ stw(R0, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1544 
1545     // Get out of the current method and re-execute the call that called us.
1546     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
1547     __ restore_interpreter_state(R11_scratch1);
1548     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
1549     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
1550     if (ProfileInterpreter) {
1551       __ set_method_data_pointer_for_bcp();
1552     }
1553 #if INCLUDE_JVMTI
1554     Label L_done;
1555 
1556     __ lbz(R11_scratch1, 0, R14_bcp);
1557     __ cmpwi(CCR0, R11_scratch1, Bytecodes::_invokestatic);
1558     __ bne(CCR0, L_done);
1559 
1560     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1561     // Detect such a case in the InterpreterRuntime function and return the member name argument, or NULL.
1562     __ ld(R4_ARG2, 0, R18_locals);
1563     __ call_VM(R11_scratch1, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null),
1564                R4_ARG2, R19_method, R14_bcp);
1565 
1566     __ cmpdi(CCR0, R11_scratch1, 0);
1567     __ beq(CCR0, L_done);
1568 
1569     __ std(R11_scratch1, wordSize, R15_esp);
1570     __ bind(L_done);
1571 #endif // INCLUDE_JVMTI
1572     __ dispatch_next(vtos);
1573   }
1574   // end of JVMTI PopFrame support
1575 
1576   // --------------------------------------------------------------------------
1577   // Remove activation exception entry.
1578   // This is jumped to if an interpreted method can't handle an exception itself
1579   // (we come from the throw/rethrow exception entry above). We're going to call
1580   // into the VM to find the exception handler in the caller, pop the current
1581   // frame and return the handler we calculated.
1582   Interpreter::_remove_activation_entry = __ pc();
1583   {
1584     __ pop_ptr(Rexception);
1585     __ verify_thread();
1586     __ verify_oop(Rexception);
1587     __ std(Rexception, in_bytes(JavaThread::vm_result_offset()), R16_thread);
1588 
1589     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, true);
1590     __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI, false);
1591 
1592     __ get_vm_result(Rexception);
1593 
1594     // We are done with this activation frame; find out where to go next.
1595     // The continuation point will be an exception handler, which expects
1596     // the following registers set up:
1597     //
1598     // RET:  exception oop
1599     // ARG2: Issuing PC (see generate_exception_blob()), only used if the caller is compiled.
1600 
1601     Register return_pc = R31; // Needs to survive the runtime call.
1602     __ ld(return_pc, 0, R1_SP);
1603     __ ld(return_pc, _abi(lr), return_pc);
1604     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), R16_thread, return_pc);
1605 
1606     // Remove the current activation.
1607     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
1608 
1609     __ mr(R4_ARG2, return_pc);
1610     __ mtlr(R3_RET);
1611     __ mr(R3_RET, Rexception);
1612     __ blr();
1613   }
1614 }
1615 
1616 // JVMTI ForceEarlyReturn support.
1617 // Returns "in the middle" of a method with a "fake" return value.
1618 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1619 
1620   Register Rscratch1 = R11_scratch1,
1621            Rscratch2 = R12_scratch2;
1622 
1623   address entry = __ pc();
1624   __ empty_expression_stack();
1625 
1626   __ load_earlyret_value(state, Rscratch1);
1627 
1628   __ ld(Rscratch1, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
1629   // Clear the earlyret state.
1630   __ li(R0, 0);
1631   __ stw(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rscratch1);
1632 
1633   __ remove_activation(state, false, false);
1634   // Copied from TemplateTable::_return.
1635   // Restoration of lr done by remove_activation.
1636   switch (state) {
1637     case ltos:
1638     case btos:
1639     case ctos:
1640     case stos:
1641     case atos:
1642     case itos: __ mr(R3_RET, R17_tos); break;
1643     case ftos:
1644     case dtos: __ fmr(F1_RET, F15_ftos); break;
1645     case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
1646                // to get visible before the reference to the object gets stored anywhere.
1647                __ membar(Assembler::StoreStore); break;
1648     default  : ShouldNotReachHere();
1649   }
1650   __ blr();
1651 
1652   return entry;
1653 } // end of ForceEarlyReturn support
1654 
1655 //-----------------------------------------------------------------------------
1656 // Helper for vtos entry point generation
1657 
1658 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
1659                                                          address& bep,
1660                                                          address& cep,
1661                                                          address& sep,
1662                                                          address& aep,
1663                                                          address& iep,
1664                                                          address& lep,
1665                                                          address& fep,
1666                                                          address& dep,
1667                                                          address& vep) {
1668   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1669   Label L;
1670 
1671   aep = __ pc();  __ push_ptr();  __ b(L);
1672   fep = __ pc();  __ push_f();    __ b(L);
1673   dep = __ pc();  __ push_d();    __ b(L);
1674   lep = __ pc();  __ push_l();    __ b(L);
1675   __ align(32, 12, 24); // align L
1676   bep = cep = sep =
1677   iep = __ pc();  __ push_i();
1678   vep = __ pc();
1679   __ bind(L);
1680   generate_and_dispatch(t);
1681 }
1682 
1683 //-----------------------------------------------------------------------------
1684 // Generation of individual instructions
1685 
1686 // helpers for generate_and_dispatch
1687 
1688 InterpreterGenerator::InterpreterGenerator(StubQueue* code)
1689   : TemplateInterpreterGenerator(code) {
1690   generate_all(); // Down here so it can be "virtual".
1691 }
1692 
1693 //-----------------------------------------------------------------------------
1694 
1695 // Non-product code
1696 #ifndef PRODUCT
1697 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1698   //__ flush_bundle();
1699   address entry = __ pc();
1700 
1701   const char *bname = NULL;
1702   uint tsize = 0;
1703   switch(state) {
1704   case ftos:
1705     bname = "trace_code_ftos {";
1706     tsize = 2;
1707     break;
1708   case btos:
1709     bname = "trace_code_btos {";
1710     tsize = 2;
1711     break;
1712   case ctos:
1713     bname = "trace_code_ctos {";
1714     tsize = 2;
1715     break;
1716   case stos:
1717     bname = "trace_code_stos {";
1718     tsize = 2;
1719     break;
1720   case itos:
1721     bname = "trace_code_itos {";
1722     tsize = 2;
1723     break;
1724   case ltos:
1725     bname = "trace_code_ltos {";
1726     tsize = 3;
1727     break;
1728   case atos:
1729     bname = "trace_code_atos {";
1730     tsize = 2;
1731     break;
1732   case vtos:
1733     // Note: In case of vtos, the topmost of stack value could be a int or doubl
1734     // In case of a double (2 slots) we won't see the 2nd stack value.
1735     // Maybe we simply should print the topmost 3 stack slots to cope with the problem.
1736     bname = "trace_code_vtos {";
1737     tsize = 2;
1738 
1739     break;
1740   case dtos:
1741     bname = "trace_code_dtos {";
1742     tsize = 3;
1743     break;
1744   default:
1745     ShouldNotReachHere();
1746   }
1747   BLOCK_COMMENT(bname);
1748 
1749   // Support short-cut for TraceBytecodesAt.
1750   // Don't call into the VM if we don't want to trace to speed up things.
1751   Label Lskip_vm_call;
1752   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
1753     int offs1 = __ load_const_optimized(R11_scratch1, (address) &TraceBytecodesAt, R0, true);
1754     int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
1755     __ ld(R11_scratch1, offs1, R11_scratch1);
1756     __ lwa(R12_scratch2, offs2, R12_scratch2);
1757     __ cmpd(CCR0, R12_scratch2, R11_scratch1);
1758     __ blt(CCR0, Lskip_vm_call);
1759   }
1760 
1761   __ push(state);
1762   // Load 2 topmost expression stack values.
1763   __ ld(R6_ARG4, tsize*Interpreter::stackElementSize, R15_esp);
1764   __ ld(R5_ARG3, Interpreter::stackElementSize, R15_esp);
1765   __ mflr(R31);
1766   __ call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::trace_bytecode), /* unused */ R4_ARG2, R5_ARG3, R6_ARG4, false);
1767   __ mtlr(R31);
1768   __ pop(state);
1769 
1770   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
1771     __ bind(Lskip_vm_call);
1772   }
1773   __ blr();
1774   BLOCK_COMMENT("} trace_code");
1775   return entry;
1776 }
1777 
1778 void TemplateInterpreterGenerator::count_bytecode() {
1779   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeCounter::_counter_value, R12_scratch2, true);
1780   __ lwz(R12_scratch2, offs, R11_scratch1);
1781   __ addi(R12_scratch2, R12_scratch2, 1);
1782   __ stw(R12_scratch2, offs, R11_scratch1);
1783 }
1784 
1785 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1786   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeHistogram::_counters[t->bytecode()], R12_scratch2, true);
1787   __ lwz(R12_scratch2, offs, R11_scratch1);
1788   __ addi(R12_scratch2, R12_scratch2, 1);
1789   __ stw(R12_scratch2, offs, R11_scratch1);
1790 }
1791 
1792 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1793   const Register addr = R11_scratch1,
1794                  tmp  = R12_scratch2;
1795   // Get index, shift out old bytecode, bring in new bytecode, and store it.
1796   // _index = (_index >> log2_number_of_codes) |
1797   //          (bytecode << log2_number_of_codes);
1798   int offs1 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_index, tmp, true);
1799   __ lwz(tmp, offs1, addr);
1800   __ srwi(tmp, tmp, BytecodePairHistogram::log2_number_of_codes);
1801   __ ori(tmp, tmp, ((int) t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
1802   __ stw(tmp, offs1, addr);
1803 
1804   // Bump bucket contents.
1805   // _counters[_index] ++;
1806   int offs2 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_counters, R0, true);
1807   __ sldi(tmp, tmp, LogBytesPerInt);
1808   __ add(addr, tmp, addr);
1809   __ lwz(tmp, offs2, addr);
1810   __ addi(tmp, tmp, 1);
1811   __ stw(tmp, offs2, addr);
1812 }
1813 
1814 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
1815   // Call a little run-time stub to avoid blow-up for each bytecode.
1816   // The run-time runtime saves the right registers, depending on
1817   // the tosca in-state for the given template.
1818 
1819   assert(Interpreter::trace_code(t->tos_in()) != NULL,
1820          "entry must have been generated");
1821 
1822   // Note: we destroy LR here.
1823   __ bl(Interpreter::trace_code(t->tos_in()));
1824 }
1825 
1826 void TemplateInterpreterGenerator::stop_interpreter_at() {
1827   Label L;
1828   int offs1 = __ load_const_optimized(R11_scratch1, (address) &StopInterpreterAt, R0, true);
1829   int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
1830   __ ld(R11_scratch1, offs1, R11_scratch1);
1831   __ lwa(R12_scratch2, offs2, R12_scratch2);
1832   __ cmpd(CCR0, R12_scratch2, R11_scratch1);
1833   __ bne(CCR0, L);
1834   __ illtrap();
1835   __ bind(L);
1836 }
1837 
1838 #endif // !PRODUCT
1839 #endif // !CC_INTERP