1 /*
  2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "asm/macroAssembler.hpp"
 26 #include "asm/macroAssembler.inline.hpp"
 27 #include "cds/metaspaceShared.hpp"
 28 #include "compiler/disassembler.hpp"
 29 #include "interpreter/bytecodeHistogram.hpp"
 30 #include "interpreter/bytecodeStream.hpp"
 31 #include "interpreter/interpreter.hpp"
 32 #include "interpreter/interpreterRuntime.hpp"
 33 #include "interpreter/interp_masm.hpp"
 34 #include "interpreter/templateTable.hpp"
 35 #include "memory/allocation.inline.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "oops/arrayOop.hpp"
 38 #include "oops/constantPool.inline.hpp"
 39 #include "oops/cpCache.inline.hpp"
 40 #include "oops/methodData.hpp"
 41 #include "oops/method.inline.hpp"
 42 #include "oops/oop.inline.hpp"
 43 #include "prims/jvmtiExport.hpp"
 44 #include "prims/methodHandles.hpp"
 45 #include "runtime/handles.inline.hpp"
 46 #include "runtime/sharedRuntime.hpp"
 47 #include "runtime/stubRoutines.hpp"
 48 #include "runtime/timer.hpp"
 49 
 50 # define __ _masm->
 51 
 52 //------------------------------------------------------------------------------------------------------------------------
 53 // Implementation of platform independent aspects of Interpreter
 54 
 55 void AbstractInterpreter::initialize() {
 56   // make sure 'imported' classes are initialized
 57   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) BytecodeCounter::reset();
 58   if (PrintBytecodeHistogram)                                BytecodeHistogram::reset();
 59   if (PrintBytecodePairHistogram)                            BytecodePairHistogram::reset();
 60 }
 61 
 62 void AbstractInterpreter::print() {
 63   tty->cr();
 64   tty->print_cr("----------------------------------------------------------------------");
 65   tty->print_cr("Interpreter");
 66   tty->cr();
 67   tty->print_cr("code size        = %6dK bytes", (int)_code->used_space()/1024);
 68   tty->print_cr("total space      = %6dK bytes", (int)_code->total_space()/1024);
 69   tty->print_cr("wasted space     = %6dK bytes", (int)_code->available_space()/1024);
 70   tty->cr();
 71   tty->print_cr("# of codelets    = %6d"      , _code->number_of_stubs());
 72   if (_code->number_of_stubs() != 0) {
 73     tty->print_cr("avg codelet size = %6d bytes", _code->used_space() / _code->number_of_stubs());
 74     tty->cr();
 75   }
 76   _should_print_instructions = PrintInterpreter;
 77   _code->print();
 78   _should_print_instructions = false;
 79   tty->print_cr("----------------------------------------------------------------------");
 80   tty->cr();
 81 }
 82 
 83 
 84 //------------------------------------------------------------------------------------------------------------------------
 85 // Implementation of interpreter
 86 
 87 StubQueue* AbstractInterpreter::_code                                       = nullptr;
 88 bool       AbstractInterpreter::_notice_safepoints                          = false;
 89 address    AbstractInterpreter::_rethrow_exception_entry                    = nullptr;
 90 
 91 address    AbstractInterpreter::_slow_signature_handler;
 92 address    AbstractInterpreter::_entry_table            [AbstractInterpreter::number_of_method_entries];
 93 address    AbstractInterpreter::_native_abi_to_tosca    [AbstractInterpreter::number_of_result_handlers];
 94 
 95 bool       AbstractInterpreter::_should_print_instructions = false;
 96 
 97 //------------------------------------------------------------------------------------------------------------------------
 98 // Generation of complete interpreter
 99 
100 AbstractInterpreterGenerator::AbstractInterpreterGenerator() {
101   _masm                      = nullptr;
102 }
103 
104 
105 //------------------------------------------------------------------------------------------------------------------------
106 // Entry points
107 
108 AbstractInterpreter::MethodKind AbstractInterpreter::method_kind(const methodHandle& m) {
109   // Abstract method?
110   if (m->is_abstract()) return abstract;
111 
112   // Method handle primitive?
113   vmIntrinsics::ID iid = m->intrinsic_id();
114   if (iid != vmIntrinsics::_none) {
115     if (m->is_method_handle_intrinsic()) {
116       assert(MethodHandles::is_signature_polymorphic(iid), "must match an intrinsic");
117       MethodKind kind = (MethodKind)(method_handle_invoke_FIRST +
118                                     vmIntrinsics::as_int(iid) -
119                                     static_cast<int>(vmIntrinsics::FIRST_MH_SIG_POLY));
120       assert(kind <= method_handle_invoke_LAST, "parallel enum ranges");
121       return kind;
122     }
123 
124     switch (iid) {
125 #ifndef ZERO
126       // Use optimized stub code for CRC32 native methods.
127       case vmIntrinsics::_updateCRC32:       return java_util_zip_CRC32_update;
128       case vmIntrinsics::_updateBytesCRC32:  return java_util_zip_CRC32_updateBytes;
129       case vmIntrinsics::_updateByteBufferCRC32: return java_util_zip_CRC32_updateByteBuffer;
130       // Use optimized stub code for CRC32C methods.
131       case vmIntrinsics::_updateBytesCRC32C: return java_util_zip_CRC32C_updateBytes;
132       case vmIntrinsics::_updateDirectByteBufferCRC32C: return java_util_zip_CRC32C_updateDirectByteBuffer;
133       case vmIntrinsics::_intBitsToFloat:    return java_lang_Float_intBitsToFloat;
134       case vmIntrinsics::_floatToRawIntBits: return java_lang_Float_floatToRawIntBits;
135       case vmIntrinsics::_longBitsToDouble:  return java_lang_Double_longBitsToDouble;
136       case vmIntrinsics::_doubleToRawLongBits: return java_lang_Double_doubleToRawLongBits;
137       case vmIntrinsics::_float16ToFloat:    return java_lang_Float_float16ToFloat;
138       case vmIntrinsics::_floatToFloat16:    return java_lang_Float_floatToFloat16;
139       case vmIntrinsics::_currentThread:     return java_lang_Thread_currentThread;
140 #endif // ZERO
141       case vmIntrinsics::_dsin:              return java_lang_math_sin;
142       case vmIntrinsics::_dcos:              return java_lang_math_cos;
143       case vmIntrinsics::_dtan:              return java_lang_math_tan;
144       case vmIntrinsics::_dtanh:             return java_lang_math_tanh;
145       case vmIntrinsics::_dabs:              return java_lang_math_abs;
146       case vmIntrinsics::_dlog:              return java_lang_math_log;
147       case vmIntrinsics::_dlog10:            return java_lang_math_log10;
148       case vmIntrinsics::_dpow:              return java_lang_math_pow;
149       case vmIntrinsics::_dexp:              return java_lang_math_exp;
150       case vmIntrinsics::_fmaD:              return java_lang_math_fmaD;
151       case vmIntrinsics::_fmaF:              return java_lang_math_fmaF;
152       case vmIntrinsics::_dsqrt:             return java_lang_math_sqrt;
153       case vmIntrinsics::_dsqrt_strict:      return java_lang_math_sqrt_strict;
154       case vmIntrinsics::_Reference_get:     return java_lang_ref_reference_get;
155       case vmIntrinsics::_Object_init:
156         if (m->code_size() == 1) {
157           // We need to execute the special return bytecode to check for
158           // finalizer registration so create a normal frame.
159           return zerolocals;
160         }
161         break;
162       default: break;
163     }
164   }
165 
166   // Native method?
167   if (m->is_native()) {
168     if (m->is_continuation_native_intrinsic()) {
169       // This entry will never be called.  The real entry gets generated later, like for MH intrinsics.
170       return abstract;
171     }
172     assert(!m->is_method_handle_intrinsic(), "overlapping bits here, watch out");
173     if (m->is_synchronized()) {
174       return m->has_upcall_on_method_entry() ? native_synchronized_upcalls : native_synchronized;
175     }
176     return m->has_upcall_on_method_entry() ? native_upcalls : native;
177   }
178 
179   // Synchronized?
180   if (m->is_synchronized()) {
181     return m->has_upcall_on_method_entry() ? zerolocals_synchronized_upcalls : zerolocals_synchronized;
182   }
183 
184   // Empty method?
185   if (m->is_empty_method()) {
186     return m->has_upcall_on_method_entry() ? empty_upcalls : empty;
187   }
188 
189   // Getter method?
190   if (m->is_getter()) {
191     return getter;
192   }
193 
194   // Setter method?
195   if (m->is_setter()) {
196     return setter;
197   }
198 
199   // Note: for now: zero locals for all non-empty methods
200   return m->has_upcall_on_method_entry() ? zerolocals_upcalls : zerolocals;
201 }
202 
203 vmIntrinsics::ID AbstractInterpreter::method_intrinsic(MethodKind kind) {
204   switch (kind) {
205   case java_lang_math_sin         : return vmIntrinsics::_dsin;
206   case java_lang_math_cos         : return vmIntrinsics::_dcos;
207   case java_lang_math_tan         : return vmIntrinsics::_dtan;
208   case java_lang_math_tanh        : return vmIntrinsics::_dtanh;
209   case java_lang_math_abs         : return vmIntrinsics::_dabs;
210   case java_lang_math_log         : return vmIntrinsics::_dlog;
211   case java_lang_math_log10       : return vmIntrinsics::_dlog10;
212   case java_lang_math_sqrt        : return vmIntrinsics::_dsqrt;
213   case java_lang_math_sqrt_strict : return vmIntrinsics::_dsqrt_strict;
214   case java_lang_math_pow         : return vmIntrinsics::_dpow;
215   case java_lang_math_exp         : return vmIntrinsics::_dexp;
216   case java_lang_math_fmaD        : return vmIntrinsics::_fmaD;
217   case java_lang_math_fmaF        : return vmIntrinsics::_fmaF;
218   case java_lang_ref_reference_get: return vmIntrinsics::_Reference_get;
219   case java_util_zip_CRC32_update : return vmIntrinsics::_updateCRC32;
220   case java_util_zip_CRC32_updateBytes
221                                   : return vmIntrinsics::_updateBytesCRC32;
222   case java_util_zip_CRC32_updateByteBuffer
223                                   : return vmIntrinsics::_updateByteBufferCRC32;
224   case java_util_zip_CRC32C_updateBytes
225                                   : return vmIntrinsics::_updateBytesCRC32C;
226   case java_util_zip_CRC32C_updateDirectByteBuffer
227                                   : return vmIntrinsics::_updateDirectByteBufferCRC32C;
228   case java_lang_Thread_currentThread
229                                   : return vmIntrinsics::_currentThread;
230   case java_lang_Float_intBitsToFloat
231                                   : return vmIntrinsics::_intBitsToFloat;
232   case java_lang_Float_floatToRawIntBits
233                                   : return vmIntrinsics::_floatToRawIntBits;
234   case java_lang_Double_longBitsToDouble
235                                   : return vmIntrinsics::_longBitsToDouble;
236   case java_lang_Double_doubleToRawLongBits
237                                   : return vmIntrinsics::_doubleToRawLongBits;
238   case java_lang_Float_float16ToFloat
239                                   : return vmIntrinsics::_float16ToFloat;
240   case java_lang_Float_floatToFloat16
241                                   : return vmIntrinsics::_floatToFloat16;
242 
243   default:
244     fatal("unexpected method intrinsic kind: %d", kind);
245     break;
246   }
247   return vmIntrinsics::_none;
248 }
249 
250 void AbstractInterpreter::set_entry_for_kind(MethodKind kind, address entry) {
251   assert(kind >= method_handle_invoke_FIRST &&
252          kind <= method_handle_invoke_LAST, "late initialization only for MH entry points");
253   assert(_entry_table[kind] == _entry_table[abstract], "previous value must be AME entry");
254   _entry_table[kind] = entry;
255 }
256 
257 // Return true if the interpreter can prove that the given bytecode has
258 // not yet been executed (in Java semantics, not in actual operation).
259 bool AbstractInterpreter::is_not_reached(const methodHandle& method, int bci) {
260   BytecodeStream s(method, bci);
261   Bytecodes::Code code = s.next();
262 
263   if (Bytecodes::is_invoke(code)) {
264     assert(!Bytecodes::must_rewrite(code), "invokes aren't rewritten");
265     ConstantPool* cpool = method()->constants();
266 
267     Bytecode invoke_bc(s.bytecode());
268 
269     switch (code) {
270       case Bytecodes::_invokedynamic: {
271         assert(invoke_bc.has_index_u4(code), "sanity");
272         int method_index = invoke_bc.get_index_u4(code);
273         return cpool->resolved_indy_entry_at(method_index)->is_resolved();
274       }
275       case Bytecodes::_invokevirtual:   // fall-through
276       case Bytecodes::_invokeinterface: // fall-through
277       case Bytecodes::_invokespecial:   // fall-through
278       case Bytecodes::_invokestatic: {
279         if (cpool->has_preresolution()) {
280           return false; // might have been reached
281         }
282         assert(!invoke_bc.has_index_u4(code), "sanity");
283         int method_index = invoke_bc.get_index_u2(code);
284         constantPoolHandle cp(Thread::current(), cpool);
285         Method* resolved_method = ConstantPool::method_at_if_loaded(cp, method_index);
286         return (resolved_method == nullptr);
287       }
288       default: ShouldNotReachHere();
289     }
290   } else if (!Bytecodes::must_rewrite(code)) {
291     // might have been reached
292     return false;
293   }
294 
295   // the bytecode might not be rewritten if the method is an accessor, etc.
296   address ientry = method->interpreter_entry();
297   if (ientry != entry_for_kind(AbstractInterpreter::zerolocals) &&
298       ientry != entry_for_kind(AbstractInterpreter::zerolocals_synchronized))
299     return false;  // interpreter does not run this method!
300 
301   // otherwise, we can be sure this bytecode has never been executed
302   return true;
303 }
304 
305 
306 #ifndef PRODUCT
307 void AbstractInterpreter::print_method_kind(MethodKind kind) {
308   switch (kind) {
309     case zerolocals             : tty->print("zerolocals"             ); break;
310     case zerolocals_synchronized: tty->print("zerolocals_synchronized"); break;
311     case native                 : tty->print("native"                 ); break;
312     case native_synchronized    : tty->print("native_synchronized"    ); break;
313     case empty                  : tty->print("empty"                  ); break;
314     case getter                 : tty->print("getter"                 ); break;
315     case setter                 : tty->print("setter"                 ); break;
316     case abstract               : tty->print("abstract"               ); break;
317     case java_lang_math_sin     : tty->print("java_lang_math_sin"     ); break;
318     case java_lang_math_cos     : tty->print("java_lang_math_cos"     ); break;
319     case java_lang_math_tan     : tty->print("java_lang_math_tan"     ); break;
320     case java_lang_math_tanh    : tty->print("java_lang_math_tanh"    ); break;
321     case java_lang_math_abs     : tty->print("java_lang_math_abs"     ); break;
322     case java_lang_math_log     : tty->print("java_lang_math_log"     ); break;
323     case java_lang_math_log10   : tty->print("java_lang_math_log10"   ); break;
324     case java_lang_math_pow     : tty->print("java_lang_math_pow"     ); break;
325     case java_lang_math_exp     : tty->print("java_lang_math_exp"     ); break;
326     case java_lang_math_fmaD    : tty->print("java_lang_math_fmaD"    ); break;
327     case java_lang_math_fmaF    : tty->print("java_lang_math_fmaF"    ); break;
328     case java_lang_math_sqrt    : tty->print("java_lang_math_sqrt"    ); break;
329     case java_lang_math_sqrt_strict           : tty->print("java_lang_math_sqrt_strict"); break;
330     case java_util_zip_CRC32_update           : tty->print("java_util_zip_CRC32_update"); break;
331     case java_util_zip_CRC32_updateBytes      : tty->print("java_util_zip_CRC32_updateBytes"); break;
332     case java_util_zip_CRC32_updateByteBuffer : tty->print("java_util_zip_CRC32_updateByteBuffer"); break;
333     case java_util_zip_CRC32C_updateBytes     : tty->print("java_util_zip_CRC32C_updateBytes"); break;
334     case java_util_zip_CRC32C_updateDirectByteBuffer: tty->print("java_util_zip_CRC32C_updateDirectByteByffer"); break;
335     case java_lang_ref_reference_get          : tty->print("java_lang_ref_reference_get"); break;
336     case java_lang_Thread_currentThread       : tty->print("java_lang_Thread_currentThread"); break;
337     case java_lang_Float_intBitsToFloat       : tty->print("java_lang_Float_intBitsToFloat"); break;
338     case java_lang_Float_floatToRawIntBits    : tty->print("java_lang_Float_floatToRawIntBits"); break;
339     case java_lang_Double_longBitsToDouble    : tty->print("java_lang_Double_longBitsToDouble"); break;
340     case java_lang_Double_doubleToRawLongBits : tty->print("java_lang_Double_doubleToRawLongBits"); break;
341     case java_lang_Float_float16ToFloat       : tty->print("java_lang_Float_float16ToFloat"); break;
342     case java_lang_Float_floatToFloat16       : tty->print("java_lang_Float_floatToFloat16"); break;
343     default:
344       if (kind >= method_handle_invoke_FIRST &&
345           kind <= method_handle_invoke_LAST) {
346         const char* kind_name = vmIntrinsics::name_at(method_handle_intrinsic(kind));
347         if (kind_name[0] == '_')  kind_name = &kind_name[1];  // '_invokeExact' => 'invokeExact'
348         tty->print("method_handle_%s", kind_name);
349         break;
350       }
351       ShouldNotReachHere();
352       break;
353   }
354 }
355 #endif // PRODUCT
356 
357 
358 //------------------------------------------------------------------------------------------------------------------------
359 // Deoptimization support
360 
361 /**
362  * If a deoptimization happens, this function returns the point of next bytecode to continue execution.
363  */
364 address AbstractInterpreter::deopt_continue_after_entry(Method* method, address bcp, int callee_parameters, bool is_top_frame) {
365   assert(method->contains(bcp), "just checkin'");
366 
367   // Get the original and rewritten bytecode.
368   Bytecodes::Code code = Bytecodes::java_code_at(method, bcp);
369   assert(!Interpreter::bytecode_should_reexecute(code), "should not reexecute");
370 
371   const int bci = method->bci_from(bcp);
372 
373   // compute continuation length
374   const int length = Bytecodes::length_at(method, bcp);
375 
376   // compute result type
377   BasicType type = T_ILLEGAL;
378 
379   switch (code) {
380     case Bytecodes::_invokevirtual  :
381     case Bytecodes::_invokespecial  :
382     case Bytecodes::_invokestatic   :
383     case Bytecodes::_invokeinterface: {
384       Thread *thread = Thread::current();
385       ResourceMark rm(thread);
386       methodHandle mh(thread, method);
387       type = Bytecode_invoke(mh, bci).result_type();
388       // since the cache entry might not be initialized:
389       // (NOT needed for the old calling convention)
390       if (!is_top_frame) {
391         int index = Bytes::get_native_u2(bcp+1);
392         method->constants()->cache()->resolved_method_entry_at(index)->set_num_parameters(callee_parameters);
393       }
394       break;
395     }
396 
397    case Bytecodes::_invokedynamic: {
398       Thread *thread = Thread::current();
399       ResourceMark rm(thread);
400       methodHandle mh(thread, method);
401       type = Bytecode_invoke(mh, bci).result_type();
402       // since the cache entry might not be initialized:
403       // (NOT needed for the old calling convention)
404       if (!is_top_frame) {
405         int index = Bytes::get_native_u4(bcp+1);
406         method->constants()->resolved_indy_entry_at(index)->set_num_parameters(callee_parameters);
407       }
408       break;
409     }
410 
411     case Bytecodes::_ldc   :
412     case Bytecodes::_ldc_w : // fall through
413     case Bytecodes::_ldc2_w:
414       {
415         Thread *thread = Thread::current();
416         ResourceMark rm(thread);
417         methodHandle mh(thread, method);
418         type = Bytecode_loadconstant(mh, bci).result_type();
419         break;
420       }
421 
422     default:
423       type = Bytecodes::result_type(code);
424       break;
425   }
426 
427   // return entry point for computed continuation state & bytecode length
428   return
429     is_top_frame
430     ? Interpreter::deopt_entry (as_TosState(type), length)
431     : Interpreter::return_entry(as_TosState(type), length, code);
432 }
433 
434 // If deoptimization happens, this function returns the point where the interpreter reexecutes
435 // the bytecode.
436 // Note: Bytecodes::_athrow is a special case in that it does not return
437 //       Interpreter::deopt_entry(vtos, 0) like others
438 address AbstractInterpreter::deopt_reexecute_entry(Method* method, address bcp) {
439   assert(method->contains(bcp), "just checkin'");
440   Bytecodes::Code code   = Bytecodes::java_code_at(method, bcp);
441 #if defined(COMPILER1) || INCLUDE_JVMCI
442   if(code == Bytecodes::_athrow ) {
443     return Interpreter::rethrow_exception_entry();
444   }
445 #endif /* COMPILER1 || INCLUDE_JVMCI */
446   return Interpreter::deopt_entry(vtos, 0);
447 }
448 
449 // If deoptimization happens, the interpreter should reexecute these bytecodes.
450 // This function mainly helps the compilers to set up the reexecute bit.
451 bool AbstractInterpreter::bytecode_should_reexecute(Bytecodes::Code code) {
452   switch (code) {
453     case Bytecodes::_lookupswitch:
454     case Bytecodes::_tableswitch:
455     case Bytecodes::_fast_binaryswitch:
456     case Bytecodes::_fast_linearswitch:
457     // recompute conditional expression folded into _if<cond>
458     case Bytecodes::_lcmp      :
459     case Bytecodes::_fcmpl     :
460     case Bytecodes::_fcmpg     :
461     case Bytecodes::_dcmpl     :
462     case Bytecodes::_dcmpg     :
463     case Bytecodes::_ifnull    :
464     case Bytecodes::_ifnonnull :
465     case Bytecodes::_goto      :
466     case Bytecodes::_goto_w    :
467     case Bytecodes::_ifeq      :
468     case Bytecodes::_ifne      :
469     case Bytecodes::_iflt      :
470     case Bytecodes::_ifge      :
471     case Bytecodes::_ifgt      :
472     case Bytecodes::_ifle      :
473     case Bytecodes::_if_icmpeq :
474     case Bytecodes::_if_icmpne :
475     case Bytecodes::_if_icmplt :
476     case Bytecodes::_if_icmpge :
477     case Bytecodes::_if_icmpgt :
478     case Bytecodes::_if_icmple :
479     case Bytecodes::_if_acmpeq :
480     case Bytecodes::_if_acmpne :
481     // special cases
482     case Bytecodes::_getfield  :
483     case Bytecodes::_putfield  :
484     case Bytecodes::_getstatic :
485     case Bytecodes::_putstatic :
486     case Bytecodes::_aastore   :
487 #ifdef COMPILER1
488     //special case of reexecution
489     case Bytecodes::_athrow    :
490 #endif
491       return true;
492 
493     default:
494       return false;
495   }
496 }
497 
498 void AbstractInterpreter::initialize_method_handle_entries() {
499   // method handle entry kinds are generated later in MethodHandlesAdapterGenerator::generate:
500   for (int i = method_handle_invoke_FIRST; i <= method_handle_invoke_LAST; i++) {
501     MethodKind kind = (MethodKind) i;
502     _entry_table[kind] = _entry_table[Interpreter::abstract];
503   }
504 }