1 /*
   2  * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2015, 2021 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interpreter/bytecodeHistogram.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "interpreter/interpreterRuntime.hpp"
  33 #include "interpreter/interp_masm.hpp"
  34 #include "interpreter/templateInterpreterGenerator.hpp"
  35 #include "interpreter/templateTable.hpp"
  36 #include "oops/arrayOop.hpp"
  37 #include "oops/methodData.hpp"
  38 #include "oops/method.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/jvmtiExport.hpp"
  41 #include "prims/jvmtiThreadState.hpp"
  42 #include "runtime/arguments.hpp"
  43 #include "runtime/deoptimization.hpp"
  44 #include "runtime/frame.inline.hpp"
  45 #include "runtime/jniHandles.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/synchronizer.hpp"
  49 #include "runtime/timer.hpp"
  50 #include "runtime/vframeArray.hpp"
  51 #include "runtime/vm_version.hpp"
  52 #include "utilities/debug.hpp"
  53 #include "utilities/macros.hpp"
  54 
  55 #undef __
  56 #define __ _masm->
  57 
  58 // Size of interpreter code.  Increase if too small.  Interpreter will
  59 // fail with a guarantee ("not enough space for interpreter generation");
  60 // if too small.
  61 // Run with +PrintInterpreter to get the VM to print out the size.
  62 // Max size with JVMTI
  63 int TemplateInterpreter::InterpreterCodeSize = 256*K;
  64 
  65 #ifdef PRODUCT
  66 #define BLOCK_COMMENT(str) /* nothing */
  67 #else
  68 #define BLOCK_COMMENT(str) __ block_comment(str)
  69 #endif
  70 
  71 #define BIND(label)        __ bind(label); BLOCK_COMMENT(#label ":")
  72 
  73 //-----------------------------------------------------------------------------
  74 
  75 address TemplateInterpreterGenerator::generate_slow_signature_handler() {
  76   // Slow_signature handler that respects the PPC C calling conventions.
  77   //
  78   // We get called by the native entry code with our output register
  79   // area == 8. First we call InterpreterRuntime::get_result_handler
  80   // to copy the pointer to the signature string temporarily to the
  81   // first C-argument and to return the result_handler in
  82   // R3_RET. Since native_entry will copy the jni-pointer to the
  83   // first C-argument slot later on, it is OK to occupy this slot
  84   // temporarilly. Then we copy the argument list on the java
  85   // expression stack into native varargs format on the native stack
  86   // and load arguments into argument registers. Integer arguments in
  87   // the varargs vector will be sign-extended to 8 bytes.
  88   //
  89   // On entry:
  90   //   R3_ARG1        - intptr_t*     Address of java argument list in memory.
  91   //   R15_prev_state - BytecodeInterpreter* Address of interpreter state for
  92   //     this method
  93   //   R19_method
  94   //
  95   // On exit (just before return instruction):
  96   //   R3_RET            - contains the address of the result_handler.
  97   //   R4_ARG2           - is not updated for static methods and contains "this" otherwise.
  98   //   R5_ARG3-R10_ARG8: - When the (i-2)th Java argument is not of type float or double,
  99   //                       ARGi contains this argument. Otherwise, ARGi is not updated.
 100   //   F1_ARG1-F13_ARG13 - contain the first 13 arguments of type float or double.
 101 
 102   const int LogSizeOfTwoInstructions = 3;
 103 
 104   // FIXME: use Argument:: GL: Argument names different numbers!
 105   const int max_fp_register_arguments  = 13;
 106   const int max_int_register_arguments = 6;  // first 2 are reserved
 107 
 108   const Register arg_java       = R21_tmp1;
 109   const Register arg_c          = R22_tmp2;
 110   const Register signature      = R23_tmp3;  // is string
 111   const Register sig_byte       = R24_tmp4;
 112   const Register fpcnt          = R25_tmp5;
 113   const Register argcnt         = R26_tmp6;
 114   const Register intSlot        = R27_tmp7;
 115   const Register target_sp      = R28_tmp8;
 116   const FloatRegister floatSlot = F0;
 117 
 118   address entry = __ function_entry();
 119 
 120   __ save_LR_CR(R0);
 121   __ save_nonvolatile_gprs(R1_SP, _spill_nonvolatiles_neg(r14));
 122   // We use target_sp for storing arguments in the C frame.
 123   __ mr(target_sp, R1_SP);
 124   __ push_frame_reg_args_nonvolatiles(0, R11_scratch1);
 125 
 126   __ mr(arg_java, R3_ARG1);
 127 
 128   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_signature), R16_thread, R19_method);
 129 
 130   // Signature is in R3_RET. Signature is callee saved.
 131   __ mr(signature, R3_RET);
 132 
 133   // Get the result handler.
 134   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_result_handler), R16_thread, R19_method);
 135 
 136   {
 137     Label L;
 138     // test if static
 139     // _access_flags._flags must be at offset 0.
 140     // TODO PPC port: requires change in shared code.
 141     //assert(in_bytes(AccessFlags::flags_offset()) == 0,
 142     //       "MethodDesc._access_flags == MethodDesc._access_flags._flags");
 143     // _access_flags must be a 32 bit value.
 144     assert(sizeof(AccessFlags) == 4, "wrong size");
 145     __ lwa(R11_scratch1/*access_flags*/, method_(access_flags));
 146     // testbit with condition register.
 147     __ testbitdi(CCR0, R0, R11_scratch1/*access_flags*/, JVM_ACC_STATIC_BIT);
 148     __ btrue(CCR0, L);
 149     // For non-static functions, pass "this" in R4_ARG2 and copy it
 150     // to 2nd C-arg slot.
 151     // We need to box the Java object here, so we use arg_java
 152     // (address of current Java stack slot) as argument and don't
 153     // dereference it as in case of ints, floats, etc.
 154     __ mr(R4_ARG2, arg_java);
 155     __ addi(arg_java, arg_java, -BytesPerWord);
 156     __ std(R4_ARG2, _abi0(carg_2), target_sp);
 157     __ bind(L);
 158   }
 159 
 160   // Will be incremented directly after loop_start. argcnt=0
 161   // corresponds to 3rd C argument.
 162   __ li(argcnt, -1);
 163   // arg_c points to 3rd C argument
 164   __ addi(arg_c, target_sp, _abi0(carg_3));
 165   // no floating-point args parsed so far
 166   __ li(fpcnt, 0);
 167 
 168   Label move_intSlot_to_ARG, move_floatSlot_to_FARG;
 169   Label loop_start, loop_end;
 170   Label do_int, do_long, do_float, do_double, do_dontreachhere, do_object, do_array, do_boxed;
 171 
 172   // signature points to '(' at entry
 173 #ifdef ASSERT
 174   __ lbz(sig_byte, 0, signature);
 175   __ cmplwi(CCR0, sig_byte, '(');
 176   __ bne(CCR0, do_dontreachhere);
 177 #endif
 178 
 179   __ bind(loop_start);
 180 
 181   __ addi(argcnt, argcnt, 1);
 182   __ lbzu(sig_byte, 1, signature);
 183 
 184   __ cmplwi(CCR0, sig_byte, ')'); // end of signature
 185   __ beq(CCR0, loop_end);
 186 
 187   __ cmplwi(CCR0, sig_byte, 'B'); // byte
 188   __ beq(CCR0, do_int);
 189 
 190   __ cmplwi(CCR0, sig_byte, 'C'); // char
 191   __ beq(CCR0, do_int);
 192 
 193   __ cmplwi(CCR0, sig_byte, 'D'); // double
 194   __ beq(CCR0, do_double);
 195 
 196   __ cmplwi(CCR0, sig_byte, 'F'); // float
 197   __ beq(CCR0, do_float);
 198 
 199   __ cmplwi(CCR0, sig_byte, 'I'); // int
 200   __ beq(CCR0, do_int);
 201 
 202   __ cmplwi(CCR0, sig_byte, 'J'); // long
 203   __ beq(CCR0, do_long);
 204 
 205   __ cmplwi(CCR0, sig_byte, 'S'); // short
 206   __ beq(CCR0, do_int);
 207 
 208   __ cmplwi(CCR0, sig_byte, 'Z'); // boolean
 209   __ beq(CCR0, do_int);
 210 
 211   __ cmplwi(CCR0, sig_byte, 'L'); // object
 212   __ beq(CCR0, do_object);
 213 
 214   __ cmplwi(CCR0, sig_byte, '['); // array
 215   __ beq(CCR0, do_array);
 216 
 217   //  __ cmplwi(CCR0, sig_byte, 'V'); // void cannot appear since we do not parse the return type
 218   //  __ beq(CCR0, do_void);
 219 
 220   __ bind(do_dontreachhere);
 221 
 222   __ unimplemented("ShouldNotReachHere in slow_signature_handler");
 223 
 224   __ bind(do_array);
 225 
 226   {
 227     Label start_skip, end_skip;
 228 
 229     __ bind(start_skip);
 230     __ lbzu(sig_byte, 1, signature);
 231     __ cmplwi(CCR0, sig_byte, '[');
 232     __ beq(CCR0, start_skip); // skip further brackets
 233     __ cmplwi(CCR0, sig_byte, '9');
 234     __ bgt(CCR0, end_skip);   // no optional size
 235     __ cmplwi(CCR0, sig_byte, '0');
 236     __ bge(CCR0, start_skip); // skip optional size
 237     __ bind(end_skip);
 238 
 239     __ cmplwi(CCR0, sig_byte, 'L');
 240     __ beq(CCR0, do_object);  // for arrays of objects, the name of the object must be skipped
 241     __ b(do_boxed);          // otherwise, go directly to do_boxed
 242   }
 243 
 244   __ bind(do_object);
 245   {
 246     Label L;
 247     __ bind(L);
 248     __ lbzu(sig_byte, 1, signature);
 249     __ cmplwi(CCR0, sig_byte, ';');
 250     __ bne(CCR0, L);
 251    }
 252   // Need to box the Java object here, so we use arg_java (address of
 253   // current Java stack slot) as argument and don't dereference it as
 254   // in case of ints, floats, etc.
 255   Label do_null;
 256   __ bind(do_boxed);
 257   __ ld(R0,0, arg_java);
 258   __ cmpdi(CCR0, R0, 0);
 259   __ li(intSlot,0);
 260   __ beq(CCR0, do_null);
 261   __ mr(intSlot, arg_java);
 262   __ bind(do_null);
 263   __ std(intSlot, 0, arg_c);
 264   __ addi(arg_java, arg_java, -BytesPerWord);
 265   __ addi(arg_c, arg_c, BytesPerWord);
 266   __ cmplwi(CCR0, argcnt, max_int_register_arguments);
 267   __ blt(CCR0, move_intSlot_to_ARG);
 268   __ b(loop_start);
 269 
 270   __ bind(do_int);
 271   __ lwa(intSlot, 0, arg_java);
 272   __ std(intSlot, 0, arg_c);
 273   __ addi(arg_java, arg_java, -BytesPerWord);
 274   __ addi(arg_c, arg_c, BytesPerWord);
 275   __ cmplwi(CCR0, argcnt, max_int_register_arguments);
 276   __ blt(CCR0, move_intSlot_to_ARG);
 277   __ b(loop_start);
 278 
 279   __ bind(do_long);
 280   __ ld(intSlot, -BytesPerWord, arg_java);
 281   __ std(intSlot, 0, arg_c);
 282   __ addi(arg_java, arg_java, - 2 * BytesPerWord);
 283   __ addi(arg_c, arg_c, BytesPerWord);
 284   __ cmplwi(CCR0, argcnt, max_int_register_arguments);
 285   __ blt(CCR0, move_intSlot_to_ARG);
 286   __ b(loop_start);
 287 
 288   __ bind(do_float);
 289   __ lfs(floatSlot, 0, arg_java);
 290 #if defined(LINUX)
 291   // Linux uses ELF ABI. Both original ELF and ELFv2 ABIs have float
 292   // in the least significant word of an argument slot.
 293 #if defined(VM_LITTLE_ENDIAN)
 294   __ stfs(floatSlot, 0, arg_c);
 295 #else
 296   __ stfs(floatSlot, 4, arg_c);
 297 #endif
 298 #elif defined(AIX)
 299   // Although AIX runs on big endian CPU, float is in most significant
 300   // word of an argument slot.
 301   __ stfs(floatSlot, 0, arg_c);
 302 #else
 303 #error "unknown OS"
 304 #endif
 305   __ addi(arg_java, arg_java, -BytesPerWord);
 306   __ addi(arg_c, arg_c, BytesPerWord);
 307   __ cmplwi(CCR0, fpcnt, max_fp_register_arguments);
 308   __ blt(CCR0, move_floatSlot_to_FARG);
 309   __ b(loop_start);
 310 
 311   __ bind(do_double);
 312   __ lfd(floatSlot, - BytesPerWord, arg_java);
 313   __ stfd(floatSlot, 0, arg_c);
 314   __ addi(arg_java, arg_java, - 2 * BytesPerWord);
 315   __ addi(arg_c, arg_c, BytesPerWord);
 316   __ cmplwi(CCR0, fpcnt, max_fp_register_arguments);
 317   __ blt(CCR0, move_floatSlot_to_FARG);
 318   __ b(loop_start);
 319 
 320   __ bind(loop_end);
 321 
 322   __ pop_frame();
 323   __ restore_nonvolatile_gprs(R1_SP, _spill_nonvolatiles_neg(r14));
 324   __ restore_LR_CR(R0);
 325 
 326   __ blr();
 327 
 328   Label move_int_arg, move_float_arg;
 329   __ bind(move_int_arg); // each case must consist of 2 instructions (otherwise adapt LogSizeOfTwoInstructions)
 330   __ mr(R5_ARG3, intSlot);  __ b(loop_start);
 331   __ mr(R6_ARG4, intSlot);  __ b(loop_start);
 332   __ mr(R7_ARG5, intSlot);  __ b(loop_start);
 333   __ mr(R8_ARG6, intSlot);  __ b(loop_start);
 334   __ mr(R9_ARG7, intSlot);  __ b(loop_start);
 335   __ mr(R10_ARG8, intSlot); __ b(loop_start);
 336 
 337   __ bind(move_float_arg); // each case must consist of 2 instructions (otherwise adapt LogSizeOfTwoInstructions)
 338   __ fmr(F1_ARG1, floatSlot);   __ b(loop_start);
 339   __ fmr(F2_ARG2, floatSlot);   __ b(loop_start);
 340   __ fmr(F3_ARG3, floatSlot);   __ b(loop_start);
 341   __ fmr(F4_ARG4, floatSlot);   __ b(loop_start);
 342   __ fmr(F5_ARG5, floatSlot);   __ b(loop_start);
 343   __ fmr(F6_ARG6, floatSlot);   __ b(loop_start);
 344   __ fmr(F7_ARG7, floatSlot);   __ b(loop_start);
 345   __ fmr(F8_ARG8, floatSlot);   __ b(loop_start);
 346   __ fmr(F9_ARG9, floatSlot);   __ b(loop_start);
 347   __ fmr(F10_ARG10, floatSlot); __ b(loop_start);
 348   __ fmr(F11_ARG11, floatSlot); __ b(loop_start);
 349   __ fmr(F12_ARG12, floatSlot); __ b(loop_start);
 350   __ fmr(F13_ARG13, floatSlot); __ b(loop_start);
 351 
 352   __ bind(move_intSlot_to_ARG);
 353   __ sldi(R0, argcnt, LogSizeOfTwoInstructions);
 354   __ load_const(R11_scratch1, move_int_arg); // Label must be bound here.
 355   __ add(R11_scratch1, R0, R11_scratch1);
 356   __ mtctr(R11_scratch1/*branch_target*/);
 357   __ bctr();
 358   __ bind(move_floatSlot_to_FARG);
 359   __ sldi(R0, fpcnt, LogSizeOfTwoInstructions);
 360   __ addi(fpcnt, fpcnt, 1);
 361   __ load_const(R11_scratch1, move_float_arg); // Label must be bound here.
 362   __ add(R11_scratch1, R0, R11_scratch1);
 363   __ mtctr(R11_scratch1/*branch_target*/);
 364   __ bctr();
 365 
 366   return entry;
 367 }
 368 
 369 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 370   //
 371   // Registers alive
 372   //   R3_RET
 373   //   LR
 374   //
 375   // Registers updated
 376   //   R3_RET
 377   //
 378 
 379   Label done;
 380   address entry = __ pc();
 381 
 382   switch (type) {
 383   case T_BOOLEAN:
 384     // convert !=0 to 1
 385     __ neg(R0, R3_RET);
 386     __ orr(R0, R3_RET, R0);
 387     __ srwi(R3_RET, R0, 31);
 388     break;
 389   case T_BYTE:
 390      // sign extend 8 bits
 391      __ extsb(R3_RET, R3_RET);
 392      break;
 393   case T_CHAR:
 394      // zero extend 16 bits
 395      __ clrldi(R3_RET, R3_RET, 48);
 396      break;
 397   case T_SHORT:
 398      // sign extend 16 bits
 399      __ extsh(R3_RET, R3_RET);
 400      break;
 401   case T_INT:
 402      // sign extend 32 bits
 403      __ extsw(R3_RET, R3_RET);
 404      break;
 405   case T_LONG:
 406      break;
 407   case T_OBJECT:
 408     // JNIHandles::resolve result.
 409     __ resolve_jobject(R3_RET, R11_scratch1, R31, MacroAssembler::PRESERVATION_FRAME_LR); // kills R31
 410     break;
 411   case T_FLOAT:
 412      break;
 413   case T_DOUBLE:
 414      break;
 415   case T_VOID:
 416      break;
 417   default: ShouldNotReachHere();
 418   }
 419 
 420   BIND(done);
 421   __ blr();
 422 
 423   return entry;
 424 }
 425 
 426 // Abstract method entry.
 427 //
 428 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
 429   address entry = __ pc();
 430 
 431   //
 432   // Registers alive
 433   //   R16_thread     - JavaThread*
 434   //   R19_method     - callee's method (method to be invoked)
 435   //   R1_SP          - SP prepared such that caller's outgoing args are near top
 436   //   LR             - return address to caller
 437   //
 438   // Stack layout at this point:
 439   //
 440   //   0       [TOP_IJAVA_FRAME_ABI]         <-- R1_SP
 441   //           alignment (optional)
 442   //           [outgoing Java arguments]
 443   //           ...
 444   //   PARENT  [PARENT_IJAVA_FRAME_ABI]
 445   //            ...
 446   //
 447 
 448   // Can't use call_VM here because we have not set up a new
 449   // interpreter state. Make the call to the vm and make it look like
 450   // our caller set up the JavaFrameAnchor.
 451   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
 452 
 453   // Push a new C frame and save LR.
 454   __ save_LR_CR(R0);
 455   __ push_frame_reg_args(0, R11_scratch1);
 456 
 457   // This is not a leaf but we have a JavaFrameAnchor now and we will
 458   // check (create) exceptions afterward so this is ok.
 459   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodErrorWithMethod),
 460                   R16_thread, R19_method);
 461 
 462   // Pop the C frame and restore LR.
 463   __ pop_frame();
 464   __ restore_LR_CR(R0);
 465 
 466   // Reset JavaFrameAnchor from call_VM_leaf above.
 467   __ reset_last_Java_frame();
 468 
 469   // We don't know our caller, so jump to the general forward exception stub,
 470   // which will also pop our full frame off. Satisfy the interface of
 471   // SharedRuntime::generate_forward_exception()
 472   __ load_const_optimized(R11_scratch1, StubRoutines::forward_exception_entry(), R0);
 473   __ mtctr(R11_scratch1);
 474   __ bctr();
 475 
 476   return entry;
 477 }
 478 
 479 address TemplateInterpreterGenerator::generate_Continuation_doYield_entry(void) {
 480   Unimplemented();
 481   return NULL;
 482 }
 483 
 484 // Interpreter intrinsic for WeakReference.get().
 485 // 1. Don't push a full blown frame and go on dispatching, but fetch the value
 486 //    into R8 and return quickly
 487 // 2. If G1 is active we *must* execute this intrinsic for corrrectness:
 488 //    It contains a GC barrier which puts the reference into the satb buffer
 489 //    to indicate that someone holds a strong reference to the object the
 490 //    weak ref points to!
 491 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 492   // Code: _aload_0, _getfield, _areturn
 493   // parameter size = 1
 494   //
 495   // The code that gets generated by this routine is split into 2 parts:
 496   //    1. the "intrinsified" code for G1 (or any SATB based GC),
 497   //    2. the slow path - which is an expansion of the regular method entry.
 498   //
 499   // Notes:
 500   // * In the G1 code we do not check whether we need to block for
 501   //   a safepoint. If G1 is enabled then we must execute the specialized
 502   //   code for Reference.get (except when the Reference object is null)
 503   //   so that we can log the value in the referent field with an SATB
 504   //   update buffer.
 505   //   If the code for the getfield template is modified so that the
 506   //   G1 pre-barrier code is executed when the current method is
 507   //   Reference.get() then going through the normal method entry
 508   //   will be fine.
 509   // * The G1 code can, however, check the receiver object (the instance
 510   //   of java.lang.Reference) and jump to the slow path if null. If the
 511   //   Reference object is null then we obviously cannot fetch the referent
 512   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 513   //   regular method entry code to generate the NPE.
 514   //
 515 
 516   address entry = __ pc();
 517 
 518   const int referent_offset = java_lang_ref_Reference::referent_offset();
 519 
 520   Label slow_path;
 521 
 522   // Debugging not possible, so can't use __ skip_if_jvmti_mode(slow_path, GR31_SCRATCH);
 523 
 524   // In the G1 code we don't check if we need to reach a safepoint. We
 525   // continue and the thread will safepoint at the next bytecode dispatch.
 526 
 527   // If the receiver is null then it is OK to jump to the slow path.
 528   __ ld(R3_RET, Interpreter::stackElementSize, R15_esp); // get receiver
 529 
 530   // Check if receiver == NULL and go the slow path.
 531   __ cmpdi(CCR0, R3_RET, 0);
 532   __ beq(CCR0, slow_path);
 533 
 534   __ load_heap_oop(R3_RET, referent_offset, R3_RET,
 535                    /* non-volatile temp */ R31, R11_scratch1,
 536                    MacroAssembler::PRESERVATION_FRAME_LR,
 537                    ON_WEAK_OOP_REF);
 538 
 539   // Generate the G1 pre-barrier code to log the value of
 540   // the referent field in an SATB buffer. Note with
 541   // these parameters the pre-barrier does not generate
 542   // the load of the previous value.
 543 
 544   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
 545   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
 546 
 547   __ blr();
 548 
 549   __ bind(slow_path);
 550   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
 551   return entry;
 552 }
 553 
 554 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
 555   address entry = __ pc();
 556 
 557   // Expression stack must be empty before entering the VM if an
 558   // exception happened.
 559   __ empty_expression_stack();
 560   // Throw exception.
 561   __ call_VM(noreg,
 562              CAST_FROM_FN_PTR(address,
 563                               InterpreterRuntime::throw_StackOverflowError));
 564   return entry;
 565 }
 566 
 567 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 568   address entry = __ pc();
 569   __ empty_expression_stack();
 570   // R4_ARG2 already contains the array.
 571   // Index is in R17_tos.
 572   __ mr(R5_ARG3, R17_tos);
 573   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException), R4_ARG2, R5_ARG3);
 574   return entry;
 575 }
 576 
 577 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 578   address entry = __ pc();
 579   // Expression stack must be empty before entering the VM if an
 580   // exception happened.
 581   __ empty_expression_stack();
 582 
 583   // Load exception object.
 584   // Thread will be loaded to R3_ARG1.
 585   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException), R17_tos);
 586 #ifdef ASSERT
 587   // Above call must not return here since exception pending.
 588   __ should_not_reach_here();
 589 #endif
 590   return entry;
 591 }
 592 
 593 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 594   address entry = __ pc();
 595   //__ untested("generate_exception_handler_common");
 596   Register Rexception = R17_tos;
 597 
 598   // Expression stack must be empty before entering the VM if an exception happened.
 599   __ empty_expression_stack();
 600 
 601   __ load_const_optimized(R4_ARG2, (address) name, R11_scratch1);
 602   if (pass_oop) {
 603     __ mr(R5_ARG3, Rexception);
 604     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception));
 605   } else {
 606     __ load_const_optimized(R5_ARG3, (address) message, R11_scratch1);
 607     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception));
 608   }
 609 
 610   // Throw exception.
 611   __ mr(R3_ARG1, Rexception);
 612   __ load_const_optimized(R11_scratch1, Interpreter::throw_exception_entry(), R12_scratch2);
 613   __ mtctr(R11_scratch1);
 614   __ bctr();
 615 
 616   return entry;
 617 }
 618 
 619 // This entry is returned to when a call returns to the interpreter.
 620 // When we arrive here, we expect that the callee stack frame is already popped.
 621 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 622   address entry = __ pc();
 623 
 624   // Move the value out of the return register back to the TOS cache of current frame.
 625   switch (state) {
 626     case ltos:
 627     case btos:
 628     case ztos:
 629     case ctos:
 630     case stos:
 631     case atos:
 632     case itos: __ mr(R17_tos, R3_RET); break;   // RET -> TOS cache
 633     case ftos:
 634     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 635     case vtos: break;                           // Nothing to do, this was a void return.
 636     default  : ShouldNotReachHere();
 637   }
 638 
 639   __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
 640   __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
 641   __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
 642 
 643   // Compiled code destroys templateTableBase, reload.
 644   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
 645 
 646   if (state == atos) {
 647     __ profile_return_type(R3_RET, R11_scratch1, R12_scratch2);
 648   }
 649 
 650   const Register cache = R11_scratch1;
 651   const Register size  = R12_scratch2;
 652   __ get_cache_and_index_at_bcp(cache, 1, index_size);
 653 
 654   // Get least significant byte of 64 bit value:
 655 #if defined(VM_LITTLE_ENDIAN)
 656   __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()), cache);
 657 #else
 658   __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()) + 7, cache);
 659 #endif
 660   __ sldi(size, size, Interpreter::logStackElementSize);
 661   __ add(R15_esp, R15_esp, size);
 662 
 663  __ check_and_handle_popframe(R11_scratch1);
 664  __ check_and_handle_earlyret(R11_scratch1);
 665 
 666   __ dispatch_next(state, step);
 667   return entry;
 668 }
 669 
 670 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step, address continuation) {
 671   address entry = __ pc();
 672   // If state != vtos, we're returning from a native method, which put it's result
 673   // into the result register. So move the value out of the return register back
 674   // to the TOS cache of current frame.
 675 
 676   switch (state) {
 677     case ltos:
 678     case btos:
 679     case ztos:
 680     case ctos:
 681     case stos:
 682     case atos:
 683     case itos: __ mr(R17_tos, R3_RET); break;   // GR_RET -> TOS cache
 684     case ftos:
 685     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 686     case vtos: break;                           // Nothing to do, this was a void return.
 687     default  : ShouldNotReachHere();
 688   }
 689 
 690   // Load LcpoolCache @@@ should be already set!
 691   __ get_constant_pool_cache(R27_constPoolCache);
 692 
 693   // Handle a pending exception, fall through if none.
 694   __ check_and_forward_exception(R11_scratch1, R12_scratch2);
 695 
 696   // Start executing bytecodes.
 697   if (continuation == NULL) {
 698     __ dispatch_next(state, step);
 699   } else {
 700     __ jump_to_entry(continuation, R11_scratch1);
 701   }
 702 
 703   return entry;
 704 }
 705 
 706 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 707   address entry = __ pc();
 708 
 709   __ push(state);
 710   __ call_VM(noreg, runtime_entry);
 711   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 712 
 713   return entry;
 714 }
 715 
 716 // Helpers for commoning out cases in the various type of method entries.
 717 
 718 // Increment invocation count & check for overflow.
 719 //
 720 // Note: checking for negative value instead of overflow
 721 //       so we have a 'sticky' overflow test.
 722 //
 723 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 724   // Note: In tiered we increment either counters in method or in MDO depending if we're profiling or not.
 725   Register Rscratch1   = R11_scratch1;
 726   Register Rscratch2   = R12_scratch2;
 727   Register R3_counters = R3_ARG1;
 728   Label done;
 729 
 730   const int increment = InvocationCounter::count_increment;
 731   Label no_mdo;
 732   if (ProfileInterpreter) {
 733     const Register Rmdo = R3_counters;
 734     __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
 735     __ cmpdi(CCR0, Rmdo, 0);
 736     __ beq(CCR0, no_mdo);
 737 
 738     // Increment invocation counter in the MDO.
 739     const int mdo_ic_offs = in_bytes(MethodData::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 740     __ lwz(Rscratch2, mdo_ic_offs, Rmdo);
 741     __ lwz(Rscratch1, in_bytes(MethodData::invoke_mask_offset()), Rmdo);
 742     __ addi(Rscratch2, Rscratch2, increment);
 743     __ stw(Rscratch2, mdo_ic_offs, Rmdo);
 744     __ and_(Rscratch1, Rscratch2, Rscratch1);
 745     __ bne(CCR0, done);
 746     __ b(*overflow);
 747   }
 748 
 749   // Increment counter in MethodCounters*.
 750   const int mo_ic_offs = in_bytes(MethodCounters::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 751   __ bind(no_mdo);
 752   __ get_method_counters(R19_method, R3_counters, done);
 753   __ lwz(Rscratch2, mo_ic_offs, R3_counters);
 754   __ lwz(Rscratch1, in_bytes(MethodCounters::invoke_mask_offset()), R3_counters);
 755   __ addi(Rscratch2, Rscratch2, increment);
 756   __ stw(Rscratch2, mo_ic_offs, R3_counters);
 757   __ and_(Rscratch1, Rscratch2, Rscratch1);
 758   __ beq(CCR0, *overflow);
 759 
 760   __ bind(done);
 761 }
 762 
 763 // Generate code to initiate compilation on invocation counter overflow.
 764 void TemplateInterpreterGenerator::generate_counter_overflow(Label& continue_entry) {
 765   // Generate code to initiate compilation on the counter overflow.
 766 
 767   // InterpreterRuntime::frequency_counter_overflow takes one arguments,
 768   // which indicates if the counter overflow occurs at a backwards branch (NULL bcp)
 769   // We pass zero in.
 770   // The call returns the address of the verified entry point for the method or NULL
 771   // if the compilation did not complete (either went background or bailed out).
 772   //
 773   // Unlike the C++ interpreter above: Check exceptions!
 774   // Assumption: Caller must set the flag "do_not_unlock_if_sychronized" if the monitor of a sync'ed
 775   // method has not yet been created. Thus, no unlocking of a non-existing monitor can occur.
 776 
 777   __ li(R4_ARG2, 0);
 778   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
 779 
 780   // Returns verified_entry_point or NULL.
 781   // We ignore it in any case.
 782   __ b(continue_entry);
 783 }
 784 
 785 // See if we've got enough room on the stack for locals plus overhead below
 786 // JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 787 // without going through the signal handler, i.e., reserved and yellow zones
 788 // will not be made usable. The shadow zone must suffice to handle the
 789 // overflow.
 790 //
 791 // Kills Rmem_frame_size, Rscratch1.
 792 void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rmem_frame_size, Register Rscratch1) {
 793   Label done;
 794   assert_different_registers(Rmem_frame_size, Rscratch1);
 795 
 796   BLOCK_COMMENT("stack_overflow_check_with_compare {");
 797   __ sub(Rmem_frame_size, R1_SP, Rmem_frame_size);
 798   __ ld(Rscratch1, thread_(stack_overflow_limit));
 799   __ cmpld(CCR0/*is_stack_overflow*/, Rmem_frame_size, Rscratch1);
 800   __ bgt(CCR0/*is_stack_overflow*/, done);
 801 
 802   // The stack overflows. Load target address of the runtime stub and call it.
 803   assert(StubRoutines::throw_StackOverflowError_entry() != NULL, "generated in wrong order");
 804   __ load_const_optimized(Rscratch1, (StubRoutines::throw_StackOverflowError_entry()), R0);
 805   __ mtctr(Rscratch1);
 806   // Restore caller_sp (c2i adapter may exist, but no shrinking of interpreted caller frame).
 807 #ifdef ASSERT
 808   Label frame_not_shrunk;
 809   __ cmpld(CCR0, R1_SP, R21_sender_SP);
 810   __ ble(CCR0, frame_not_shrunk);
 811   __ stop("frame shrunk");
 812   __ bind(frame_not_shrunk);
 813   __ ld(Rscratch1, 0, R1_SP);
 814   __ ld(R0, 0, R21_sender_SP);
 815   __ cmpd(CCR0, R0, Rscratch1);
 816   __ asm_assert_eq("backlink");
 817 #endif // ASSERT
 818   __ mr(R1_SP, R21_sender_SP);
 819   __ bctr();
 820 
 821   __ align(32, 12);
 822   __ bind(done);
 823   BLOCK_COMMENT("} stack_overflow_check_with_compare");
 824 }
 825 
 826 // Lock the current method, interpreter register window must be set up!
 827 void TemplateInterpreterGenerator::lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded) {
 828   const Register Robj_to_lock = Rscratch2;
 829 
 830   {
 831     if (!flags_preloaded) {
 832       __ lwz(Rflags, method_(access_flags));
 833     }
 834 
 835 #ifdef ASSERT
 836     // Check if methods needs synchronization.
 837     {
 838       Label Lok;
 839       __ testbitdi(CCR0, R0, Rflags, JVM_ACC_SYNCHRONIZED_BIT);
 840       __ btrue(CCR0,Lok);
 841       __ stop("method doesn't need synchronization");
 842       __ bind(Lok);
 843     }
 844 #endif // ASSERT
 845   }
 846 
 847   // Get synchronization object to Rscratch2.
 848   {
 849     Label Lstatic;
 850     Label Ldone;
 851 
 852     __ testbitdi(CCR0, R0, Rflags, JVM_ACC_STATIC_BIT);
 853     __ btrue(CCR0, Lstatic);
 854 
 855     // Non-static case: load receiver obj from stack and we're done.
 856     __ ld(Robj_to_lock, R18_locals);
 857     __ b(Ldone);
 858 
 859     __ bind(Lstatic); // Static case: Lock the java mirror
 860     // Load mirror from interpreter frame.
 861     __ ld(Robj_to_lock, _abi0(callers_sp), R1_SP);
 862     __ ld(Robj_to_lock, _ijava_state_neg(mirror), Robj_to_lock);
 863 
 864     __ bind(Ldone);
 865     __ verify_oop(Robj_to_lock);
 866   }
 867 
 868   // Got the oop to lock => execute!
 869   __ add_monitor_to_stack(true, Rscratch1, R0);
 870 
 871   __ std(Robj_to_lock, BasicObjectLock::obj_offset_in_bytes(), R26_monitor);
 872   __ lock_object(R26_monitor, Robj_to_lock);
 873 }
 874 
 875 // Generate a fixed interpreter frame for pure interpreter
 876 // and I2N native transition frames.
 877 //
 878 // Before (stack grows downwards):
 879 //
 880 //         |  ...         |
 881 //         |------------- |
 882 //         |  java arg0   |
 883 //         |  ...         |
 884 //         |  java argn   |
 885 //         |              |   <-   R15_esp
 886 //         |              |
 887 //         |--------------|
 888 //         | abi_112      |
 889 //         |              |   <-   R1_SP
 890 //         |==============|
 891 //
 892 //
 893 // After:
 894 //
 895 //         |  ...         |
 896 //         |  java arg0   |<-   R18_locals
 897 //         |  ...         |
 898 //         |  java argn   |
 899 //         |--------------|
 900 //         |              |
 901 //         |  java locals |
 902 //         |              |
 903 //         |--------------|
 904 //         |  abi_48      |
 905 //         |==============|
 906 //         |              |
 907 //         |   istate     |
 908 //         |              |
 909 //         |--------------|
 910 //         |   monitor    |<-   R26_monitor
 911 //         |--------------|
 912 //         |              |<-   R15_esp
 913 //         | expression   |
 914 //         | stack        |
 915 //         |              |
 916 //         |--------------|
 917 //         |              |
 918 //         | abi_112      |<-   R1_SP
 919 //         |==============|
 920 //
 921 // The top most frame needs an abi space of 112 bytes. This space is needed,
 922 // since we call to c. The c function may spill their arguments to the caller
 923 // frame. When we call to java, we don't need these spill slots. In order to save
 924 // space on the stack, we resize the caller. However, java locals reside in
 925 // the caller frame and the frame has to be increased. The frame_size for the
 926 // current frame was calculated based on max_stack as size for the expression
 927 // stack. At the call, just a part of the expression stack might be used.
 928 // We don't want to waste this space and cut the frame back accordingly.
 929 // The resulting amount for resizing is calculated as follows:
 930 // resize =   (number_of_locals - number_of_arguments) * slot_size
 931 //          + (R1_SP - R15_esp) + 48
 932 //
 933 // The size for the callee frame is calculated:
 934 // framesize = 112 + max_stack + monitor + state_size
 935 //
 936 // maxstack:   Max number of slots on the expression stack, loaded from the method.
 937 // monitor:    We statically reserve room for one monitor object.
 938 // state_size: We save the current state of the interpreter to this area.
 939 //
 940 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals) {
 941   Register Rparent_frame_resize = R6_ARG4, // Frame will grow by this number of bytes.
 942            Rtop_frame_size      = R7_ARG5,
 943            Rconst_method        = R8_ARG6,
 944            Rconst_pool          = R9_ARG7,
 945            Rmirror              = R10_ARG8;
 946 
 947   assert_different_registers(Rsize_of_parameters, Rsize_of_locals, Rparent_frame_resize, Rtop_frame_size,
 948                              Rconst_method, Rconst_pool);
 949 
 950   __ ld(Rconst_method, method_(const));
 951   __ lhz(Rsize_of_parameters /* number of params */,
 952          in_bytes(ConstMethod::size_of_parameters_offset()), Rconst_method);
 953   if (native_call) {
 954     // If we're calling a native method, we reserve space for the worst-case signature
 955     // handler varargs vector, which is max(Argument::n_register_parameters, parameter_count+2).
 956     // We add two slots to the parameter_count, one for the jni
 957     // environment and one for a possible native mirror.
 958     Label skip_native_calculate_max_stack;
 959     __ addi(Rtop_frame_size, Rsize_of_parameters, 2);
 960     __ cmpwi(CCR0, Rtop_frame_size, Argument::n_register_parameters);
 961     __ bge(CCR0, skip_native_calculate_max_stack);
 962     __ li(Rtop_frame_size, Argument::n_register_parameters);
 963     __ bind(skip_native_calculate_max_stack);
 964     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 965     __ sldi(Rtop_frame_size, Rtop_frame_size, Interpreter::logStackElementSize);
 966     __ sub(Rparent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 967     assert(Rsize_of_locals == noreg, "Rsize_of_locals not initialized"); // Only relevant value is Rsize_of_parameters.
 968   } else {
 969     __ lhz(Rsize_of_locals /* number of params */, in_bytes(ConstMethod::size_of_locals_offset()), Rconst_method);
 970     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 971     __ sldi(Rsize_of_locals, Rsize_of_locals, Interpreter::logStackElementSize);
 972     __ lhz(Rtop_frame_size, in_bytes(ConstMethod::max_stack_offset()), Rconst_method);
 973     __ sub(R11_scratch1, Rsize_of_locals, Rsize_of_parameters); // >=0
 974     __ sub(Rparent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 975     __ sldi(Rtop_frame_size, Rtop_frame_size, Interpreter::logStackElementSize);
 976     __ add(Rparent_frame_resize, Rparent_frame_resize, R11_scratch1);
 977   }
 978 
 979   // Compute top frame size.
 980   __ addi(Rtop_frame_size, Rtop_frame_size, frame::abi_reg_args_size + frame::ijava_state_size);
 981 
 982   // Cut back area between esp and max_stack.
 983   __ addi(Rparent_frame_resize, Rparent_frame_resize, frame::abi_minframe_size - Interpreter::stackElementSize);
 984 
 985   __ round_to(Rtop_frame_size, frame::alignment_in_bytes);
 986   __ round_to(Rparent_frame_resize, frame::alignment_in_bytes);
 987   // Rparent_frame_resize = (locals-parameters) - (ESP-SP-ABI48) Rounded to frame alignment size.
 988   // Enlarge by locals-parameters (not in case of native_call), shrink by ESP-SP-ABI48.
 989 
 990   if (!native_call) {
 991     // Stack overflow check.
 992     // Native calls don't need the stack size check since they have no
 993     // expression stack and the arguments are already on the stack and
 994     // we only add a handful of words to the stack.
 995     __ add(R11_scratch1, Rparent_frame_resize, Rtop_frame_size);
 996     generate_stack_overflow_check(R11_scratch1, R12_scratch2);
 997   }
 998 
 999   // Set up interpreter state registers.
1000 
1001   __ add(R18_locals, R15_esp, Rsize_of_parameters);
1002   __ ld(Rconst_pool, in_bytes(ConstMethod::constants_offset()), Rconst_method);
1003   __ ld(R27_constPoolCache, ConstantPool::cache_offset_in_bytes(), Rconst_pool);
1004 
1005   // Set method data pointer.
1006   if (ProfileInterpreter) {
1007     Label zero_continue;
1008     __ ld(R28_mdx, method_(method_data));
1009     __ cmpdi(CCR0, R28_mdx, 0);
1010     __ beq(CCR0, zero_continue);
1011     __ addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
1012     __ bind(zero_continue);
1013   }
1014 
1015   if (native_call) {
1016     __ li(R14_bcp, 0); // Must initialize.
1017   } else {
1018     __ add(R14_bcp, in_bytes(ConstMethod::codes_offset()), Rconst_method);
1019   }
1020 
1021   // Resize parent frame.
1022   __ mflr(R12_scratch2);
1023   __ neg(Rparent_frame_resize, Rparent_frame_resize);
1024   __ resize_frame(Rparent_frame_resize, R11_scratch1);
1025   __ std(R12_scratch2, _abi0(lr), R1_SP);
1026 
1027   // Get mirror and store it in the frame as GC root for this Method*.
1028   __ ld(Rmirror, ConstantPool::pool_holder_offset_in_bytes(), Rconst_pool);
1029   __ ld(Rmirror, in_bytes(Klass::java_mirror_offset()), Rmirror);
1030   __ resolve_oop_handle(Rmirror, R11_scratch1, R12_scratch2, MacroAssembler::PRESERVATION_FRAME_LR_GP_REGS);
1031 
1032   __ addi(R26_monitor, R1_SP, -frame::ijava_state_size);
1033   __ addi(R15_esp, R26_monitor, -Interpreter::stackElementSize);
1034 
1035   // Store values.
1036   __ std(R19_method, _ijava_state_neg(method), R1_SP);
1037   __ std(Rmirror, _ijava_state_neg(mirror), R1_SP);
1038   __ std(R18_locals, _ijava_state_neg(locals), R1_SP);
1039   __ std(R27_constPoolCache, _ijava_state_neg(cpoolCache), R1_SP);
1040 
1041   // Note: esp, bcp, monitor, mdx live in registers. Hence, the correct version can only
1042   // be found in the frame after save_interpreter_state is done. This is always true
1043   // for non-top frames. But when a signal occurs, dumping the top frame can go wrong,
1044   // because e.g. frame::interpreter_frame_bcp() will not access the correct value
1045   // (Enhanced Stack Trace).
1046   // The signal handler does not save the interpreter state into the frame.
1047 
1048   // We have to initialize some of these frame slots for native calls (accessed by GC).
1049   // Also initialize them for non-native calls for better tool support (even though
1050   // you may not get the most recent version as described above).
1051   __ li(R0, 0);
1052   __ std(R26_monitor, _ijava_state_neg(monitors), R1_SP);
1053   __ std(R14_bcp, _ijava_state_neg(bcp), R1_SP);
1054   if (ProfileInterpreter) { __ std(R28_mdx, _ijava_state_neg(mdx), R1_SP); }
1055   __ std(R15_esp, _ijava_state_neg(esp), R1_SP);
1056   __ std(R0, _ijava_state_neg(oop_tmp), R1_SP); // only used for native_call
1057 
1058   // Store sender's SP and this frame's top SP.
1059   __ subf(R12_scratch2, Rtop_frame_size, R1_SP);
1060   __ std(R21_sender_SP, _ijava_state_neg(sender_sp), R1_SP);
1061   __ std(R12_scratch2, _ijava_state_neg(top_frame_sp), R1_SP);
1062 
1063   // Push top frame.
1064   __ push_frame(Rtop_frame_size, R11_scratch1);
1065 }
1066 
1067 // End of helpers
1068 
1069 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
1070 
1071   // Decide what to do: Use same platform specific instructions and runtime calls as compilers.
1072   bool use_instruction = false;
1073   address runtime_entry = NULL;
1074   int num_args = 1;
1075   bool double_precision = true;
1076 
1077   // PPC64 specific:
1078   switch (kind) {
1079     case Interpreter::java_lang_math_sqrt: use_instruction = VM_Version::has_fsqrt(); break;
1080     case Interpreter::java_lang_math_abs:  use_instruction = true; break;
1081     case Interpreter::java_lang_math_fmaF:
1082     case Interpreter::java_lang_math_fmaD: use_instruction = UseFMA; break;
1083     default: break; // Fall back to runtime call.
1084   }
1085 
1086   switch (kind) {
1087     case Interpreter::java_lang_math_sin  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);   break;
1088     case Interpreter::java_lang_math_cos  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);   break;
1089     case Interpreter::java_lang_math_tan  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);   break;
1090     case Interpreter::java_lang_math_abs  : /* run interpreted */ break;
1091     case Interpreter::java_lang_math_sqrt : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsqrt);  break;
1092     case Interpreter::java_lang_math_log  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);   break;
1093     case Interpreter::java_lang_math_log10: runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10); break;
1094     case Interpreter::java_lang_math_pow  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dpow); num_args = 2; break;
1095     case Interpreter::java_lang_math_exp  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);   break;
1096     case Interpreter::java_lang_math_fmaF : /* run interpreted */ num_args = 3; double_precision = false; break;
1097     case Interpreter::java_lang_math_fmaD : /* run interpreted */ num_args = 3; break;
1098     default: ShouldNotReachHere();
1099   }
1100 
1101   // Use normal entry if neither instruction nor runtime call is used.
1102   if (!use_instruction && runtime_entry == NULL) return NULL;
1103 
1104   address entry = __ pc();
1105 
1106   // Load arguments
1107   assert(num_args <= 13, "passed in registers");
1108   if (double_precision) {
1109     int offset = (2 * num_args - 1) * Interpreter::stackElementSize;
1110     for (int i = 0; i < num_args; ++i) {
1111       __ lfd(as_FloatRegister(F1_ARG1->encoding() + i), offset, R15_esp);
1112       offset -= 2 * Interpreter::stackElementSize;
1113     }
1114   } else {
1115     int offset = num_args * Interpreter::stackElementSize;
1116     for (int i = 0; i < num_args; ++i) {
1117       __ lfs(as_FloatRegister(F1_ARG1->encoding() + i), offset, R15_esp);
1118       offset -= Interpreter::stackElementSize;
1119     }
1120   }
1121 
1122   if (use_instruction) {
1123     switch (kind) {
1124       case Interpreter::java_lang_math_sqrt: __ fsqrt(F1_RET, F1);          break;
1125       case Interpreter::java_lang_math_abs:  __ fabs(F1_RET, F1);           break;
1126       case Interpreter::java_lang_math_fmaF: __ fmadds(F1_RET, F1, F2, F3); break;
1127       case Interpreter::java_lang_math_fmaD: __ fmadd(F1_RET, F1, F2, F3);  break;
1128       default: ShouldNotReachHere();
1129     }
1130   } else {
1131     // Comment: Can use tail call if the unextended frame is always C ABI compliant:
1132     //__ load_const_optimized(R12_scratch2, runtime_entry, R0);
1133     //__ call_c_and_return_to_caller(R12_scratch2);
1134 
1135     // Push a new C frame and save LR.
1136     __ save_LR_CR(R0);
1137     __ push_frame_reg_args(0, R11_scratch1);
1138 
1139     __ call_VM_leaf(runtime_entry);
1140 
1141     // Pop the C frame and restore LR.
1142     __ pop_frame();
1143     __ restore_LR_CR(R0);
1144   }
1145 
1146   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1147   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1148   __ blr();
1149 
1150   __ flush();
1151 
1152   return entry;
1153 }
1154 
1155 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1156   // Quick & dirty stack overflow checking: bang the stack & handle trap.
1157   // Note that we do the banging after the frame is setup, since the exception
1158   // handling code expects to find a valid interpreter frame on the stack.
1159   // Doing the banging earlier fails if the caller frame is not an interpreter
1160   // frame.
1161   // (Also, the exception throwing code expects to unlock any synchronized
1162   // method receiever, so do the banging after locking the receiver.)
1163 
1164   // Bang each page in the shadow zone. We can't assume it's been done for
1165   // an interpreter frame with greater than a page of locals, so each page
1166   // needs to be checked.  Only true for non-native.
1167   const int page_size = os::vm_page_size();
1168   const int n_shadow_pages = ((int)StackOverflow::stack_shadow_zone_size()) / page_size;
1169   const int start_page = native_call ? n_shadow_pages : 1;
1170   BLOCK_COMMENT("bang_stack_shadow_pages:");
1171   for (int pages = start_page; pages <= n_shadow_pages; pages++) {
1172     __ bang_stack_with_offset(pages*page_size);
1173   }
1174 }
1175 
1176 // Interpreter stub for calling a native method. (asm interpreter)
1177 // This sets up a somewhat different looking stack for calling the
1178 // native method than the typical interpreter frame setup.
1179 //
1180 // On entry:
1181 //   R19_method    - method
1182 //   R16_thread    - JavaThread*
1183 //   R15_esp       - intptr_t* sender tos
1184 //
1185 //   abstract stack (grows up)
1186 //     [  IJava (caller of JNI callee)  ]  <-- ASP
1187 //        ...
1188 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1189 
1190   address entry = __ pc();
1191 
1192   const bool inc_counter = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1193 
1194   // -----------------------------------------------------------------------------
1195   // Allocate a new frame that represents the native callee (i2n frame).
1196   // This is not a full-blown interpreter frame, but in particular, the
1197   // following registers are valid after this:
1198   // - R19_method
1199   // - R18_local (points to start of arguments to native function)
1200   //
1201   //   abstract stack (grows up)
1202   //     [  IJava (caller of JNI callee)  ]  <-- ASP
1203   //        ...
1204 
1205   const Register signature_handler_fd = R11_scratch1;
1206   const Register pending_exception    = R0;
1207   const Register result_handler_addr  = R31;
1208   const Register native_method_fd     = R11_scratch1;
1209   const Register access_flags         = R22_tmp2;
1210   const Register active_handles       = R11_scratch1; // R26_monitor saved to state.
1211   const Register sync_state           = R12_scratch2;
1212   const Register sync_state_addr      = sync_state;   // Address is dead after use.
1213   const Register suspend_flags        = R11_scratch1;
1214 
1215   //=============================================================================
1216   // Allocate new frame and initialize interpreter state.
1217 
1218   Label exception_return;
1219   Label exception_return_sync_check;
1220   Label stack_overflow_return;
1221 
1222   // Generate new interpreter state and jump to stack_overflow_return in case of
1223   // a stack overflow.
1224   //generate_compute_interpreter_state(stack_overflow_return);
1225 
1226   Register size_of_parameters = R22_tmp2;
1227 
1228   generate_fixed_frame(true, size_of_parameters, noreg /* unused */);
1229 
1230   //=============================================================================
1231   // Increment invocation counter. On overflow, entry to JNI method
1232   // will be compiled.
1233   Label invocation_counter_overflow, continue_after_compile;
1234   if (inc_counter) {
1235     if (synchronized) {
1236       // Since at this point in the method invocation the exception handler
1237       // would try to exit the monitor of synchronized methods which hasn't
1238       // been entered yet, we set the thread local variable
1239       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1240       // runtime, exception handling i.e. unlock_if_synchronized_method will
1241       // check this thread local flag.
1242       // This flag has two effects, one is to force an unwind in the topmost
1243       // interpreter frame and not perform an unlock while doing so.
1244       __ li(R0, 1);
1245       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1246     }
1247     generate_counter_incr(&invocation_counter_overflow);
1248 
1249     BIND(continue_after_compile);
1250   }
1251 
1252   bang_stack_shadow_pages(true);
1253 
1254   if (inc_counter) {
1255     // Reset the _do_not_unlock_if_synchronized flag.
1256     if (synchronized) {
1257       __ li(R0, 0);
1258       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1259     }
1260   }
1261 
1262   // access_flags = method->access_flags();
1263   // Load access flags.
1264   assert(access_flags->is_nonvolatile(),
1265          "access_flags must be in a non-volatile register");
1266   // Type check.
1267   assert(4 == sizeof(AccessFlags), "unexpected field size");
1268   __ lwz(access_flags, method_(access_flags));
1269 
1270   // We don't want to reload R19_method and access_flags after calls
1271   // to some helper functions.
1272   assert(R19_method->is_nonvolatile(),
1273          "R19_method must be a non-volatile register");
1274 
1275   // Check for synchronized methods. Must happen AFTER invocation counter
1276   // check, so method is not locked if counter overflows.
1277 
1278   if (synchronized) {
1279     lock_method(access_flags, R11_scratch1, R12_scratch2, true);
1280 
1281     // Update monitor in state.
1282     __ ld(R11_scratch1, 0, R1_SP);
1283     __ std(R26_monitor, _ijava_state_neg(monitors), R11_scratch1);
1284   }
1285 
1286   // jvmti/jvmpi support
1287   __ notify_method_entry();
1288 
1289   //=============================================================================
1290   // Get and call the signature handler.
1291 
1292   __ ld(signature_handler_fd, method_(signature_handler));
1293   Label call_signature_handler;
1294 
1295   __ cmpdi(CCR0, signature_handler_fd, 0);
1296   __ bne(CCR0, call_signature_handler);
1297 
1298   // Method has never been called. Either generate a specialized
1299   // handler or point to the slow one.
1300   //
1301   // Pass parameter 'false' to avoid exception check in call_VM.
1302   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), R19_method, false);
1303 
1304   // Check for an exception while looking up the target method. If we
1305   // incurred one, bail.
1306   __ ld(pending_exception, thread_(pending_exception));
1307   __ cmpdi(CCR0, pending_exception, 0);
1308   __ bne(CCR0, exception_return_sync_check); // Has pending exception.
1309 
1310   // Reload signature handler, it may have been created/assigned in the meanwhile.
1311   __ ld(signature_handler_fd, method_(signature_handler));
1312   __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
1313 
1314   BIND(call_signature_handler);
1315 
1316   // Before we call the signature handler we push a new frame to
1317   // protect the interpreter frame volatile registers when we return
1318   // from jni but before we can get back to Java.
1319 
1320   // First set the frame anchor while the SP/FP registers are
1321   // convenient and the slow signature handler can use this same frame
1322   // anchor.
1323 
1324   // We have a TOP_IJAVA_FRAME here, which belongs to us.
1325   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
1326 
1327   // Now the interpreter frame (and its call chain) have been
1328   // invalidated and flushed. We are now protected against eager
1329   // being enabled in native code. Even if it goes eager the
1330   // registers will be reloaded as clean and we will invalidate after
1331   // the call so no spurious flush should be possible.
1332 
1333   // Call signature handler and pass locals address.
1334   //
1335   // Our signature handlers copy required arguments to the C stack
1336   // (outgoing C args), R3_ARG1 to R10_ARG8, and FARG1 to FARG13.
1337   __ mr(R3_ARG1, R18_locals);
1338 #if !defined(ABI_ELFv2)
1339   __ ld(signature_handler_fd, 0, signature_handler_fd);
1340 #endif
1341 
1342   __ call_stub(signature_handler_fd);
1343 
1344   // Remove the register parameter varargs slots we allocated in
1345   // compute_interpreter_state. SP+16 ends up pointing to the ABI
1346   // outgoing argument area.
1347   //
1348   // Not needed on PPC64.
1349   //__ add(SP, SP, Argument::n_register_parameters*BytesPerWord);
1350 
1351   assert(result_handler_addr->is_nonvolatile(), "result_handler_addr must be in a non-volatile register");
1352   // Save across call to native method.
1353   __ mr(result_handler_addr, R3_RET);
1354 
1355   __ isync(); // Acquire signature handler before trying to fetch the native entry point and klass mirror.
1356 
1357   // Set up fixed parameters and call the native method.
1358   // If the method is static, get mirror into R4_ARG2.
1359   {
1360     Label method_is_not_static;
1361     // Access_flags is non-volatile and still, no need to restore it.
1362 
1363     // Restore access flags.
1364     __ testbitdi(CCR0, R0, access_flags, JVM_ACC_STATIC_BIT);
1365     __ bfalse(CCR0, method_is_not_static);
1366 
1367     __ ld(R11_scratch1, _abi0(callers_sp), R1_SP);
1368     // Load mirror from interpreter frame.
1369     __ ld(R12_scratch2, _ijava_state_neg(mirror), R11_scratch1);
1370     // R4_ARG2 = &state->_oop_temp;
1371     __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
1372     __ std(R12_scratch2/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
1373     BIND(method_is_not_static);
1374   }
1375 
1376   // At this point, arguments have been copied off the stack into
1377   // their JNI positions. Oops are boxed in-place on the stack, with
1378   // handles copied to arguments. The result handler address is in a
1379   // register.
1380 
1381   // Pass JNIEnv address as first parameter.
1382   __ addir(R3_ARG1, thread_(jni_environment));
1383 
1384   // Load the native_method entry before we change the thread state.
1385   __ ld(native_method_fd, method_(native_function));
1386 
1387   //=============================================================================
1388   // Transition from _thread_in_Java to _thread_in_native. As soon as
1389   // we make this change the safepoint code needs to be certain that
1390   // the last Java frame we established is good. The pc in that frame
1391   // just needs to be near here not an actual return address.
1392 
1393   // We use release_store_fence to update values like the thread state, where
1394   // we don't want the current thread to continue until all our prior memory
1395   // accesses (including the new thread state) are visible to other threads.
1396   __ li(R0, _thread_in_native);
1397   __ release();
1398 
1399   // TODO PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
1400   __ stw(R0, thread_(thread_state));
1401 
1402   //=============================================================================
1403   // Call the native method. Argument registers must not have been
1404   // overwritten since "__ call_stub(signature_handler);" (except for
1405   // ARG1 and ARG2 for static methods).
1406   __ call_c(native_method_fd);
1407 
1408   __ li(R0, 0);
1409   __ ld(R11_scratch1, 0, R1_SP);
1410   __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1411   __ stfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1412   __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1); // reset
1413 
1414   // Note: C++ interpreter needs the following here:
1415   // The frame_manager_lr field, which we use for setting the last
1416   // java frame, gets overwritten by the signature handler. Restore
1417   // it now.
1418   //__ get_PC_trash_LR(R11_scratch1);
1419   //__ std(R11_scratch1, _top_ijava_frame_abi(frame_manager_lr), R1_SP);
1420 
1421   // Because of GC R19_method may no longer be valid.
1422 
1423   // Block, if necessary, before resuming in _thread_in_Java state.
1424   // In order for GC to work, don't clear the last_Java_sp until after
1425   // blocking.
1426 
1427   //=============================================================================
1428   // Switch thread to "native transition" state before reading the
1429   // synchronization state. This additional state is necessary
1430   // because reading and testing the synchronization state is not
1431   // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
1432   // in _thread_in_native state, loads _not_synchronized and is
1433   // preempted. VM thread changes sync state to synchronizing and
1434   // suspends threads for GC. Thread A is resumed to finish this
1435   // native method, but doesn't block here since it didn't see any
1436   // synchronization in progress, and escapes.
1437 
1438   // We use release_store_fence to update values like the thread state, where
1439   // we don't want the current thread to continue until all our prior memory
1440   // accesses (including the new thread state) are visible to other threads.
1441   __ li(R0/*thread_state*/, _thread_in_native_trans);
1442   __ release();
1443   __ stw(R0/*thread_state*/, thread_(thread_state));
1444   __ fence();
1445 
1446   // Now before we return to java we must look for a current safepoint
1447   // (a new safepoint can not start since we entered native_trans).
1448   // We must check here because a current safepoint could be modifying
1449   // the callers registers right this moment.
1450 
1451   // Acquire isn't strictly necessary here because of the fence, but
1452   // sync_state is declared to be volatile, so we do it anyway
1453   // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
1454 
1455   Label do_safepoint, sync_check_done;
1456   // No synchronization in progress nor yet synchronized.
1457   __ safepoint_poll(do_safepoint, sync_state, true /* at_return */, false /* in_nmethod */);
1458 
1459   // Not suspended.
1460   // TODO PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
1461   __ lwz(suspend_flags, thread_(suspend_flags));
1462   __ cmpwi(CCR1, suspend_flags, 0);
1463   __ beq(CCR1, sync_check_done);
1464 
1465   __ bind(do_safepoint);
1466   __ isync();
1467   // Block. We do the call directly and leave the current
1468   // last_Java_frame setup undisturbed. We must save any possible
1469   // native result across the call. No oop is present.
1470 
1471   __ mr(R3_ARG1, R16_thread);
1472 #if defined(ABI_ELFv2)
1473   __ call_c(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans),
1474             relocInfo::none);
1475 #else
1476   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, JavaThread::check_special_condition_for_native_trans),
1477             relocInfo::none);
1478 #endif
1479 
1480   __ bind(sync_check_done);
1481 
1482   //=============================================================================
1483   // <<<<<< Back in Interpreter Frame >>>>>
1484 
1485   // We are in thread_in_native_trans here and back in the normal
1486   // interpreter frame. We don't have to do anything special about
1487   // safepoints and we can switch to Java mode anytime we are ready.
1488 
1489   // Note: frame::interpreter_frame_result has a dependency on how the
1490   // method result is saved across the call to post_method_exit. For
1491   // native methods it assumes that the non-FPU/non-void result is
1492   // saved in _native_lresult and a FPU result in _native_fresult. If
1493   // this changes then the interpreter_frame_result implementation
1494   // will need to be updated too.
1495 
1496   // On PPC64, we have stored the result directly after the native call.
1497 
1498   //=============================================================================
1499   // Back in Java
1500 
1501   // We use release_store_fence to update values like the thread state, where
1502   // we don't want the current thread to continue until all our prior memory
1503   // accesses (including the new thread state) are visible to other threads.
1504   __ li(R0/*thread_state*/, _thread_in_Java);
1505   __ lwsync(); // Acquire safepoint and suspend state, release thread state.
1506   __ stw(R0/*thread_state*/, thread_(thread_state));
1507 
1508   if (CheckJNICalls) {
1509     // clear_pending_jni_exception_check
1510     __ load_const_optimized(R0, 0L);
1511     __ st_ptr(R0, JavaThread::pending_jni_exception_check_fn_offset(), R16_thread);
1512   }
1513 
1514   __ reset_last_Java_frame();
1515 
1516   // Jvmdi/jvmpi support. Whether we've got an exception pending or
1517   // not, and whether unlocking throws an exception or not, we notify
1518   // on native method exit. If we do have an exception, we'll end up
1519   // in the caller's context to handle it, so if we don't do the
1520   // notify here, we'll drop it on the floor.
1521   __ notify_method_exit(true/*native method*/,
1522                         ilgl /*illegal state (not used for native methods)*/,
1523                         InterpreterMacroAssembler::NotifyJVMTI,
1524                         false /*check_exceptions*/);
1525 
1526   //=============================================================================
1527   // Handle exceptions
1528 
1529   if (synchronized) {
1530     __ unlock_object(R26_monitor); // Can also unlock methods.
1531   }
1532 
1533   // Reset active handles after returning from native.
1534   // thread->active_handles()->clear();
1535   __ ld(active_handles, thread_(active_handles));
1536   // TODO PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
1537   __ li(R0, 0);
1538   __ stw(R0, JNIHandleBlock::top_offset_in_bytes(), active_handles);
1539 
1540   Label exception_return_sync_check_already_unlocked;
1541   __ ld(R0/*pending_exception*/, thread_(pending_exception));
1542   __ cmpdi(CCR0, R0/*pending_exception*/, 0);
1543   __ bne(CCR0, exception_return_sync_check_already_unlocked);
1544 
1545   //-----------------------------------------------------------------------------
1546   // No exception pending.
1547 
1548   // Move native method result back into proper registers and return.
1549   // Invoke result handler (may unbox/promote).
1550   __ ld(R11_scratch1, 0, R1_SP);
1551   __ ld(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1552   __ lfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1553   __ call_stub(result_handler_addr);
1554 
1555   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
1556 
1557   // Must use the return pc which was loaded from the caller's frame
1558   // as the VM uses return-pc-patching for deoptimization.
1559   __ mtlr(R0);
1560   __ blr();
1561 
1562   //-----------------------------------------------------------------------------
1563   // An exception is pending. We call into the runtime only if the
1564   // caller was not interpreted. If it was interpreted the
1565   // interpreter will do the correct thing. If it isn't interpreted
1566   // (call stub/compiled code) we will change our return and continue.
1567 
1568   BIND(exception_return_sync_check);
1569 
1570   if (synchronized) {
1571     __ unlock_object(R26_monitor); // Can also unlock methods.
1572   }
1573   BIND(exception_return_sync_check_already_unlocked);
1574 
1575   const Register return_pc = R31;
1576 
1577   __ ld(return_pc, 0, R1_SP);
1578   __ ld(return_pc, _abi0(lr), return_pc);
1579 
1580   // Get the address of the exception handler.
1581   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1582                   R16_thread,
1583                   return_pc /* return pc */);
1584   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, noreg, R11_scratch1, R12_scratch2);
1585 
1586   // Load the PC of the the exception handler into LR.
1587   __ mtlr(R3_RET);
1588 
1589   // Load exception into R3_ARG1 and clear pending exception in thread.
1590   __ ld(R3_ARG1/*exception*/, thread_(pending_exception));
1591   __ li(R4_ARG2, 0);
1592   __ std(R4_ARG2, thread_(pending_exception));
1593 
1594   // Load the original return pc into R4_ARG2.
1595   __ mr(R4_ARG2/*issuing_pc*/, return_pc);
1596 
1597   // Return to exception handler.
1598   __ blr();
1599 
1600   //=============================================================================
1601   // Counter overflow.
1602 
1603   if (inc_counter) {
1604     // Handle invocation counter overflow.
1605     __ bind(invocation_counter_overflow);
1606 
1607     generate_counter_overflow(continue_after_compile);
1608   }
1609 
1610   return entry;
1611 }
1612 
1613 // Generic interpreted method entry to (asm) interpreter.
1614 //
1615 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1616   bool inc_counter = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1617   address entry = __ pc();
1618   // Generate the code to allocate the interpreter stack frame.
1619   Register Rsize_of_parameters = R4_ARG2, // Written by generate_fixed_frame.
1620            Rsize_of_locals     = R5_ARG3; // Written by generate_fixed_frame.
1621 
1622   // Does also a stack check to assure this frame fits on the stack.
1623   generate_fixed_frame(false, Rsize_of_parameters, Rsize_of_locals);
1624 
1625   // --------------------------------------------------------------------------
1626   // Zero out non-parameter locals.
1627   // Note: *Always* zero out non-parameter locals as Sparc does. It's not
1628   // worth to ask the flag, just do it.
1629   Register Rslot_addr = R6_ARG4,
1630            Rnum       = R7_ARG5;
1631   Label Lno_locals, Lzero_loop;
1632 
1633   // Set up the zeroing loop.
1634   __ subf(Rnum, Rsize_of_parameters, Rsize_of_locals);
1635   __ subf(Rslot_addr, Rsize_of_parameters, R18_locals);
1636   __ srdi_(Rnum, Rnum, Interpreter::logStackElementSize);
1637   __ beq(CCR0, Lno_locals);
1638   __ li(R0, 0);
1639   __ mtctr(Rnum);
1640 
1641   // The zero locals loop.
1642   __ bind(Lzero_loop);
1643   __ std(R0, 0, Rslot_addr);
1644   __ addi(Rslot_addr, Rslot_addr, -Interpreter::stackElementSize);
1645   __ bdnz(Lzero_loop);
1646 
1647   __ bind(Lno_locals);
1648 
1649   // --------------------------------------------------------------------------
1650   // Counter increment and overflow check.
1651   Label invocation_counter_overflow;
1652   Label continue_after_compile;
1653   if (inc_counter || ProfileInterpreter) {
1654 
1655     Register Rdo_not_unlock_if_synchronized_addr = R11_scratch1;
1656     if (synchronized) {
1657       // Since at this point in the method invocation the exception handler
1658       // would try to exit the monitor of synchronized methods which hasn't
1659       // been entered yet, we set the thread local variable
1660       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1661       // runtime, exception handling i.e. unlock_if_synchronized_method will
1662       // check this thread local flag.
1663       // This flag has two effects, one is to force an unwind in the topmost
1664       // interpreter frame and not perform an unlock while doing so.
1665       __ li(R0, 1);
1666       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1667     }
1668 
1669     // Argument and return type profiling.
1670     __ profile_parameters_type(R3_ARG1, R4_ARG2, R5_ARG3, R6_ARG4);
1671 
1672     // Increment invocation counter and check for overflow.
1673     if (inc_counter) {
1674       generate_counter_incr(&invocation_counter_overflow);
1675     }
1676 
1677     __ bind(continue_after_compile);
1678   }
1679 
1680   bang_stack_shadow_pages(false);
1681 
1682   if (inc_counter || ProfileInterpreter) {
1683     // Reset the _do_not_unlock_if_synchronized flag.
1684     if (synchronized) {
1685       __ li(R0, 0);
1686       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1687     }
1688   }
1689 
1690   // --------------------------------------------------------------------------
1691   // Locking of synchronized methods. Must happen AFTER invocation_counter
1692   // check and stack overflow check, so method is not locked if overflows.
1693   if (synchronized) {
1694     lock_method(R3_ARG1, R4_ARG2, R5_ARG3);
1695   }
1696 #ifdef ASSERT
1697   else {
1698     Label Lok;
1699     __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1700     __ andi_(R0, R0, JVM_ACC_SYNCHRONIZED);
1701     __ asm_assert_eq("method needs synchronization");
1702     __ bind(Lok);
1703   }
1704 #endif // ASSERT
1705 
1706   __ verify_thread();
1707 
1708   // --------------------------------------------------------------------------
1709   // JVMTI support
1710   __ notify_method_entry();
1711 
1712   // --------------------------------------------------------------------------
1713   // Start executing instructions.
1714   __ dispatch_next(vtos);
1715 
1716   // --------------------------------------------------------------------------
1717   if (inc_counter) {
1718     // Handle invocation counter overflow.
1719     __ bind(invocation_counter_overflow);
1720     generate_counter_overflow(continue_after_compile);
1721   }
1722   return entry;
1723 }
1724 
1725 // CRC32 Intrinsics.
1726 //
1727 // Contract on scratch and work registers.
1728 // =======================================
1729 //
1730 // On ppc, the register set {R2..R12} is available in the interpreter as scratch/work registers.
1731 // You should, however, keep in mind that {R3_ARG1..R10_ARG8} is the C-ABI argument register set.
1732 // You can't rely on these registers across calls.
1733 //
1734 // The generators for CRC32_update and for CRC32_updateBytes use the
1735 // scratch/work register set internally, passing the work registers
1736 // as arguments to the MacroAssembler emitters as required.
1737 //
1738 // R3_ARG1..R6_ARG4 are preset to hold the incoming java arguments.
1739 // Their contents is not constant but may change according to the requirements
1740 // of the emitted code.
1741 //
1742 // All other registers from the scratch/work register set are used "internally"
1743 // and contain garbage (i.e. unpredictable values) once blr() is reached.
1744 // Basically, only R3_RET contains a defined value which is the function result.
1745 //
1746 /**
1747  * Method entry for static native methods:
1748  *   int java.util.zip.CRC32.update(int crc, int b)
1749  */
1750 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
1751   if (UseCRC32Intrinsics) {
1752     address start = __ pc();  // Remember stub start address (is rtn value).
1753     Label slow_path;
1754 
1755     // Safepoint check
1756     const Register sync_state = R11_scratch1;
1757     __ safepoint_poll(slow_path, sync_state, false /* at_return */, false /* in_nmethod */);
1758 
1759     // We don't generate local frame and don't align stack because
1760     // we not even call stub code (we generate the code inline)
1761     // and there is no safepoint on this path.
1762 
1763     // Load java parameters.
1764     // R15_esp is callers operand stack pointer, i.e. it points to the parameters.
1765     const Register argP    = R15_esp;
1766     const Register crc     = R3_ARG1;  // crc value
1767     const Register data    = R4_ARG2;
1768     const Register table   = R5_ARG3;  // address of crc32 table
1769 
1770     BLOCK_COMMENT("CRC32_update {");
1771 
1772     // Arguments are reversed on java expression stack
1773 #ifdef VM_LITTLE_ENDIAN
1774     int data_offs = 0+1*wordSize;      // (stack) address of byte value. Emitter expects address, not value.
1775                                        // Being passed as an int, the single byte is at offset +0.
1776 #else
1777     int data_offs = 3+1*wordSize;      // (stack) address of byte value. Emitter expects address, not value.
1778                                        // Being passed from java as an int, the single byte is at offset +3.
1779 #endif
1780     __ lwz(crc, 2*wordSize, argP);     // Current crc state, zero extend to 64 bit to have a clean register.
1781     __ lbz(data, data_offs, argP);     // Byte from buffer, zero-extended.
1782     __ load_const_optimized(table, StubRoutines::crc_table_addr(), R0);
1783     __ kernel_crc32_singleByteReg(crc, data, table, true);
1784 
1785     // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1786     __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1787     __ blr();
1788 
1789     // Generate a vanilla native entry as the slow path.
1790     BLOCK_COMMENT("} CRC32_update");
1791     BIND(slow_path);
1792     __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), R11_scratch1);
1793     return start;
1794   }
1795 
1796   return NULL;
1797 }
1798 
1799 /**
1800  * Method entry for static native methods:
1801  *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
1802  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long* buf, int off, int len)
1803  */
1804 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1805   if (UseCRC32Intrinsics) {
1806     address start = __ pc();  // Remember stub start address (is rtn value).
1807     Label slow_path;
1808 
1809     // Safepoint check
1810     const Register sync_state = R11_scratch1;
1811     __ safepoint_poll(slow_path, sync_state, false /* at_return */, false /* in_nmethod */);
1812 
1813     // We don't generate local frame and don't align stack because
1814     // we not even call stub code (we generate the code inline)
1815     // and there is no safepoint on this path.
1816 
1817     // Load parameters.
1818     // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1819     const Register argP    = R15_esp;
1820     const Register crc     = R3_ARG1;  // crc value
1821     const Register data    = R4_ARG2;  // address of java byte array
1822     const Register dataLen = R5_ARG3;  // source data len
1823     const Register tmp     = R11_scratch1;
1824 
1825     // Arguments are reversed on java expression stack.
1826     // Calculate address of start element.
1827     if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { // Used for "updateByteBuffer direct".
1828       BLOCK_COMMENT("CRC32_updateByteBuffer {");
1829       // crc     @ (SP + 5W) (32bit)
1830       // buf     @ (SP + 3W) (64bit ptr to long array)
1831       // off     @ (SP + 2W) (32bit)
1832       // dataLen @ (SP + 1W) (32bit)
1833       // data = buf + off
1834       __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1835       __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1836       __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1837       __ lwz( crc,     5*wordSize, argP);  // current crc state
1838       __ add( data, data, tmp);            // Add byte buffer offset.
1839     } else {                                                         // Used for "updateBytes update".
1840       BLOCK_COMMENT("CRC32_updateBytes {");
1841       // crc     @ (SP + 4W) (32bit)
1842       // buf     @ (SP + 3W) (64bit ptr to byte array)
1843       // off     @ (SP + 2W) (32bit)
1844       // dataLen @ (SP + 1W) (32bit)
1845       // data = buf + off + base_offset
1846       __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1847       __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1848       __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1849       __ add( data, data, tmp);            // add byte buffer offset
1850       __ lwz( crc,     4*wordSize, argP);  // current crc state
1851       __ addi(data, data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1852     }
1853 
1854     __ crc32(crc, data, dataLen, R2, R6, R7, R8, R9, R10, R11, R12, false);
1855 
1856     // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1857     __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1858     __ blr();
1859 
1860     // Generate a vanilla native entry as the slow path.
1861     BLOCK_COMMENT("} CRC32_updateBytes(Buffer)");
1862     BIND(slow_path);
1863     __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), R11_scratch1);
1864     return start;
1865   }
1866 
1867   return NULL;
1868 }
1869 
1870 
1871 /**
1872  * Method entry for intrinsic-candidate (non-native) methods:
1873  *   int java.util.zip.CRC32C.updateBytes(           int crc, byte[] b,  int off, int end)
1874  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long* buf, int off, int end)
1875  * Unlike CRC32, CRC32C does not have any methods marked as native
1876  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1877  **/
1878 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1879   if (UseCRC32CIntrinsics) {
1880     address start = __ pc();  // Remember stub start address (is rtn value).
1881 
1882     // We don't generate local frame and don't align stack because
1883     // we not even call stub code (we generate the code inline)
1884     // and there is no safepoint on this path.
1885 
1886     // Load parameters.
1887     // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1888     const Register argP    = R15_esp;
1889     const Register crc     = R3_ARG1;  // crc value
1890     const Register data    = R4_ARG2;  // address of java byte array
1891     const Register dataLen = R5_ARG3;  // source data len
1892     const Register tmp     = R11_scratch1;
1893 
1894     // Arguments are reversed on java expression stack.
1895     // Calculate address of start element.
1896     if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) { // Used for "updateDirectByteBuffer".
1897       BLOCK_COMMENT("CRC32C_updateDirectByteBuffer {");
1898       // crc     @ (SP + 5W) (32bit)
1899       // buf     @ (SP + 3W) (64bit ptr to long array)
1900       // off     @ (SP + 2W) (32bit)
1901       // dataLen @ (SP + 1W) (32bit)
1902       // data = buf + off
1903       __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1904       __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1905       __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1906       __ lwz( crc,     5*wordSize, argP);  // current crc state
1907       __ add( data, data, tmp);            // Add byte buffer offset.
1908       __ sub( dataLen, dataLen, tmp);      // (end_index - offset)
1909     } else {                                                         // Used for "updateBytes update".
1910       BLOCK_COMMENT("CRC32C_updateBytes {");
1911       // crc     @ (SP + 4W) (32bit)
1912       // buf     @ (SP + 3W) (64bit ptr to byte array)
1913       // off     @ (SP + 2W) (32bit)
1914       // dataLen @ (SP + 1W) (32bit)
1915       // data = buf + off + base_offset
1916       __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1917       __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1918       __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1919       __ add( data, data, tmp);            // add byte buffer offset
1920       __ sub( dataLen, dataLen, tmp);      // (end_index - offset)
1921       __ lwz( crc,     4*wordSize, argP);  // current crc state
1922       __ addi(data, data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1923     }
1924 
1925     __ crc32(crc, data, dataLen, R2, R6, R7, R8, R9, R10, R11, R12, true);
1926 
1927     // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1928     __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1929     __ blr();
1930 
1931     BLOCK_COMMENT("} CRC32C_update{Bytes|DirectByteBuffer}");
1932     return start;
1933   }
1934 
1935   return NULL;
1936 }
1937 
1938 // =============================================================================
1939 // Exceptions
1940 
1941 void TemplateInterpreterGenerator::generate_throw_exception() {
1942   Register Rexception    = R17_tos,
1943            Rcontinuation = R3_RET;
1944 
1945   // --------------------------------------------------------------------------
1946   // Entry point if an method returns with a pending exception (rethrow).
1947   Interpreter::_rethrow_exception_entry = __ pc();
1948   {
1949     __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
1950     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
1951     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
1952 
1953     // Compiled code destroys templateTableBase, reload.
1954     __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
1955   }
1956 
1957   // Entry point if a interpreted method throws an exception (throw).
1958   Interpreter::_throw_exception_entry = __ pc();
1959   {
1960     __ mr(Rexception, R3_RET);
1961 
1962     __ verify_thread();
1963     __ verify_oop(Rexception);
1964 
1965     // Expression stack must be empty before entering the VM in case of an exception.
1966     __ empty_expression_stack();
1967     // Find exception handler address and preserve exception oop.
1968     // Call C routine to find handler and jump to it.
1969     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Rexception);
1970     __ mtctr(Rcontinuation);
1971     // Push exception for exception handler bytecodes.
1972     __ push_ptr(Rexception);
1973 
1974     // Jump to exception handler (may be remove activation entry!).
1975     __ bctr();
1976   }
1977 
1978   // If the exception is not handled in the current frame the frame is
1979   // removed and the exception is rethrown (i.e. exception
1980   // continuation is _rethrow_exception).
1981   //
1982   // Note: At this point the bci is still the bxi for the instruction
1983   // which caused the exception and the expression stack is
1984   // empty. Thus, for any VM calls at this point, GC will find a legal
1985   // oop map (with empty expression stack).
1986 
1987   // In current activation
1988   // tos: exception
1989   // bcp: exception bcp
1990 
1991   // --------------------------------------------------------------------------
1992   // JVMTI PopFrame support
1993 
1994   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1995   {
1996     // Set the popframe_processing bit in popframe_condition indicating that we are
1997     // currently handling popframe, so that call_VMs that may happen later do not
1998     // trigger new popframe handling cycles.
1999     __ lwz(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2000     __ ori(R11_scratch1, R11_scratch1, JavaThread::popframe_processing_bit);
2001     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2002 
2003     // Empty the expression stack, as in normal exception handling.
2004     __ empty_expression_stack();
2005     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
2006 
2007     // Check to see whether we are returning to a deoptimized frame.
2008     // (The PopFrame call ensures that the caller of the popped frame is
2009     // either interpreted or compiled and deoptimizes it if compiled.)
2010     // Note that we don't compare the return PC against the
2011     // deoptimization blob's unpack entry because of the presence of
2012     // adapter frames in C2.
2013     Label Lcaller_not_deoptimized;
2014     Register return_pc = R3_ARG1;
2015     __ ld(return_pc, 0, R1_SP);
2016     __ ld(return_pc, _abi0(lr), return_pc);
2017     __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), return_pc);
2018     __ cmpdi(CCR0, R3_RET, 0);
2019     __ bne(CCR0, Lcaller_not_deoptimized);
2020 
2021     // The deoptimized case.
2022     // In this case, we can't call dispatch_next() after the frame is
2023     // popped, but instead must save the incoming arguments and restore
2024     // them after deoptimization has occurred.
2025     __ ld(R4_ARG2, in_bytes(Method::const_offset()), R19_method);
2026     __ lhz(R4_ARG2 /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), R4_ARG2);
2027     __ slwi(R4_ARG2, R4_ARG2, Interpreter::logStackElementSize);
2028     __ addi(R5_ARG3, R18_locals, Interpreter::stackElementSize);
2029     __ subf(R5_ARG3, R4_ARG2, R5_ARG3);
2030     // Save these arguments.
2031     __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), R16_thread, R4_ARG2, R5_ARG3);
2032 
2033     // Inform deoptimization that it is responsible for restoring these arguments.
2034     __ load_const_optimized(R11_scratch1, JavaThread::popframe_force_deopt_reexecution_bit);
2035     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2036 
2037     // Return from the current method into the deoptimization blob. Will eventually
2038     // end up in the deopt interpeter entry, deoptimization prepared everything that
2039     // we will reexecute the call that called us.
2040     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*reload return_pc*/ return_pc, R11_scratch1, R12_scratch2);
2041     __ mtlr(return_pc);
2042     __ blr();
2043 
2044     // The non-deoptimized case.
2045     __ bind(Lcaller_not_deoptimized);
2046 
2047     // Clear the popframe condition flag.
2048     __ li(R0, 0);
2049     __ stw(R0, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2050 
2051     // Get out of the current method and re-execute the call that called us.
2052     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
2053     __ restore_interpreter_state(R11_scratch1);
2054     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
2055     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
2056     if (ProfileInterpreter) {
2057       __ set_method_data_pointer_for_bcp();
2058       __ ld(R11_scratch1, 0, R1_SP);
2059       __ std(R28_mdx, _ijava_state_neg(mdx), R11_scratch1);
2060     }
2061 #if INCLUDE_JVMTI
2062     Label L_done;
2063 
2064     __ lbz(R11_scratch1, 0, R14_bcp);
2065     __ cmpwi(CCR0, R11_scratch1, Bytecodes::_invokestatic);
2066     __ bne(CCR0, L_done);
2067 
2068     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
2069     // Detect such a case in the InterpreterRuntime function and return the member name argument, or NULL.
2070     __ ld(R4_ARG2, 0, R18_locals);
2071     __ call_VM(R4_ARG2, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), R4_ARG2, R19_method, R14_bcp);
2072 
2073     __ cmpdi(CCR0, R4_ARG2, 0);
2074     __ beq(CCR0, L_done);
2075     __ std(R4_ARG2, wordSize, R15_esp);
2076     __ bind(L_done);
2077 #endif // INCLUDE_JVMTI
2078     __ dispatch_next(vtos);
2079   }
2080   // end of JVMTI PopFrame support
2081 
2082   // --------------------------------------------------------------------------
2083   // Remove activation exception entry.
2084   // This is jumped to if an interpreted method can't handle an exception itself
2085   // (we come from the throw/rethrow exception entry above). We're going to call
2086   // into the VM to find the exception handler in the caller, pop the current
2087   // frame and return the handler we calculated.
2088   Interpreter::_remove_activation_entry = __ pc();
2089   {
2090     __ pop_ptr(Rexception);
2091     __ verify_thread();
2092     __ verify_oop(Rexception);
2093     __ std(Rexception, in_bytes(JavaThread::vm_result_offset()), R16_thread);
2094 
2095     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, true);
2096     __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI, false);
2097 
2098     __ get_vm_result(Rexception);
2099 
2100     // We are done with this activation frame; find out where to go next.
2101     // The continuation point will be an exception handler, which expects
2102     // the following registers set up:
2103     //
2104     // RET:  exception oop
2105     // ARG2: Issuing PC (see generate_exception_blob()), only used if the caller is compiled.
2106 
2107     Register return_pc = R31; // Needs to survive the runtime call.
2108     __ ld(return_pc, 0, R1_SP);
2109     __ ld(return_pc, _abi0(lr), return_pc);
2110     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), R16_thread, return_pc);
2111 
2112     // Remove the current activation.
2113     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
2114 
2115     __ mr(R4_ARG2, return_pc);
2116     __ mtlr(R3_RET);
2117     __ mr(R3_RET, Rexception);
2118     __ blr();
2119   }
2120 }
2121 
2122 // JVMTI ForceEarlyReturn support.
2123 // Returns "in the middle" of a method with a "fake" return value.
2124 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
2125 
2126   Register Rscratch1 = R11_scratch1,
2127            Rscratch2 = R12_scratch2;
2128 
2129   address entry = __ pc();
2130   __ empty_expression_stack();
2131 
2132   __ load_earlyret_value(state, Rscratch1);
2133 
2134   __ ld(Rscratch1, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
2135   // Clear the earlyret state.
2136   __ li(R0, 0);
2137   __ stw(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rscratch1);
2138 
2139   __ remove_activation(state, false, false);
2140   // Copied from TemplateTable::_return.
2141   // Restoration of lr done by remove_activation.
2142   switch (state) {
2143     // Narrow result if state is itos but result type is smaller.
2144     case btos:
2145     case ztos:
2146     case ctos:
2147     case stos:
2148     case itos: __ narrow(R17_tos); /* fall through */
2149     case ltos:
2150     case atos: __ mr(R3_RET, R17_tos); break;
2151     case ftos:
2152     case dtos: __ fmr(F1_RET, F15_ftos); break;
2153     case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
2154                // to get visible before the reference to the object gets stored anywhere.
2155                __ membar(Assembler::StoreStore); break;
2156     default  : ShouldNotReachHere();
2157   }
2158   __ blr();
2159 
2160   return entry;
2161 } // end of ForceEarlyReturn support
2162 
2163 //-----------------------------------------------------------------------------
2164 // Helper for vtos entry point generation
2165 
2166 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2167                                                          address& bep,
2168                                                          address& cep,
2169                                                          address& sep,
2170                                                          address& aep,
2171                                                          address& iep,
2172                                                          address& lep,
2173                                                          address& fep,
2174                                                          address& dep,
2175                                                          address& vep) {
2176   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2177   Label L;
2178 
2179   aep = __ pc();  __ push_ptr();  __ b(L);
2180   fep = __ pc();  __ push_f();    __ b(L);
2181   dep = __ pc();  __ push_d();    __ b(L);
2182   lep = __ pc();  __ push_l();    __ b(L);
2183   __ align(32, 12, 24); // align L
2184   bep = cep = sep =
2185   iep = __ pc();  __ push_i();
2186   vep = __ pc();
2187   __ bind(L);
2188   generate_and_dispatch(t);
2189 }
2190 
2191 //-----------------------------------------------------------------------------
2192 
2193 // Non-product code
2194 #ifndef PRODUCT
2195 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2196   //__ flush_bundle();
2197   address entry = __ pc();
2198 
2199   const char *bname = NULL;
2200   uint tsize = 0;
2201   switch(state) {
2202   case ftos:
2203     bname = "trace_code_ftos {";
2204     tsize = 2;
2205     break;
2206   case btos:
2207     bname = "trace_code_btos {";
2208     tsize = 2;
2209     break;
2210   case ztos:
2211     bname = "trace_code_ztos {";
2212     tsize = 2;
2213     break;
2214   case ctos:
2215     bname = "trace_code_ctos {";
2216     tsize = 2;
2217     break;
2218   case stos:
2219     bname = "trace_code_stos {";
2220     tsize = 2;
2221     break;
2222   case itos:
2223     bname = "trace_code_itos {";
2224     tsize = 2;
2225     break;
2226   case ltos:
2227     bname = "trace_code_ltos {";
2228     tsize = 3;
2229     break;
2230   case atos:
2231     bname = "trace_code_atos {";
2232     tsize = 2;
2233     break;
2234   case vtos:
2235     // Note: In case of vtos, the topmost of stack value could be a int or doubl
2236     // In case of a double (2 slots) we won't see the 2nd stack value.
2237     // Maybe we simply should print the topmost 3 stack slots to cope with the problem.
2238     bname = "trace_code_vtos {";
2239     tsize = 2;
2240 
2241     break;
2242   case dtos:
2243     bname = "trace_code_dtos {";
2244     tsize = 3;
2245     break;
2246   default:
2247     ShouldNotReachHere();
2248   }
2249   BLOCK_COMMENT(bname);
2250 
2251   // Support short-cut for TraceBytecodesAt.
2252   // Don't call into the VM if we don't want to trace to speed up things.
2253   Label Lskip_vm_call;
2254   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
2255     int offs1 = __ load_const_optimized(R11_scratch1, (address) &TraceBytecodesAt, R0, true);
2256     int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
2257     __ ld(R11_scratch1, offs1, R11_scratch1);
2258     __ lwa(R12_scratch2, offs2, R12_scratch2);
2259     __ cmpd(CCR0, R12_scratch2, R11_scratch1);
2260     __ blt(CCR0, Lskip_vm_call);
2261   }
2262 
2263   __ push(state);
2264   // Load 2 topmost expression stack values.
2265   __ ld(R6_ARG4, tsize*Interpreter::stackElementSize, R15_esp);
2266   __ ld(R5_ARG3, Interpreter::stackElementSize, R15_esp);
2267   __ mflr(R31);
2268   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode), /* unused */ R4_ARG2, R5_ARG3, R6_ARG4, false);
2269   __ mtlr(R31);
2270   __ pop(state);
2271 
2272   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
2273     __ bind(Lskip_vm_call);
2274   }
2275   __ blr();
2276   BLOCK_COMMENT("} trace_code");
2277   return entry;
2278 }
2279 
2280 void TemplateInterpreterGenerator::count_bytecode() {
2281   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeCounter::_counter_value, R12_scratch2, true);
2282   __ lwz(R12_scratch2, offs, R11_scratch1);
2283   __ addi(R12_scratch2, R12_scratch2, 1);
2284   __ stw(R12_scratch2, offs, R11_scratch1);
2285 }
2286 
2287 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2288   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeHistogram::_counters[t->bytecode()], R12_scratch2, true);
2289   __ lwz(R12_scratch2, offs, R11_scratch1);
2290   __ addi(R12_scratch2, R12_scratch2, 1);
2291   __ stw(R12_scratch2, offs, R11_scratch1);
2292 }
2293 
2294 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2295   const Register addr = R11_scratch1,
2296                  tmp  = R12_scratch2;
2297   // Get index, shift out old bytecode, bring in new bytecode, and store it.
2298   // _index = (_index >> log2_number_of_codes) |
2299   //          (bytecode << log2_number_of_codes);
2300   int offs1 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_index, tmp, true);
2301   __ lwz(tmp, offs1, addr);
2302   __ srwi(tmp, tmp, BytecodePairHistogram::log2_number_of_codes);
2303   __ ori(tmp, tmp, ((int) t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2304   __ stw(tmp, offs1, addr);
2305 
2306   // Bump bucket contents.
2307   // _counters[_index] ++;
2308   int offs2 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_counters, R0, true);
2309   __ sldi(tmp, tmp, LogBytesPerInt);
2310   __ add(addr, tmp, addr);
2311   __ lwz(tmp, offs2, addr);
2312   __ addi(tmp, tmp, 1);
2313   __ stw(tmp, offs2, addr);
2314 }
2315 
2316 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2317   // Call a little run-time stub to avoid blow-up for each bytecode.
2318   // The run-time runtime saves the right registers, depending on
2319   // the tosca in-state for the given template.
2320 
2321   assert(Interpreter::trace_code(t->tos_in()) != NULL,
2322          "entry must have been generated");
2323 
2324   // Note: we destroy LR here.
2325   __ bl(Interpreter::trace_code(t->tos_in()));
2326 }
2327 
2328 void TemplateInterpreterGenerator::stop_interpreter_at() {
2329   Label L;
2330   int offs1 = __ load_const_optimized(R11_scratch1, (address) &StopInterpreterAt, R0, true);
2331   int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
2332   __ ld(R11_scratch1, offs1, R11_scratch1);
2333   __ lwa(R12_scratch2, offs2, R12_scratch2);
2334   __ cmpd(CCR0, R12_scratch2, R11_scratch1);
2335   __ bne(CCR0, L);
2336   __ illtrap();
2337   __ bind(L);
2338 }
2339 
2340 #endif // !PRODUCT