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