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