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