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