< prev index next >

src/hotspot/share/runtime/sharedRuntime.cpp

Print this page

  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/nmethod.inline.hpp"
  38 #include "code/scopeDesc.hpp"
  39 #include "code/vtableStubs.hpp"
  40 #include "compiler/abstractCompiler.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/interpreter.hpp"
  46 #include "interpreter/interpreterRuntime.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"

  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "metaprogramming/primitiveConversions.hpp"



  53 #include "oops/klass.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"

  56 #include "oops/oop.inline.hpp"
  57 #include "prims/forte.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "prims/jvmtiThreadState.hpp"
  60 #include "prims/methodHandles.hpp"
  61 #include "prims/nativeLookup.hpp"
  62 #include "runtime/arguments.hpp"
  63 #include "runtime/atomicAccess.hpp"
  64 #include "runtime/basicLock.inline.hpp"
  65 #include "runtime/frame.inline.hpp"
  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/init.hpp"
  68 #include "runtime/interfaceSupport.inline.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/jniHandles.inline.hpp"
  72 #include "runtime/osThread.hpp"
  73 #include "runtime/perfData.hpp"
  74 #include "runtime/sharedRuntime.hpp"

  75 #include "runtime/stackWatermarkSet.hpp"
  76 #include "runtime/stubRoutines.hpp"
  77 #include "runtime/synchronizer.hpp"
  78 #include "runtime/timerTrace.hpp"
  79 #include "runtime/vframe.inline.hpp"
  80 #include "runtime/vframeArray.hpp"
  81 #include "runtime/vm_version.hpp"
  82 #include "utilities/copy.hpp"
  83 #include "utilities/dtrace.hpp"
  84 #include "utilities/events.hpp"
  85 #include "utilities/exceptions.hpp"
  86 #include "utilities/globalDefinitions.hpp"
  87 #include "utilities/hashTable.hpp"
  88 #include "utilities/macros.hpp"
  89 #include "utilities/xmlstream.hpp"
  90 #ifdef COMPILER1
  91 #include "c1/c1_Runtime1.hpp"
  92 #endif
  93 #ifdef COMPILER2
  94 #include "opto/runtime.hpp"

 105   type*       SharedRuntime::BLOB_FIELD_NAME(name);
 106   SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
 107 #undef SHARED_STUB_FIELD_DEFINE
 108 
 109 nmethod*            SharedRuntime::_cont_doYield_stub;
 110 
 111 #if 0
 112 // TODO tweak global stub name generation to match this
 113 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
 114 const char *SharedRuntime::_stub_names[] = {
 115   SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
 116 };
 117 #endif
 118 
 119 //----------------------------generate_stubs-----------------------------------
 120 void SharedRuntime::generate_initial_stubs() {
 121   // Build this early so it's available for the interpreter.
 122   _throw_StackOverflowError_blob =
 123     generate_throw_exception(StubId::shared_throw_StackOverflowError_id,
 124                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));





 125 }
 126 
 127 void SharedRuntime::generate_stubs() {
 128   _wrong_method_blob =
 129     generate_resolve_blob(StubId::shared_wrong_method_id,
 130                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
 131   _wrong_method_abstract_blob =
 132     generate_resolve_blob(StubId::shared_wrong_method_abstract_id,
 133                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
 134   _ic_miss_blob =
 135     generate_resolve_blob(StubId::shared_ic_miss_id,
 136                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
 137   _resolve_opt_virtual_call_blob =
 138     generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id,
 139                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
 140   _resolve_virtual_call_blob =
 141     generate_resolve_blob(StubId::shared_resolve_virtual_call_id,
 142                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
 143   _resolve_static_call_blob =
 144     generate_resolve_blob(StubId::shared_resolve_static_call_id,

1167 // for a call current in progress, i.e., arguments has been pushed on stack
1168 // but callee has not been invoked yet.  Caller frame must be compiled.
1169 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1170                                               CallInfo& callinfo, TRAPS) {
1171   Handle receiver;
1172   Handle nullHandle;  // create a handy null handle for exception returns
1173   JavaThread* current = THREAD;
1174 
1175   assert(!vfst.at_end(), "Java frame must exist");
1176 
1177   // Find caller and bci from vframe
1178   methodHandle caller(current, vfst.method());
1179   int          bci   = vfst.bci();
1180 
1181   if (caller->is_continuation_enter_intrinsic()) {
1182     bc = Bytecodes::_invokestatic;
1183     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1184     return receiver;
1185   }
1186 
















1187   Bytecode_invoke bytecode(caller, bci);
1188   int bytecode_index = bytecode.index();
1189   bc = bytecode.invoke_code();
1190 
1191   methodHandle attached_method(current, extract_attached_method(vfst));
1192   if (attached_method.not_null()) {
1193     Method* callee = bytecode.static_target(CHECK_NH);
1194     vmIntrinsics::ID id = callee->intrinsic_id();
1195     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1196     // it attaches statically resolved method to the call site.
1197     if (MethodHandles::is_signature_polymorphic(id) &&
1198         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1199       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1200 
1201       // Adjust invocation mode according to the attached method.
1202       switch (bc) {
1203         case Bytecodes::_invokevirtual:
1204           if (attached_method->method_holder()->is_interface()) {
1205             bc = Bytecodes::_invokeinterface;
1206           }
1207           break;
1208         case Bytecodes::_invokeinterface:
1209           if (!attached_method->method_holder()->is_interface()) {
1210             bc = Bytecodes::_invokevirtual;
1211           }
1212           break;
1213         case Bytecodes::_invokehandle:
1214           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1215             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1216                                               : Bytecodes::_invokevirtual;
1217           }
1218           break;
1219         default:
1220           break;
1221       }






1222     }
1223   }
1224 
1225   assert(bc != Bytecodes::_illegal, "not initialized");
1226 
1227   bool has_receiver = bc != Bytecodes::_invokestatic &&
1228                       bc != Bytecodes::_invokedynamic &&
1229                       bc != Bytecodes::_invokehandle;

1230 
1231   // Find receiver for non-static call
1232   if (has_receiver) {
1233     // This register map must be update since we need to find the receiver for
1234     // compiled frames. The receiver might be in a register.
1235     RegisterMap reg_map2(current,
1236                          RegisterMap::UpdateMap::include,
1237                          RegisterMap::ProcessFrames::include,
1238                          RegisterMap::WalkContinuation::skip);
1239     frame stubFrame   = current->last_frame();
1240     // Caller-frame is a compiled frame
1241     frame callerFrame = stubFrame.sender(&reg_map2);
1242 
1243     if (attached_method.is_null()) {
1244       Method* callee = bytecode.static_target(CHECK_NH);

1245       if (callee == nullptr) {
1246         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1247       }
1248     }
1249 
1250     // Retrieve from a compiled argument list
1251     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1252     assert(oopDesc::is_oop_or_null(receiver()), "");
1253 
1254     if (receiver.is_null()) {
1255       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);










1256     }
1257   }
1258 
1259   // Resolve method
1260   if (attached_method.not_null()) {
1261     // Parameterized by attached method.
1262     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1263   } else {
1264     // Parameterized by bytecode.
1265     constantPoolHandle constants(current, caller->constants());
1266     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1267   }
1268 
1269 #ifdef ASSERT
1270   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1271   if (has_receiver) {
1272     assert(receiver.not_null(), "should have thrown exception");
1273     Klass* receiver_klass = receiver->klass();
1274     Klass* rk = nullptr;
1275     if (attached_method.not_null()) {
1276       // In case there's resolved method attached, use its holder during the check.
1277       rk = attached_method->method_holder();
1278     } else {
1279       // Klass is already loaded.
1280       constantPoolHandle constants(current, caller->constants());
1281       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1282     }
1283     Klass* static_receiver_klass = rk;
1284     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1285            "actual receiver must be subclass of static receiver klass");
1286     if (receiver_klass->is_instance_klass()) {
1287       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1288         tty->print_cr("ERROR: Klass not yet initialized!!");
1289         receiver_klass->print();
1290       }
1291       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1292     }
1293   }
1294 #endif
1295 
1296   return receiver;
1297 }
1298 
1299 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1300   JavaThread* current = THREAD;
1301   ResourceMark rm(current);
1302   // We need first to check if any Java activations (compiled, interpreted)
1303   // exist on the stack since last JavaCall.  If not, we need
1304   // to get the target method from the JavaCall wrapper.
1305   vframeStream vfst(current, true);  // Do not skip any javaCalls
1306   methodHandle callee_method;
1307   if (vfst.at_end()) {
1308     // No Java frames were found on stack since we did the JavaCall.
1309     // Hence the stack can only contain an entry_frame.  We need to
1310     // find the target method from the stub frame.
1311     RegisterMap reg_map(current,
1312                         RegisterMap::UpdateMap::skip,
1313                         RegisterMap::ProcessFrames::include,
1314                         RegisterMap::WalkContinuation::skip);
1315     frame fr = current->last_frame();
1316     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1317     fr = fr.sender(&reg_map);
1318     assert(fr.is_entry_frame(), "must be");
1319     // fr is now pointing to the entry frame.
1320     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1321   } else {
1322     Bytecodes::Code bc;
1323     CallInfo callinfo;
1324     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));




1325     callee_method = methodHandle(current, callinfo.selected_method());
1326   }
1327   assert(callee_method()->is_method(), "must be");
1328   return callee_method;
1329 }
1330 
1331 // Resolves a call.
1332 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1333   JavaThread* current = THREAD;
1334   ResourceMark rm(current);
1335   RegisterMap cbl_map(current,
1336                       RegisterMap::UpdateMap::skip,
1337                       RegisterMap::ProcessFrames::include,
1338                       RegisterMap::WalkContinuation::skip);
1339   frame caller_frame = current->last_frame().sender(&cbl_map);
1340 
1341   CodeBlob* caller_cb = caller_frame.cb();
1342   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1343   nmethod* caller_nm = caller_cb->as_nmethod();
1344 
1345   // determine call info & receiver
1346   // note: a) receiver is null for static calls
1347   //       b) an exception is thrown if receiver is null for non-static calls
1348   CallInfo call_info;
1349   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1350   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1351 
1352   NoSafepointVerifier nsv;
1353 
1354   methodHandle callee_method(current, call_info.selected_method());





1355 
1356   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1357          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1358          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1359          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1360          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1361 
1362   assert(!caller_nm->is_unloading(), "It should not be unloading");
1363 
1364 #ifndef PRODUCT
1365   // tracing/debugging/statistics
1366   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1367                  (is_virtual) ? (&_resolve_virtual_ctr) :
1368                                 (&_resolve_static_ctr);
1369   AtomicAccess::inc(addr);
1370 
1371   if (TraceCallFixup) {
1372     ResourceMark rm(current);
1373     tty->print("resolving %s%s (%s) call to",
1374                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1375                Bytecodes::name(invoke_code));
1376     callee_method->print_short_name(tty);
1377     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1378                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1379   }
1380 #endif
1381 
1382   if (invoke_code == Bytecodes::_invokestatic) {
1383     assert(callee_method->method_holder()->is_initialized() ||
1384            callee_method->method_holder()->is_reentrant_initialization(current),
1385            "invalid class initialization state for invoke_static");
1386     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1387       // In order to keep class initialization check, do not patch call
1388       // site for static call when the class is not fully initialized.
1389       // Proper check is enforced by call site re-resolution on every invocation.
1390       //
1391       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1392       // explicit class initialization check is put in nmethod entry (VEP).
1393       assert(callee_method->method_holder()->is_linked(), "must be");
1394       return callee_method;
1395     }
1396   }
1397 
1398 
1399   // JSR 292 key invariant:
1400   // If the resolved method is a MethodHandle invoke target, the call
1401   // site must be a MethodHandle call site, because the lambda form might tail-call
1402   // leaving the stack in a state unknown to either caller or callee
1403 
1404   // Compute entry points. The computation of the entry points is independent of
1405   // patching the call.
1406 
1407   // Make sure the callee nmethod does not get deoptimized and removed before
1408   // we are done patching the code.
1409 
1410 
1411   CompiledICLocker ml(caller_nm);
1412   if (is_virtual && !is_optimized) {
1413     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1414     inline_cache->update(&call_info, receiver->klass());
1415   } else {
1416     // Callsite is a direct call - set it to the destination method
1417     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1418     callsite->set(callee_method);
1419   }
1420 
1421   return callee_method;
1422 }
1423 
1424 // Inline caches exist only in compiled code
1425 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1426 #ifdef ASSERT
1427   RegisterMap reg_map(current,
1428                       RegisterMap::UpdateMap::skip,
1429                       RegisterMap::ProcessFrames::include,
1430                       RegisterMap::WalkContinuation::skip);
1431   frame stub_frame = current->last_frame();
1432   assert(stub_frame.is_runtime_frame(), "sanity check");
1433   frame caller_frame = stub_frame.sender(&reg_map);
1434   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1435 #endif /* ASSERT */
1436 
1437   methodHandle callee_method;

1438   JRT_BLOCK
1439     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1440     // Return Method* through TLS
1441     current->set_vm_result_metadata(callee_method());
1442   JRT_BLOCK_END
1443   // return compiled code entry point after potential safepoints
1444   return get_resolved_entry(current, callee_method);
1445 JRT_END
1446 
1447 
1448 // Handle call site that has been made non-entrant
1449 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1450   // 6243940 We might end up in here if the callee is deoptimized
1451   // as we race to call it.  We don't want to take a safepoint if
1452   // the caller was interpreted because the caller frame will look
1453   // interpreted to the stack walkers and arguments are now
1454   // "compiled" so it is much better to make this transition
1455   // invisible to the stack walking code. The i2c path will
1456   // place the callee method in the callee_target. It is stashed
1457   // there because if we try and find the callee by normal means a
1458   // safepoint is possible and have trouble gc'ing the compiled args.
1459   RegisterMap reg_map(current,
1460                       RegisterMap::UpdateMap::skip,
1461                       RegisterMap::ProcessFrames::include,
1462                       RegisterMap::WalkContinuation::skip);
1463   frame stub_frame = current->last_frame();
1464   assert(stub_frame.is_runtime_frame(), "sanity check");
1465   frame caller_frame = stub_frame.sender(&reg_map);
1466 
1467   if (caller_frame.is_interpreted_frame() ||
1468       caller_frame.is_entry_frame() ||
1469       caller_frame.is_upcall_stub_frame()) {
1470     Method* callee = current->callee_target();
1471     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1472     current->set_vm_result_metadata(callee);
1473     current->set_callee_target(nullptr);
1474     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1475       // Bypass class initialization checks in c2i when caller is in native.
1476       // JNI calls to static methods don't have class initialization checks.
1477       // Fast class initialization checks are present in c2i adapters and call into
1478       // SharedRuntime::handle_wrong_method() on the slow path.
1479       //
1480       // JVM upcalls may land here as well, but there's a proper check present in
1481       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1482       // so bypassing it in c2i adapter is benign.
1483       return callee->get_c2i_no_clinit_check_entry();
1484     } else {
1485       return callee->get_c2i_entry();




1486     }
1487   }
1488 
1489   // Must be compiled to compiled path which is safe to stackwalk
1490   methodHandle callee_method;



1491   JRT_BLOCK
1492     // Force resolving of caller (if we called from compiled frame)
1493     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1494     current->set_vm_result_metadata(callee_method());
1495   JRT_BLOCK_END
1496   // return compiled code entry point after potential safepoints
1497   return get_resolved_entry(current, callee_method);
1498 JRT_END
1499 
1500 // Handle abstract method call
1501 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1502   // Verbose error message for AbstractMethodError.
1503   // Get the called method from the invoke bytecode.
1504   vframeStream vfst(current, true);
1505   assert(!vfst.at_end(), "Java frame must exist");
1506   methodHandle caller(current, vfst.method());
1507   Bytecode_invoke invoke(caller, vfst.bci());
1508   DEBUG_ONLY( invoke.verify(); )
1509 
1510   // Find the compiled caller frame.
1511   RegisterMap reg_map(current,
1512                       RegisterMap::UpdateMap::include,
1513                       RegisterMap::ProcessFrames::include,
1514                       RegisterMap::WalkContinuation::skip);
1515   frame stubFrame = current->last_frame();
1516   assert(stubFrame.is_runtime_frame(), "must be");
1517   frame callerFrame = stubFrame.sender(&reg_map);
1518   assert(callerFrame.is_compiled_frame(), "must be");
1519 
1520   // Install exception and return forward entry.
1521   address res = SharedRuntime::throw_AbstractMethodError_entry();
1522   JRT_BLOCK
1523     methodHandle callee(current, invoke.static_target(current));
1524     if (!callee.is_null()) {
1525       oop recv = callerFrame.retrieve_receiver(&reg_map);
1526       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1527       res = StubRoutines::forward_exception_entry();
1528       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1529     }
1530   JRT_BLOCK_END
1531   return res;
1532 JRT_END
1533 
1534 // return verified_code_entry if interp_only_mode is not set for the current thread;
1535 // otherwise return c2i entry.
1536 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1537   if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1538     // In interp_only_mode we need to go to the interpreted entry
1539     // The c2i won't patch in this mode -- see fixup_callers_callsite
1540     return callee_method->get_c2i_entry();




















1541   }
1542   assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1543   return callee_method->verified_code_entry();
1544 }
1545 
1546 // resolve a static call and patch code
1547 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1548   methodHandle callee_method;

1549   bool enter_special = false;
1550   JRT_BLOCK
1551     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1552     current->set_vm_result_metadata(callee_method());
1553   JRT_BLOCK_END
1554   // return compiled code entry point after potential safepoints
1555   return get_resolved_entry(current, callee_method);
1556 JRT_END
1557 
1558 // resolve virtual call and update inline cache to monomorphic
1559 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1560   methodHandle callee_method;

1561   JRT_BLOCK
1562     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1563     current->set_vm_result_metadata(callee_method());
1564   JRT_BLOCK_END
1565   // return compiled code entry point after potential safepoints
1566   return get_resolved_entry(current, callee_method);
1567 JRT_END
1568 
1569 
1570 // Resolve a virtual call that can be statically bound (e.g., always
1571 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1572 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1573   methodHandle callee_method;

1574   JRT_BLOCK
1575     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1576     current->set_vm_result_metadata(callee_method());
1577   JRT_BLOCK_END
1578   // return compiled code entry point after potential safepoints
1579   return get_resolved_entry(current, callee_method);
1580 JRT_END
1581 
1582 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1583   JavaThread* current = THREAD;
1584   ResourceMark rm(current);
1585   CallInfo call_info;
1586   Bytecodes::Code bc;
1587 
1588   // receiver is null for static calls. An exception is thrown for null
1589   // receivers for non-static calls
1590   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1591 
1592   methodHandle callee_method(current, call_info.selected_method());
1593 
1594 #ifndef PRODUCT
1595   AtomicAccess::inc(&_ic_miss_ctr);
1596 
1597   // Statistics & Tracing
1598   if (TraceCallFixup) {
1599     ResourceMark rm(current);
1600     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1601     callee_method->print_short_name(tty);
1602     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1603   }
1604 
1605   if (ICMissHistogram) {
1606     MutexLocker m(VMStatistic_lock);
1607     RegisterMap reg_map(current,
1608                         RegisterMap::UpdateMap::skip,
1609                         RegisterMap::ProcessFrames::include,
1610                         RegisterMap::WalkContinuation::skip);
1611     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1612     // produce statistics under the lock
1613     trace_ic_miss(f.pc());
1614   }
1615 #endif
1616 
1617   // install an event collector so that when a vtable stub is created the
1618   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1619   // event can't be posted when the stub is created as locks are held
1620   // - instead the event will be deferred until the event collector goes
1621   // out of scope.
1622   JvmtiDynamicCodeEventCollector event_collector;
1623 
1624   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1625   RegisterMap reg_map(current,
1626                       RegisterMap::UpdateMap::skip,
1627                       RegisterMap::ProcessFrames::include,
1628                       RegisterMap::WalkContinuation::skip);
1629   frame caller_frame = current->last_frame().sender(&reg_map);
1630   CodeBlob* cb = caller_frame.cb();
1631   nmethod* caller_nm = cb->as_nmethod();




1632 
1633   CompiledICLocker ml(caller_nm);
1634   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1635   inline_cache->update(&call_info, receiver()->klass());
1636 
1637   return callee_method;
1638 }
1639 
1640 //
1641 // Resets a call-site in compiled code so it will get resolved again.
1642 // This routines handles both virtual call sites, optimized virtual call
1643 // sites, and static call sites. Typically used to change a call sites
1644 // destination from compiled to interpreted.
1645 //
1646 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1647   JavaThread* current = THREAD;
1648   ResourceMark rm(current);
1649   RegisterMap reg_map(current,
1650                       RegisterMap::UpdateMap::skip,
1651                       RegisterMap::ProcessFrames::include,
1652                       RegisterMap::WalkContinuation::skip);
1653   frame stub_frame = current->last_frame();
1654   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1655   frame caller = stub_frame.sender(&reg_map);
1656 
1657   // Do nothing if the frame isn't a live compiled frame.
1658   // nmethod could be deoptimized by the time we get here
1659   // so no update to the caller is needed.
1660 
1661   if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1662       (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1663 













1664     address pc = caller.pc();
1665 
1666     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1667     assert(caller_nm != nullptr, "did not find caller nmethod");
1668 
1669     // Default call_addr is the location of the "basic" call.
1670     // Determine the address of the call we a reresolving. With
1671     // Inline Caches we will always find a recognizable call.
1672     // With Inline Caches disabled we may or may not find a
1673     // recognizable call. We will always find a call for static
1674     // calls and for optimized virtual calls. For vanilla virtual
1675     // calls it depends on the state of the UseInlineCaches switch.
1676     //
1677     // With Inline Caches disabled we can get here for a virtual call
1678     // for two reasons:
1679     //   1 - calling an abstract method. The vtable for abstract methods
1680     //       will run us thru handle_wrong_method and we will eventually
1681     //       end up in the interpreter to throw the ame.
1682     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1683     //       call and between the time we fetch the entry address and
1684     //       we jump to it the target gets deoptimized. Similar to 1
1685     //       we will wind up in the interprter (thru a c2i with c2).
1686     //
1687     CompiledICLocker ml(caller_nm);
1688     address call_addr = caller_nm->call_instruction_address(pc);
1689 
1690     if (call_addr != nullptr) {
1691       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1692       // bytes back in the instruction stream so we must also check for reloc info.
1693       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1694       bool ret = iter.next(); // Get item
1695       if (ret) {

1696         switch (iter.type()) {
1697           case relocInfo::static_call_type:

1698           case relocInfo::opt_virtual_call_type: {
1699             CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1700             cdc->set_to_clean();



1701             break;
1702           }
1703 
1704           case relocInfo::virtual_call_type: {
1705             // compiled, dispatched call (which used to call an interpreted method)
1706             CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1707             inline_cache->set_to_clean();


1708             break;
1709           }
1710           default:
1711             break;
1712         }
1713       }
1714     }
1715   }
1716 
1717   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1718 
1719 
1720 #ifndef PRODUCT
1721   AtomicAccess::inc(&_wrong_method_ctr);
1722 
1723   if (TraceCallFixup) {
1724     ResourceMark rm(current);
1725     tty->print("handle_wrong_method reresolving call to");
1726     callee_method->print_short_name(tty);
1727     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1728   }
1729 #endif
1730 
1731   return callee_method;
1732 }
1733 
1734 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1735   // The faulting unsafe accesses should be changed to throw the error
1736   // synchronously instead. Meanwhile the faulting instruction will be
1737   // skipped over (effectively turning it into a no-op) and an
1738   // asynchronous exception will be raised which the thread will
1739   // handle at a later point. If the instruction is a load it will
1740   // return garbage.
1741 
1742   // Request an async exception.
1743   thread->set_pending_unsafe_access_error();
1744 
1745   // Return address of next instruction to execute.

1911   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
1912 
1913   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
1914   if (message == nullptr) {
1915     // Shouldn't happen, but don't cause even more problems if it does
1916     message = const_cast<char*>(caster_klass->external_name());
1917   } else {
1918     jio_snprintf(message,
1919                  msglen,
1920                  "class %s cannot be cast to class %s (%s%s%s)",
1921                  caster_name,
1922                  target_name,
1923                  caster_klass_description,
1924                  klass_separator,
1925                  target_klass_description
1926                  );
1927   }
1928   return message;
1929 }
1930 















1931 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1932   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
1933 JRT_END
1934 
1935 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1936   if (!SafepointSynchronize::is_synchronizing()) {
1937     // Only try quick_enter() if we're not trying to reach a safepoint
1938     // so that the calling thread reaches the safepoint more quickly.
1939     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
1940       return;
1941     }
1942   }
1943   // NO_ASYNC required because an async exception on the state transition destructor
1944   // would leave you with the lock held and it would never be released.
1945   // The normal monitorenter NullPointerException is thrown without acquiring a lock
1946   // and the model is that an exception implies the method failed.
1947   JRT_BLOCK_NO_ASYNC
1948   Handle h_obj(THREAD, obj);
1949   ObjectSynchronizer::enter(h_obj, lock, current);
1950   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2144   tty->print_cr("Note 1: counter updates are not MT-safe.");
2145   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2146   tty->print_cr("        %% in nested categories are relative to their category");
2147   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2148   tty->cr();
2149 
2150   MethodArityHistogram h;
2151 }
2152 #endif
2153 
2154 #ifndef PRODUCT
2155 static int _lookups; // number of calls to lookup
2156 static int _equals;  // number of buckets checked with matching hash
2157 static int _archived_hits; // number of successful lookups in archived table
2158 static int _runtime_hits;  // number of successful lookups in runtime table
2159 #endif
2160 
2161 // A simple wrapper class around the calling convention information
2162 // that allows sharing of adapters for the same calling convention.
2163 class AdapterFingerPrint : public MetaspaceObj {
2164  private:
2165   enum {
2166     _basic_type_bits = 4,
2167     _basic_type_mask = right_n_bits(_basic_type_bits),
2168     _basic_types_per_int = BitsPerInt / _basic_type_bits,

























2169   };
2170   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2171   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2172 
2173   int _length;


2174 
2175   static int data_offset() { return sizeof(AdapterFingerPrint); }
2176   int* data_pointer() {
2177     return (int*)((address)this + data_offset());






2178   }
2179 
2180   // Private construtor. Use allocate() to get an instance.
2181   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) {
2182     int* data = data_pointer();
2183     // Pack the BasicTypes with 8 per int
2184     assert(len == length(total_args_passed), "sanity");
2185     _length = len;
2186     int sig_index = 0;
2187     for (int index = 0; index < _length; index++) {
2188       int value = 0;
2189       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2190         int bt = adapter_encoding(sig_bt[sig_index++]);
2191         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2192         value = (value << _basic_type_bits) | bt;










2193       }
2194       data[index] = value;


2195     }

2196   }
2197 
2198   // Call deallocate instead
2199   ~AdapterFingerPrint() {
2200     ShouldNotCallThis();
2201   }
2202 
2203   static int length(int total_args) {
2204     return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int;
2205   }
2206 
2207   static int compute_size_in_words(int len) {
2208     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int)));
2209   }
2210 
2211   // Remap BasicTypes that are handled equivalently by the adapters.
2212   // These are correct for the current system but someday it might be
2213   // necessary to make this mapping platform dependent.
2214   static int adapter_encoding(BasicType in) {
2215     switch (in) {
2216       case T_BOOLEAN:
2217       case T_BYTE:
2218       case T_SHORT:
2219       case T_CHAR:
2220         // There are all promoted to T_INT in the calling convention
2221         return T_INT;
2222 
2223       case T_OBJECT:
2224       case T_ARRAY:
2225         // In other words, we assume that any register good enough for
2226         // an int or long is good enough for a managed pointer.
2227 #ifdef _LP64
2228         return T_LONG;
2229 #else
2230         return T_INT;
2231 #endif
2232 
2233       case T_INT:
2234       case T_LONG:
2235       case T_FLOAT:
2236       case T_DOUBLE:
2237       case T_VOID:
2238         return in;
2239 
2240       default:
2241         ShouldNotReachHere();
2242         return T_CONFLICT;
2243     }
2244   }
2245 
2246   void* operator new(size_t size, size_t fp_size) throw() {
2247     assert(fp_size >= size, "sanity check");
2248     void* p = AllocateHeap(fp_size, mtCode);
2249     memset(p, 0, fp_size);
2250     return p;
2251   }
2252 

2253   template<typename Function>
2254   void iterate_args(Function function) {
2255     for (int i = 0; i < length(); i++) {
2256       unsigned val = (unsigned)value(i);
2257       // args are packed so that first/lower arguments are in the highest
2258       // bits of each int value, so iterate from highest to the lowest
2259       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2260         unsigned v = (val >> j) & _basic_type_mask;
2261         if (v == 0) {
2262           continue;
2263         }
2264         function(v);
2265       }
2266     }
2267   }
2268 
2269  public:
2270   static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2271     int len = length(total_args_passed);
2272     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2273     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len);
2274     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2275     return afp;
2276   }
2277 
2278   static void deallocate(AdapterFingerPrint* fp) {
2279     FreeHeap(fp);
2280   }
2281 
2282   int value(int index) {
2283     int* data = data_pointer();
2284     return data[index];
2285   }
2286 
2287   int length() {
2288     return _length;
2289   }
2290 
2291   unsigned int compute_hash() {
2292     int hash = 0;
2293     for (int i = 0; i < length(); i++) {
2294       int v = value(i);
2295       //Add arithmetic operation to the hash, like +3 to improve hashing
2296       hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2297     }
2298     return (unsigned int)hash;
2299   }
2300 
2301   const char* as_string() {
2302     stringStream st;
2303     st.print("0x");





2304     for (int i = 0; i < length(); i++) {
2305       st.print("%x", value(i));


2306     }

2307     return st.as_string();
2308   }
2309 
2310   const char* as_basic_args_string() {
2311     stringStream st;
2312     bool long_prev = false;
2313     iterate_args([&] (int arg) {
2314       if (long_prev) {
2315         long_prev = false;
2316         if (arg == T_VOID) {
2317           st.print("J");
2318         } else {
2319           st.print("L");
2320         }
2321       }
2322       switch (arg) {
2323         case T_INT:    st.print("I");    break;
2324         case T_LONG:   long_prev = true; break;
2325         case T_FLOAT:  st.print("F");    break;
2326         case T_DOUBLE: st.print("D");    break;
2327         case T_VOID:   break;
2328         default: ShouldNotReachHere();
2329       }
2330     });
2331     if (long_prev) {
2332       st.print("L");
2333     }
2334     return st.as_string();
2335   }
2336 
2337   BasicType* as_basic_type(int& nargs) {
2338     nargs = 0;
2339     GrowableArray<BasicType> btarray;
2340     bool long_prev = false;
2341 
2342     iterate_args([&] (int arg) {
2343       if (long_prev) {
2344         long_prev = false;
2345         if (arg == T_VOID) {
2346           btarray.append(T_LONG);
2347         } else {
2348           btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2349         }
2350       }
2351       switch (arg) {
2352         case T_INT: // fallthrough
2353         case T_FLOAT: // fallthrough
2354         case T_DOUBLE:
2355         case T_VOID:
2356           btarray.append((BasicType)arg);
2357           break;
2358         case T_LONG:
2359           long_prev = true;
2360           break;
2361         default: ShouldNotReachHere();
2362       }
2363     });
2364 
2365     if (long_prev) {
2366       btarray.append(T_OBJECT);
2367     }
2368 
2369     nargs = btarray.length();
2370     BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2371     int index = 0;
2372     GrowableArrayIterator<BasicType> iter = btarray.begin();
2373     while (iter != btarray.end()) {
2374       sig_bt[index++] = *iter;
2375       ++iter;
2376     }
2377     assert(index == btarray.length(), "sanity check");
2378 #ifdef ASSERT
2379     {
2380       AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2381       assert(this->equals(compare_fp), "sanity check");
2382       AdapterFingerPrint::deallocate(compare_fp);
2383     }
2384 #endif
2385     return sig_bt;
2386   }
2387 
2388   bool equals(AdapterFingerPrint* other) {
2389     if (other->_length != _length) {


2390       return false;
2391     } else {
2392       for (int i = 0; i < _length; i++) {
2393         if (value(i) != other->value(i)) {
2394           return false;
2395         }
2396       }
2397     }
2398     return true;
2399   }
2400 
2401   // methods required by virtue of being a MetaspaceObj
2402   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2403   int size() const { return compute_size_in_words(_length); }
2404   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2405 
2406   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2407     NOT_PRODUCT(_equals++);
2408     return fp1->equals(fp2);
2409   }
2410 
2411   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2412     return fp->compute_hash();
2413   }

2416 #if INCLUDE_CDS
2417 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2418   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2419 }
2420 
2421 class ArchivedAdapterTable : public OffsetCompactHashtable<
2422   AdapterFingerPrint*,
2423   AdapterHandlerEntry*,
2424   adapter_fp_equals_compact_hashtable_entry> {};
2425 #endif // INCLUDE_CDS
2426 
2427 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2428 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2429                   AnyObj::C_HEAP, mtCode,
2430                   AdapterFingerPrint::compute_hash,
2431                   AdapterFingerPrint::equals>;
2432 static AdapterHandlerTable* _adapter_handler_table;
2433 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2434 
2435 // Find a entry with the same fingerprint if it exists
2436 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2437   NOT_PRODUCT(_lookups++);
2438   assert_lock_strong(AdapterHandlerLibrary_lock);
2439   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2440   AdapterHandlerEntry* entry = nullptr;
2441 #if INCLUDE_CDS
2442   // if we are building the archive then the archived adapter table is
2443   // not valid and we need to use the ones added to the runtime table
2444   if (AOTCodeCache::is_using_adapter()) {
2445     // Search archived table first. It is read-only table so can be searched without lock
2446     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2447 #ifndef PRODUCT
2448     if (entry != nullptr) {
2449       _archived_hits++;
2450     }
2451 #endif
2452   }
2453 #endif // INCLUDE_CDS
2454   if (entry == nullptr) {
2455     assert_lock_strong(AdapterHandlerLibrary_lock);
2456     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2457     if (entry_p != nullptr) {
2458       entry = *entry_p;
2459       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2476   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2477   ts.print(tty, "AdapterHandlerTable");
2478   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2479                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2480   int total_hits = _archived_hits + _runtime_hits;
2481   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2482                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2483 }
2484 #endif
2485 
2486 // ---------------------------------------------------------------------------
2487 // Implementation of AdapterHandlerLibrary
2488 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2489 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2490 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2491 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2492 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2493 #if INCLUDE_CDS
2494 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2495 #endif // INCLUDE_CDS
2496 static const int AdapterHandlerLibrary_size = 16*K;
2497 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2498 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2499 
2500 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2501   assert(_buffer != nullptr, "should be initialized");
2502   return _buffer;
2503 }
2504 
2505 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2506   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2507     AdapterBlob* adapter_blob = entry->adapter_blob();
2508     char blob_id[256];
2509     jio_snprintf(blob_id,
2510                  sizeof(blob_id),
2511                  "%s(%s)",
2512                  adapter_blob->name(),
2513                  entry->fingerprint()->as_string());
2514     if (Forte::is_enabled()) {
2515       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2516     }

2524 void AdapterHandlerLibrary::initialize() {
2525   {
2526     ResourceMark rm;
2527     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2528     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2529   }
2530 
2531 #if INCLUDE_CDS
2532   // Link adapters in AOT Cache to their code in AOT Code Cache
2533   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2534     link_aot_adapters();
2535     lookup_simple_adapters();
2536     return;
2537   }
2538 #endif // INCLUDE_CDS
2539 
2540   ResourceMark rm;
2541   {
2542     MutexLocker mu(AdapterHandlerLibrary_lock);
2543 
2544     _no_arg_handler = create_adapter(0, nullptr);


2545 
2546     BasicType obj_args[] = { T_OBJECT };
2547     _obj_arg_handler = create_adapter(1, obj_args);


2548 
2549     BasicType int_args[] = { T_INT };
2550     _int_arg_handler = create_adapter(1, int_args);


2551 
2552     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2553     _obj_int_arg_handler = create_adapter(2, obj_int_args);



2554 
2555     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2556     _obj_obj_arg_handler = create_adapter(2, obj_obj_args);



2557 
2558     // we should always get an entry back but we don't have any
2559     // associated blob on Zero
2560     assert(_no_arg_handler != nullptr &&
2561            _obj_arg_handler != nullptr &&
2562            _int_arg_handler != nullptr &&
2563            _obj_int_arg_handler != nullptr &&
2564            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2565   }
2566 
2567   // Outside of the lock
2568 #ifndef ZERO
2569   // no blobs to register when we are on Zero
2570   post_adapter_creation(_no_arg_handler);
2571   post_adapter_creation(_obj_arg_handler);
2572   post_adapter_creation(_int_arg_handler);
2573   post_adapter_creation(_obj_int_arg_handler);
2574   post_adapter_creation(_obj_obj_arg_handler);
2575 #endif // ZERO
2576 }
2577 
2578 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2579   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2580   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2581   return AdapterHandlerEntry::allocate(id, fingerprint);
2582 }
2583 
2584 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2585   int total_args_passed = method->size_of_parameters(); // All args on stack
2586   if (total_args_passed == 0) {
2587     return _no_arg_handler;
2588   } else if (total_args_passed == 1) {
2589     if (!method->is_static()) {



2590       return _obj_arg_handler;
2591     }
2592     switch (method->signature()->char_at(1)) {
2593       case JVM_SIGNATURE_CLASS:









2594       case JVM_SIGNATURE_ARRAY:
2595         return _obj_arg_handler;
2596       case JVM_SIGNATURE_INT:
2597       case JVM_SIGNATURE_BOOLEAN:
2598       case JVM_SIGNATURE_CHAR:
2599       case JVM_SIGNATURE_BYTE:
2600       case JVM_SIGNATURE_SHORT:
2601         return _int_arg_handler;
2602     }
2603   } else if (total_args_passed == 2 &&
2604              !method->is_static()) {
2605     switch (method->signature()->char_at(1)) {
2606       case JVM_SIGNATURE_CLASS:









2607       case JVM_SIGNATURE_ARRAY:
2608         return _obj_obj_arg_handler;
2609       case JVM_SIGNATURE_INT:
2610       case JVM_SIGNATURE_BOOLEAN:
2611       case JVM_SIGNATURE_CHAR:
2612       case JVM_SIGNATURE_BYTE:
2613       case JVM_SIGNATURE_SHORT:
2614         return _obj_int_arg_handler;
2615     }
2616   }
2617   return nullptr;
2618 }
2619 
2620 class AdapterSignatureIterator : public SignatureIterator {
2621  private:
2622   BasicType stack_sig_bt[16];
2623   BasicType* sig_bt;
2624   int index;




2625 
2626  public:
2627   AdapterSignatureIterator(Symbol* signature,
2628                            fingerprint_t fingerprint,
2629                            bool is_static,
2630                            int total_args_passed) :
2631     SignatureIterator(signature, fingerprint),
2632     index(0)
2633   {
2634     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2635     if (!is_static) { // Pass in receiver first
2636       sig_bt[index++] = T_OBJECT;













2637     }
2638     do_parameters_on(this);
2639   }
2640 
2641   BasicType* basic_types() {
2642     return sig_bt;
















































2643   }





2644 












2645 #ifdef ASSERT
2646   int slots() {
2647     return index;





2648   }
2649 #endif
























2650 
2651  private:

2652 
2653   friend class SignatureIterator;  // so do_parameters_on can call do_type
2654   void do_type(BasicType type) {
2655     sig_bt[index++] = type;
2656     if (type == T_LONG || type == T_DOUBLE) {
2657       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots























































2658     }
2659   }
2660 };
2661 


























































































































































































2662 
2663 const char* AdapterHandlerEntry::_entry_names[] = {
2664   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2665 };
2666 
2667 #ifdef ASSERT
2668 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2669   // we can only check for the same code if there is any
2670 #ifndef ZERO
2671   AdapterHandlerEntry* comparison_entry = create_adapter(total_args_passed, sig_bt, true);
2672   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
2673   assert(comparison_entry->compare_code(cached_entry), "code must match");
2674   // Release the one just created
2675   AdapterHandlerEntry::deallocate(comparison_entry);
2676 # endif // ZERO
2677 }
2678 #endif /* ASSERT*/
2679 
2680 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2681   assert(!method->is_abstract(), "abstract methods do not have adapters");
2682   // Use customized signature handler.  Need to lock around updates to
2683   // the _adapter_handler_table (it is not safe for concurrent readers
2684   // and a single writer: this could be fixed if it becomes a
2685   // problem).
2686 
2687   // Fast-path for trivial adapters
2688   AdapterHandlerEntry* entry = get_simple_adapter(method);
2689   if (entry != nullptr) {
2690     return entry;
2691   }
2692 
2693   ResourceMark rm;
2694   bool new_entry = false;
2695 
2696   // Fill in the signature array, for the calling-convention call.
2697   int total_args_passed = method->size_of_parameters(); // All args on stack











2698 
2699   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2700                               method->is_static(), total_args_passed);
2701   assert(si.slots() == total_args_passed, "");
2702   BasicType* sig_bt = si.basic_types();
2703   {
2704     MutexLocker mu(AdapterHandlerLibrary_lock);
2705 
2706     // Lookup method signature's fingerprint
2707     entry = lookup(total_args_passed, sig_bt);
2708 
2709     if (entry != nullptr) {
2710 #ifndef ZERO
2711       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2712 #endif
2713 #ifdef ASSERT
2714       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
2715         verify_adapter_sharing(total_args_passed, sig_bt, entry);
2716       }
2717 #endif
2718     } else {
2719       entry = create_adapter(total_args_passed, sig_bt);
2720       if (entry != nullptr) {
2721         new_entry = true;
2722       }
2723     }
2724   }
2725 
2726   // Outside of the lock
2727   if (new_entry) {
2728     post_adapter_creation(entry);
2729   }
2730   return entry;
2731 }
2732 
2733 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2734   ResourceMark rm;
2735   const char* name = AdapterHandlerLibrary::name(handler);
2736   const uint32_t id = AdapterHandlerLibrary::id(handler);
2737 
2738   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
2739   if (blob != nullptr) {

2754   }
2755   insts_size = adapter_blob->code_size();
2756   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2757                 handler->fingerprint()->as_basic_args_string(),
2758                 handler->fingerprint()->as_string(), insts_size);
2759   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2760   if (Verbose || PrintStubCode) {
2761     address first_pc = adapter_blob->content_begin();
2762     if (first_pc != nullptr) {
2763       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2764       st->cr();
2765     }
2766   }
2767 }
2768 #endif // PRODUCT
2769 
2770 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
2771                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
2772   entry_offset[AdapterBlob::I2C] = 0;
2773   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];


2774   entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];

2775   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
2776     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
2777   } else {
2778     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
2779   }
2780 }
2781 
2782 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
2783                                                   int total_args_passed,
2784                                                   BasicType* sig_bt,
2785                                                   bool is_transient) {
2786   if (log_is_enabled(Info, perf, class, link)) {
2787     ClassLoader::perf_method_adapters_count()->inc();
2788   }
2789 
2790 #ifndef ZERO

2791   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2792   CodeBuffer buffer(buf);
2793   short buffer_locs[20];
2794   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2795                                          sizeof(buffer_locs)/sizeof(relocInfo));
2796   MacroAssembler masm(&buffer);
2797   VMRegPair stack_regs[16];
2798   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2799 
2800   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2801   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2802   address entry_address[AdapterBlob::ENTRY_COUNT];
2803   SharedRuntime::generate_i2c2i_adapters(&masm,
2804                                          total_args_passed,
2805                                          comp_args_on_stack,
2806                                          sig_bt,
2807                                          regs,
2808                                          entry_address);















2809   // On zero there is no code to save and no need to create a blob and
2810   // or relocate the handler.
2811   int entry_offset[AdapterBlob::ENTRY_COUNT];
2812   address_to_offset(entry_address, entry_offset);
2813 #ifdef ASSERT
2814   if (VerifyAdapterSharing) {
2815     handler->save_code(buf->code_begin(), buffer.insts_size());
2816     if (is_transient) {
2817       return true;
2818     }
2819   }
2820 #endif
2821   AdapterBlob* adapter_blob = AdapterBlob::create(&buffer, entry_offset);
2822   if (adapter_blob == nullptr) {
2823     // CodeCache is full, disable compilation
2824     // Ought to log this but compile log is only per compile thread
2825     // and we're some non descript Java thread.
2826     return false;
2827   }
2828   handler->set_adapter_blob(adapter_blob);
2829   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
2830     // try to save generated code
2831     const char* name = AdapterHandlerLibrary::name(handler);
2832     const uint32_t id = AdapterHandlerLibrary::id(handler);
2833     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
2834     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
2835   }
2836 #endif // ZERO
2837 
2838 #ifndef PRODUCT
2839   // debugging support
2840   if (PrintAdapterHandlers || PrintStubCode) {
2841     print_adapter_handler_info(tty, handler);
2842   }
2843 #endif
2844 
2845   return true;
2846 }
2847 
2848 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(int total_args_passed,
2849                                                            BasicType* sig_bt,
2850                                                            bool is_transient) {
2851   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);





2852   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2853   if (!generate_adapter_code(handler, total_args_passed, sig_bt, is_transient)) {
2854     AdapterHandlerEntry::deallocate(handler);
2855     return nullptr;
2856   }
2857   if (!is_transient) {
2858     assert_lock_strong(AdapterHandlerLibrary_lock);
2859     _adapter_handler_table->put(fp, handler);
2860   }
2861   return handler;
2862 }
2863 
2864 #if INCLUDE_CDS
2865 void AdapterHandlerEntry::remove_unshareable_info() {
2866 #ifdef ASSERT
2867    _saved_code = nullptr;
2868    _saved_code_length = 0;
2869 #endif // ASSERT
2870    _adapter_blob = nullptr;
2871    _linked = false;


2872 }
2873 
2874 class CopyAdapterTableToArchive : StackObj {
2875 private:
2876   CompactHashtableWriter* _writer;
2877   ArchiveBuilder* _builder;
2878 public:
2879   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
2880                                                              _builder(ArchiveBuilder::current())
2881   {}
2882 
2883   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
2884     LogStreamHandle(Trace, aot) lsh;
2885     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
2886       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
2887       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
2888       assert(buffered_fp != nullptr,"sanity check");
2889       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
2890       assert(buffered_entry != nullptr,"sanity check");
2891 

2931   }
2932 #endif
2933 }
2934 
2935 // This method is used during production run to link archived adapters (stored in AOT Cache)
2936 // to their code in AOT Code Cache
2937 void AdapterHandlerEntry::link() {
2938   ResourceMark rm;
2939   assert(_fingerprint != nullptr, "_fingerprint must not be null");
2940   bool generate_code = false;
2941   // Generate code only if AOTCodeCache is not available, or
2942   // caching adapters is disabled, or we fail to link
2943   // the AdapterHandlerEntry to its code in the AOTCodeCache
2944   if (AOTCodeCache::is_using_adapter()) {
2945     AdapterHandlerLibrary::link_aot_adapter_handler(this);
2946     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
2947     if (_adapter_blob == nullptr) {
2948       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
2949       generate_code = true;
2950     }

















2951   } else {
2952     generate_code = true;
2953   }
2954   if (generate_code) {
2955     int nargs;
2956     BasicType* bt = _fingerprint->as_basic_type(nargs);
2957     if (!AdapterHandlerLibrary::generate_adapter_code(this, nargs, bt, /* is_transient */ false)) {
2958       // Don't throw exceptions during VM initialization because java.lang.* classes
2959       // might not have been initialized, causing problems when constructing the
2960       // Java exception object.
2961       vm_exit_during_initialization("Out of space in CodeCache for adapters");
2962     }
2963   }
2964   if (_adapter_blob != nullptr) {
2965     post_adapter_creation(this);
2966   }
2967   assert(_linked, "AdapterHandlerEntry must now be linked");
2968 }
2969 
2970 void AdapterHandlerLibrary::link_aot_adapters() {
2971   uint max_id = 0;
2972   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
2973   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
2974    * That implies adapter ids of the adapters in the cache may not be contiguous.
2975    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
2976    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
2977    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
2978    */
2979   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
2980     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
2981     entry->link();
2982     max_id = MAX2(max_id, entry->id());
2983   });
2984   // Set adapter id to the maximum id found in the AOTCache
2985   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
2986   _id_counter = max_id;
2987 }
2988 
2989 // This method is called during production run to lookup simple adapters
2990 // in the archived adapter handler table
2991 void AdapterHandlerLibrary::lookup_simple_adapters() {
2992   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
2993 
2994   MutexLocker mu(AdapterHandlerLibrary_lock);
2995   _no_arg_handler = lookup(0, nullptr);
2996 
2997   BasicType obj_args[] = { T_OBJECT };
2998   _obj_arg_handler = lookup(1, obj_args);
2999 
3000   BasicType int_args[] = { T_INT };
3001   _int_arg_handler = lookup(1, int_args);
3002 
3003   BasicType obj_int_args[] = { T_OBJECT, T_INT };
3004   _obj_int_arg_handler = lookup(2, obj_int_args);
3005 
3006   BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3007   _obj_obj_arg_handler = lookup(2, obj_obj_args);













3008 
3009   assert(_no_arg_handler != nullptr &&
3010          _obj_arg_handler != nullptr &&
3011          _int_arg_handler != nullptr &&
3012          _obj_int_arg_handler != nullptr &&
3013          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3014   assert(_no_arg_handler->is_linked() &&
3015          _obj_arg_handler->is_linked() &&
3016          _int_arg_handler->is_linked() &&
3017          _obj_int_arg_handler->is_linked() &&
3018          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3019 }
3020 #endif // INCLUDE_CDS
3021 
3022 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3023   LogStreamHandle(Trace, aot) lsh;
3024   if (lsh.is_enabled()) {
3025     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3026     lsh.cr();
3027   }
3028   it->push(&_fingerprint);
3029 }
3030 
3031 AdapterHandlerEntry::~AdapterHandlerEntry() {
3032   if (_fingerprint != nullptr) {
3033     AdapterFingerPrint::deallocate(_fingerprint);
3034     _fingerprint = nullptr;
3035   }






3036 #ifdef ASSERT
3037   FREE_C_HEAP_ARRAY(_saved_code);
3038 #endif
3039   FreeHeap(this);
3040 }
3041 
3042 
3043 #ifdef ASSERT
3044 // Capture the code before relocation so that it can be compared
3045 // against other versions.  If the code is captured after relocation
3046 // then relative instructions won't be equivalent.
3047 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3048   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3049   _saved_code_length = length;
3050   memcpy(_saved_code, buffer, length);
3051 }
3052 
3053 
3054 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3055   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");

3105       struct { double data[20]; } stubs_locs_buf;
3106       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3107 #if defined(AARCH64)
3108       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3109       // in the constant pool to ensure ordering between the barrier and oops
3110       // accesses. For native_wrappers we need a constant.
3111       buffer.initialize_consts_size(8);
3112 #elif defined(PPC64) || defined(S390)
3113       // On PPC64/S390 the continuation enter intrinsic needs the constant pool for the compiled
3114       // static java call that is resolved in the runtime.
3115       if (method->is_continuation_enter_intrinsic()) {
3116         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24) S390_ONLY(+ 17));
3117       }
3118 #endif
3119       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3120       MacroAssembler _masm(&buffer);
3121 
3122       // Fill in the signature array, for the calling-convention call.
3123       const int total_args_passed = method->size_of_parameters();
3124 

3125       VMRegPair stack_regs[16];

3126       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3127 
3128       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3129                               method->is_static(), total_args_passed);
3130       BasicType* sig_bt = si.basic_types();
3131       assert(si.slots() == total_args_passed, "");
3132       BasicType ret_type = si.return_type();








3133 
3134       // Now get the compiled-Java arguments layout.
3135       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3136 
3137       // Generate the compiled-to-native wrapper code
3138       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3139 
3140       if (nm != nullptr) {
3141         {
3142           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3143           if (nm->make_in_use()) {
3144             method->set_code(method, nm);
3145           }
3146         }
3147 
3148         CompilerDirectiveMatcher matcher(method, CompLevel_simple);
3149         if (matcher.directive_set()->PrintAssemblyOption) {
3150           nm->print_code();
3151         }
3152       }

3359       if (b == handler->adapter_blob()) {
3360         found = true;
3361         st->print("Adapter for signature: ");
3362         handler->print_adapter_on(st);
3363         return false; // abort iteration
3364       } else {
3365         return true; // keep looking
3366       }
3367     };
3368     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3369     _adapter_handler_table->iterate(findblob_runtime_table);
3370   }
3371   assert(found, "Should have found handler");
3372 }
3373 
3374 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3375   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3376   if (adapter_blob() != nullptr) {
3377     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3378     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3379     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));



3380     if (get_c2i_no_clinit_check_entry() != nullptr) {
3381       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3382     }
3383   }
3384   st->cr();
3385 }
3386 
3387 #ifndef PRODUCT
3388 
3389 void AdapterHandlerLibrary::print_statistics() {
3390   print_table_statistics();
3391 }
3392 
3393 #endif /* PRODUCT */
3394 
3395 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3396   assert(current == JavaThread::current(), "pre-condition");
3397   StackOverflow* overflow_state = current->stack_overflow_state();
3398   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3399   overflow_state->set_reserved_stack_activation(current->stack_base());

3446         event.set_method(method);
3447         event.commit();
3448       }
3449     }
3450   }
3451   return activation;
3452 }
3453 
3454 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3455   // After any safepoint, just before going back to compiled code,
3456   // we inform the GC that we will be doing initializing writes to
3457   // this object in the future without emitting card-marks, so
3458   // GC may take any compensating steps.
3459 
3460   oop new_obj = current->vm_result_oop();
3461   if (new_obj == nullptr) return;
3462 
3463   BarrierSet *bs = BarrierSet::barrier_set();
3464   bs->on_slowpath_allocation_exit(current, new_obj);
3465 }























































































































































































  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/nmethod.inline.hpp"
  38 #include "code/scopeDesc.hpp"
  39 #include "code/vtableStubs.hpp"
  40 #include "compiler/abstractCompiler.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/interpreter.hpp"
  46 #include "interpreter/interpreterRuntime.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "memory/oopFactory.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "metaprogramming/primitiveConversions.hpp"
  54 #include "oops/access.hpp"
  55 #include "oops/fieldStreams.inline.hpp"
  56 #include "oops/inlineKlass.inline.hpp"
  57 #include "oops/klass.hpp"
  58 #include "oops/method.inline.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.inline.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "prims/forte.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "prims/jvmtiThreadState.hpp"
  65 #include "prims/methodHandles.hpp"
  66 #include "prims/nativeLookup.hpp"
  67 #include "runtime/arguments.hpp"
  68 #include "runtime/atomicAccess.hpp"
  69 #include "runtime/basicLock.inline.hpp"
  70 #include "runtime/frame.inline.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/init.hpp"
  73 #include "runtime/interfaceSupport.inline.hpp"
  74 #include "runtime/java.hpp"
  75 #include "runtime/javaCalls.hpp"
  76 #include "runtime/jniHandles.inline.hpp"
  77 #include "runtime/osThread.hpp"
  78 #include "runtime/perfData.hpp"
  79 #include "runtime/sharedRuntime.hpp"
  80 #include "runtime/signature.hpp"
  81 #include "runtime/stackWatermarkSet.hpp"
  82 #include "runtime/stubRoutines.hpp"
  83 #include "runtime/synchronizer.hpp"
  84 #include "runtime/timerTrace.hpp"
  85 #include "runtime/vframe.inline.hpp"
  86 #include "runtime/vframeArray.hpp"
  87 #include "runtime/vm_version.hpp"
  88 #include "utilities/copy.hpp"
  89 #include "utilities/dtrace.hpp"
  90 #include "utilities/events.hpp"
  91 #include "utilities/exceptions.hpp"
  92 #include "utilities/globalDefinitions.hpp"
  93 #include "utilities/hashTable.hpp"
  94 #include "utilities/macros.hpp"
  95 #include "utilities/xmlstream.hpp"
  96 #ifdef COMPILER1
  97 #include "c1/c1_Runtime1.hpp"
  98 #endif
  99 #ifdef COMPILER2
 100 #include "opto/runtime.hpp"

 111   type*       SharedRuntime::BLOB_FIELD_NAME(name);
 112   SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
 113 #undef SHARED_STUB_FIELD_DEFINE
 114 
 115 nmethod*            SharedRuntime::_cont_doYield_stub;
 116 
 117 #if 0
 118 // TODO tweak global stub name generation to match this
 119 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
 120 const char *SharedRuntime::_stub_names[] = {
 121   SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
 122 };
 123 #endif
 124 
 125 //----------------------------generate_stubs-----------------------------------
 126 void SharedRuntime::generate_initial_stubs() {
 127   // Build this early so it's available for the interpreter.
 128   _throw_StackOverflowError_blob =
 129     generate_throw_exception(StubId::shared_throw_StackOverflowError_id,
 130                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
 131 
 132   if (InlineTypeReturnedAsFields) {
 133     _store_inline_type_fields_to_buf_blob =
 134       generate_return_value_stub(CAST_FROM_FN_PTR(address, SharedRuntime::store_inline_type_fields_to_buf));
 135   }
 136 }
 137 
 138 void SharedRuntime::generate_stubs() {
 139   _wrong_method_blob =
 140     generate_resolve_blob(StubId::shared_wrong_method_id,
 141                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
 142   _wrong_method_abstract_blob =
 143     generate_resolve_blob(StubId::shared_wrong_method_abstract_id,
 144                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
 145   _ic_miss_blob =
 146     generate_resolve_blob(StubId::shared_ic_miss_id,
 147                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
 148   _resolve_opt_virtual_call_blob =
 149     generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id,
 150                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
 151   _resolve_virtual_call_blob =
 152     generate_resolve_blob(StubId::shared_resolve_virtual_call_id,
 153                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
 154   _resolve_static_call_blob =
 155     generate_resolve_blob(StubId::shared_resolve_static_call_id,

1178 // for a call current in progress, i.e., arguments has been pushed on stack
1179 // but callee has not been invoked yet.  Caller frame must be compiled.
1180 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1181                                               CallInfo& callinfo, TRAPS) {
1182   Handle receiver;
1183   Handle nullHandle;  // create a handy null handle for exception returns
1184   JavaThread* current = THREAD;
1185 
1186   assert(!vfst.at_end(), "Java frame must exist");
1187 
1188   // Find caller and bci from vframe
1189   methodHandle caller(current, vfst.method());
1190   int          bci   = vfst.bci();
1191 
1192   if (caller->is_continuation_enter_intrinsic()) {
1193     bc = Bytecodes::_invokestatic;
1194     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1195     return receiver;
1196   }
1197 
1198   // Substitutability test implementation piggy backs on static call resolution
1199   Bytecodes::Code code = caller->java_code_at(bci);
1200   if (code == Bytecodes::_if_acmpeq || code == Bytecodes::_if_acmpne) {
1201     bc = Bytecodes::_invokestatic;
1202     methodHandle attached_method(THREAD, extract_attached_method(vfst));
1203     assert(attached_method.not_null(), "must have attached method");
1204     vmClasses::ValueObjectMethods_klass()->initialize(CHECK_NH);
1205     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, false, CHECK_NH);
1206 #ifdef ASSERT
1207     Symbol* subst_method_name = vmSymbols::isSubstitutable_name();
1208     Method* is_subst = vmClasses::ValueObjectMethods_klass()->find_method(subst_method_name, vmSymbols::object_object_boolean_signature());
1209     assert(callinfo.selected_method() == is_subst, "must be isSubstitutable method");
1210 #endif
1211     return receiver;
1212   }
1213 
1214   Bytecode_invoke bytecode(caller, bci);
1215   int bytecode_index = bytecode.index();
1216   bc = bytecode.invoke_code();
1217 
1218   methodHandle attached_method(current, extract_attached_method(vfst));
1219   if (attached_method.not_null()) {
1220     Method* callee = bytecode.static_target(CHECK_NH);
1221     vmIntrinsics::ID id = callee->intrinsic_id();
1222     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1223     // it attaches statically resolved method to the call site.
1224     if (MethodHandles::is_signature_polymorphic(id) &&
1225         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1226       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1227 
1228       // Adjust invocation mode according to the attached method.
1229       switch (bc) {
1230         case Bytecodes::_invokevirtual:
1231           if (attached_method->method_holder()->is_interface()) {
1232             bc = Bytecodes::_invokeinterface;
1233           }
1234           break;
1235         case Bytecodes::_invokeinterface:
1236           if (!attached_method->method_holder()->is_interface()) {
1237             bc = Bytecodes::_invokevirtual;
1238           }
1239           break;
1240         case Bytecodes::_invokehandle:
1241           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1242             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1243                                               : Bytecodes::_invokevirtual;
1244           }
1245           break;
1246         default:
1247           break;
1248       }
1249     } else {
1250       assert(attached_method->has_scalarized_args(), "invalid use of attached method");
1251       if (!attached_method->method_holder()->is_inline_klass() || attached_method->is_static()) {
1252         // Ignore the attached method in this case to not confuse below code
1253         attached_method = methodHandle(current, nullptr);
1254       }
1255     }
1256   }
1257 
1258   assert(bc != Bytecodes::_illegal, "not initialized");
1259 
1260   bool has_receiver = bc != Bytecodes::_invokestatic &&
1261                       bc != Bytecodes::_invokedynamic &&
1262                       bc != Bytecodes::_invokehandle;
1263   bool check_null_and_abstract = true;
1264 
1265   // Find receiver for non-static call
1266   if (has_receiver) {
1267     // This register map must be update since we need to find the receiver for
1268     // compiled frames. The receiver might be in a register.
1269     RegisterMap reg_map2(current,
1270                          RegisterMap::UpdateMap::include,
1271                          RegisterMap::ProcessFrames::include,
1272                          RegisterMap::WalkContinuation::skip);
1273     frame stubFrame   = current->last_frame();
1274     // Caller-frame is a compiled frame
1275     frame callerFrame = stubFrame.sender(&reg_map2);
1276 
1277     Method* callee = attached_method();
1278     if (callee == nullptr) {
1279       callee = bytecode.static_target(CHECK_NH);
1280       if (callee == nullptr) {
1281         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1282       }
1283     }
1284     bool caller_is_c1 = callerFrame.is_compiled_frame() && callerFrame.cb()->as_nmethod()->is_compiled_by_c1();
1285     if (!caller_is_c1 && callee->is_scalarized_arg(0)) {
1286       // If the receiver is an inline type that is passed as fields, no oop is available
1287       // Resolve the call without receiver null checking.
1288       assert(!callee->mismatch(), "calls with inline type receivers should never mismatch");
1289       assert(attached_method.not_null() && !attached_method->is_abstract(), "must have non-abstract attached method");
1290       if (bc == Bytecodes::_invokeinterface) {
1291         bc = Bytecodes::_invokevirtual; // C2 optimistically replaces interface calls by virtual calls
1292       }
1293       check_null_and_abstract = false;
1294     } else {
1295       // Retrieve from a compiled argument list
1296       receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1297       assert(oopDesc::is_oop_or_null(receiver()), "");
1298       if (receiver.is_null()) {
1299         THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1300       }
1301     }
1302   }
1303 
1304   // Resolve method
1305   if (attached_method.not_null()) {
1306     // Parameterized by attached method.
1307     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, check_null_and_abstract, CHECK_NH);
1308   } else {
1309     // Parameterized by bytecode.
1310     constantPoolHandle constants(current, caller->constants());
1311     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1312   }
1313 
1314 #ifdef ASSERT
1315   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1316   if (has_receiver && check_null_and_abstract) {
1317     assert(receiver.not_null(), "should have thrown exception");
1318     Klass* receiver_klass = receiver->klass();
1319     Klass* rk = nullptr;
1320     if (attached_method.not_null()) {
1321       // In case there's resolved method attached, use its holder during the check.
1322       rk = attached_method->method_holder();
1323     } else {
1324       // Klass is already loaded.
1325       constantPoolHandle constants(current, caller->constants());
1326       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1327     }
1328     Klass* static_receiver_klass = rk;
1329     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1330            "actual receiver must be subclass of static receiver klass");
1331     if (receiver_klass->is_instance_klass()) {
1332       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1333         tty->print_cr("ERROR: Klass not yet initialized!!");
1334         receiver_klass->print();
1335       }
1336       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1337     }
1338   }
1339 #endif
1340 
1341   return receiver;
1342 }
1343 
1344 methodHandle SharedRuntime::find_callee_method(bool& caller_does_not_scalarize, TRAPS) {
1345   JavaThread* current = THREAD;
1346   ResourceMark rm(current);
1347   // We need first to check if any Java activations (compiled, interpreted)
1348   // exist on the stack since last JavaCall.  If not, we need
1349   // to get the target method from the JavaCall wrapper.
1350   vframeStream vfst(current, true);  // Do not skip any javaCalls
1351   methodHandle callee_method;
1352   if (vfst.at_end()) {
1353     // No Java frames were found on stack since we did the JavaCall.
1354     // Hence the stack can only contain an entry_frame.  We need to
1355     // find the target method from the stub frame.
1356     RegisterMap reg_map(current,
1357                         RegisterMap::UpdateMap::skip,
1358                         RegisterMap::ProcessFrames::include,
1359                         RegisterMap::WalkContinuation::skip);
1360     frame fr = current->last_frame();
1361     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1362     fr = fr.sender(&reg_map);
1363     assert(fr.is_entry_frame(), "must be");
1364     // fr is now pointing to the entry frame.
1365     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1366   } else {
1367     Bytecodes::Code bc;
1368     CallInfo callinfo;
1369     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1370     // Calls via mismatching methods are always non-scalarized
1371     if (callinfo.resolved_method()->mismatch()) {
1372       caller_does_not_scalarize = true;
1373     }
1374     callee_method = methodHandle(current, callinfo.selected_method());
1375   }
1376   assert(callee_method()->is_method(), "must be");
1377   return callee_method;
1378 }
1379 
1380 // Resolves a call.
1381 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1382   JavaThread* current = THREAD;
1383   ResourceMark rm(current);
1384   RegisterMap cbl_map(current,
1385                       RegisterMap::UpdateMap::skip,
1386                       RegisterMap::ProcessFrames::include,
1387                       RegisterMap::WalkContinuation::skip);
1388   frame caller_frame = current->last_frame().sender(&cbl_map);
1389 
1390   CodeBlob* caller_cb = caller_frame.cb();
1391   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1392   nmethod* caller_nm = caller_cb->as_nmethod();
1393 
1394   // determine call info & receiver
1395   // note: a) receiver is null for static calls
1396   //       b) an exception is thrown if receiver is null for non-static calls
1397   CallInfo call_info;
1398   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1399   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1400 
1401   NoSafepointVerifier nsv;
1402 
1403   methodHandle callee_method(current, call_info.selected_method());
1404   // Calls via mismatching methods are always non-scalarized
1405   bool mismatch = is_optimized ? call_info.selected_method()->mismatch() : call_info.resolved_method()->mismatch();
1406   if (caller_nm->is_compiled_by_c1() || mismatch) {
1407     caller_does_not_scalarize = true;
1408   }
1409 
1410   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1411          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1412          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1413          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1414          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1415 
1416   assert(!caller_nm->is_unloading(), "It should not be unloading");
1417 
1418 #ifndef PRODUCT
1419   // tracing/debugging/statistics
1420   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1421                  (is_virtual) ? (&_resolve_virtual_ctr) :
1422                                 (&_resolve_static_ctr);
1423   AtomicAccess::inc(addr);
1424 
1425   if (TraceCallFixup) {
1426     ResourceMark rm(current);
1427     tty->print("resolving %s%s (%s) %s call to",
1428                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1429                Bytecodes::name(invoke_code), (caller_does_not_scalarize) ? "non-scalar" : "");
1430     callee_method->print_short_name(tty);
1431     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1432                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1433   }
1434 #endif
1435 
1436   if (invoke_code == Bytecodes::_invokestatic) {
1437     assert(callee_method->method_holder()->is_initialized() ||
1438            callee_method->method_holder()->is_reentrant_initialization(current),
1439            "invalid class initialization state for invoke_static");
1440     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1441       // In order to keep class initialization check, do not patch call
1442       // site for static call when the class is not fully initialized.
1443       // Proper check is enforced by call site re-resolution on every invocation.
1444       //
1445       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1446       // explicit class initialization check is put in nmethod entry (VEP).
1447       assert(callee_method->method_holder()->is_linked(), "must be");
1448       return callee_method;
1449     }
1450   }
1451 
1452 
1453   // JSR 292 key invariant:
1454   // If the resolved method is a MethodHandle invoke target, the call
1455   // site must be a MethodHandle call site, because the lambda form might tail-call
1456   // leaving the stack in a state unknown to either caller or callee
1457 
1458   // Compute entry points. The computation of the entry points is independent of
1459   // patching the call.
1460 
1461   // Make sure the callee nmethod does not get deoptimized and removed before
1462   // we are done patching the code.
1463 
1464 
1465   CompiledICLocker ml(caller_nm);
1466   if (is_virtual && !is_optimized) {
1467     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1468     inline_cache->update(&call_info, receiver->klass(), caller_does_not_scalarize);
1469   } else {
1470     // Callsite is a direct call - set it to the destination method
1471     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1472     callsite->set(callee_method, caller_does_not_scalarize);
1473   }
1474 
1475   return callee_method;
1476 }
1477 
1478 // Inline caches exist only in compiled code
1479 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1480 #ifdef ASSERT
1481   RegisterMap reg_map(current,
1482                       RegisterMap::UpdateMap::skip,
1483                       RegisterMap::ProcessFrames::include,
1484                       RegisterMap::WalkContinuation::skip);
1485   frame stub_frame = current->last_frame();
1486   assert(stub_frame.is_runtime_frame(), "sanity check");
1487   frame caller_frame = stub_frame.sender(&reg_map);
1488   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1489 #endif /* ASSERT */
1490 
1491   methodHandle callee_method;
1492   bool caller_does_not_scalarize = false;
1493   JRT_BLOCK
1494     callee_method = SharedRuntime::handle_ic_miss_helper(caller_does_not_scalarize, CHECK_NULL);
1495     // Return Method* through TLS
1496     current->set_vm_result_metadata(callee_method());
1497   JRT_BLOCK_END
1498   // return compiled code entry point after potential safepoints
1499   return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1500 JRT_END
1501 
1502 
1503 // Handle call site that has been made non-entrant
1504 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1505   // 6243940 We might end up in here if the callee is deoptimized
1506   // as we race to call it.  We don't want to take a safepoint if
1507   // the caller was interpreted because the caller frame will look
1508   // interpreted to the stack walkers and arguments are now
1509   // "compiled" so it is much better to make this transition
1510   // invisible to the stack walking code. The i2c path will
1511   // place the callee method in the callee_target. It is stashed
1512   // there because if we try and find the callee by normal means a
1513   // safepoint is possible and have trouble gc'ing the compiled args.
1514   RegisterMap reg_map(current,
1515                       RegisterMap::UpdateMap::skip,
1516                       RegisterMap::ProcessFrames::include,
1517                       RegisterMap::WalkContinuation::skip);
1518   frame stub_frame = current->last_frame();
1519   assert(stub_frame.is_runtime_frame(), "sanity check");
1520   frame caller_frame = stub_frame.sender(&reg_map);
1521 
1522   if (caller_frame.is_interpreted_frame() ||
1523       caller_frame.is_entry_frame() ||
1524       caller_frame.is_upcall_stub_frame()) {
1525     Method* callee = current->callee_target();
1526     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1527     current->set_vm_result_metadata(callee);
1528     current->set_callee_target(nullptr);
1529     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1530       // Bypass class initialization checks in c2i when caller is in native.
1531       // JNI calls to static methods don't have class initialization checks.
1532       // Fast class initialization checks are present in c2i adapters and call into
1533       // SharedRuntime::handle_wrong_method() on the slow path.
1534       //
1535       // JVM upcalls may land here as well, but there's a proper check present in
1536       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1537       // so bypassing it in c2i adapter is benign.
1538       return callee->get_c2i_no_clinit_check_entry();
1539     } else {
1540       if (caller_frame.is_interpreted_frame()) {
1541         return callee->get_c2i_inline_entry();
1542       } else {
1543         return callee->get_c2i_entry();
1544       }
1545     }
1546   }
1547 
1548   // Must be compiled to compiled path which is safe to stackwalk
1549   methodHandle callee_method;
1550   bool is_static_call = false;
1551   bool is_optimized = false;
1552   bool caller_does_not_scalarize = false;
1553   JRT_BLOCK
1554     // Force resolving of caller (if we called from compiled frame)
1555     callee_method = SharedRuntime::reresolve_call_site(is_optimized, caller_does_not_scalarize, CHECK_NULL);
1556     current->set_vm_result_metadata(callee_method());
1557   JRT_BLOCK_END
1558   // return compiled code entry point after potential safepoints
1559   return get_resolved_entry(current, callee_method, callee_method->is_static(), is_optimized, caller_does_not_scalarize);
1560 JRT_END
1561 
1562 // Handle abstract method call
1563 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1564   // Verbose error message for AbstractMethodError.
1565   // Get the called method from the invoke bytecode.
1566   vframeStream vfst(current, true);
1567   assert(!vfst.at_end(), "Java frame must exist");
1568   methodHandle caller(current, vfst.method());
1569   Bytecode_invoke invoke(caller, vfst.bci());
1570   DEBUG_ONLY( invoke.verify(); )
1571 
1572   // Find the compiled caller frame.
1573   RegisterMap reg_map(current,
1574                       RegisterMap::UpdateMap::include,
1575                       RegisterMap::ProcessFrames::include,
1576                       RegisterMap::WalkContinuation::skip);
1577   frame stubFrame = current->last_frame();
1578   assert(stubFrame.is_runtime_frame(), "must be");
1579   frame callerFrame = stubFrame.sender(&reg_map);
1580   assert(callerFrame.is_compiled_frame(), "must be");
1581 
1582   // Install exception and return forward entry.
1583   address res = SharedRuntime::throw_AbstractMethodError_entry();
1584   JRT_BLOCK
1585     methodHandle callee(current, invoke.static_target(current));
1586     if (!callee.is_null()) {
1587       oop recv = callerFrame.retrieve_receiver(&reg_map);
1588       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1589       res = StubRoutines::forward_exception_entry();
1590       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1591     }
1592   JRT_BLOCK_END
1593   return res;
1594 JRT_END
1595 
1596 // return verified_code_entry if interp_only_mode is not set for the current thread;
1597 // otherwise return c2i entry.
1598 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method,
1599                                           bool is_static_call, bool is_optimized, bool caller_does_not_scalarize) {
1600   bool is_interp_only_mode = (StressCallingConvention && (os::random() % (1 << 10)) == 0) || current->is_interp_only_mode();
1601   // In interp_only_mode we need to go to the interpreted entry
1602   // The c2i won't patch in this mode -- see fixup_callers_callsite
1603   bool go_to_interpreter = is_interp_only_mode && !callee_method->is_special_native_intrinsic();
1604 
1605   if (caller_does_not_scalarize) {
1606     if (go_to_interpreter) {
1607       return callee_method->get_c2i_inline_entry();
1608     }
1609     assert(callee_method->verified_inline_code_entry() != nullptr, "Jump to zero!");
1610     return callee_method->verified_inline_code_entry();
1611   } else if (is_static_call || is_optimized) {
1612     if (go_to_interpreter) {
1613       return callee_method->get_c2i_entry();
1614     }
1615     assert(callee_method->verified_code_entry() != nullptr, "Jump to zero!");
1616     return callee_method->verified_code_entry();
1617   } else {
1618     if (go_to_interpreter) {
1619       return callee_method->get_c2i_inline_ro_entry();
1620     }
1621     assert(callee_method->verified_inline_ro_code_entry() != nullptr, "Jump to zero!");
1622     return callee_method->verified_inline_ro_code_entry();
1623   }


1624 }
1625 
1626 // resolve a static call and patch code
1627 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1628   methodHandle callee_method;
1629   bool caller_does_not_scalarize = false;
1630   bool enter_special = false;
1631   JRT_BLOCK
1632     callee_method = SharedRuntime::resolve_helper(false, false, caller_does_not_scalarize, CHECK_NULL);
1633     current->set_vm_result_metadata(callee_method());
1634   JRT_BLOCK_END
1635   // return compiled code entry point after potential safepoints
1636   return get_resolved_entry(current, callee_method, true, false, caller_does_not_scalarize);
1637 JRT_END
1638 
1639 // resolve virtual call and update inline cache to monomorphic
1640 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1641   methodHandle callee_method;
1642   bool caller_does_not_scalarize = false;
1643   JRT_BLOCK
1644     callee_method = SharedRuntime::resolve_helper(true, false, caller_does_not_scalarize, CHECK_NULL);
1645     current->set_vm_result_metadata(callee_method());
1646   JRT_BLOCK_END
1647   // return compiled code entry point after potential safepoints
1648   return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1649 JRT_END
1650 
1651 
1652 // Resolve a virtual call that can be statically bound (e.g., always
1653 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1654 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1655   methodHandle callee_method;
1656   bool caller_does_not_scalarize = false;
1657   JRT_BLOCK
1658     callee_method = SharedRuntime::resolve_helper(true, true, caller_does_not_scalarize, CHECK_NULL);
1659     current->set_vm_result_metadata(callee_method());
1660   JRT_BLOCK_END
1661   // return compiled code entry point after potential safepoints
1662   return get_resolved_entry(current, callee_method, false, true, caller_does_not_scalarize);
1663 JRT_END
1664 
1665 methodHandle SharedRuntime::handle_ic_miss_helper(bool& caller_does_not_scalarize, TRAPS) {
1666   JavaThread* current = THREAD;
1667   ResourceMark rm(current);
1668   CallInfo call_info;
1669   Bytecodes::Code bc;
1670 
1671   // receiver is null for static calls. An exception is thrown for null
1672   // receivers for non-static calls
1673   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1674 
1675   methodHandle callee_method(current, call_info.selected_method());
1676 
1677 #ifndef PRODUCT
1678   AtomicAccess::inc(&_ic_miss_ctr);
1679 
1680   // Statistics & Tracing
1681   if (TraceCallFixup) {
1682     ResourceMark rm(current);
1683     tty->print("IC miss (%s) %s call to", Bytecodes::name(bc), (caller_does_not_scalarize) ? "non-scalar" : "");
1684     callee_method->print_short_name(tty);
1685     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1686   }
1687 
1688   if (ICMissHistogram) {
1689     MutexLocker m(VMStatistic_lock);
1690     RegisterMap reg_map(current,
1691                         RegisterMap::UpdateMap::skip,
1692                         RegisterMap::ProcessFrames::include,
1693                         RegisterMap::WalkContinuation::skip);
1694     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1695     // produce statistics under the lock
1696     trace_ic_miss(f.pc());
1697   }
1698 #endif
1699 
1700   // install an event collector so that when a vtable stub is created the
1701   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1702   // event can't be posted when the stub is created as locks are held
1703   // - instead the event will be deferred until the event collector goes
1704   // out of scope.
1705   JvmtiDynamicCodeEventCollector event_collector;
1706 
1707   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1708   RegisterMap reg_map(current,
1709                       RegisterMap::UpdateMap::skip,
1710                       RegisterMap::ProcessFrames::include,
1711                       RegisterMap::WalkContinuation::skip);
1712   frame caller_frame = current->last_frame().sender(&reg_map);
1713   CodeBlob* cb = caller_frame.cb();
1714   nmethod* caller_nm = cb->as_nmethod();
1715   // Calls via mismatching methods are always non-scalarized
1716   if (caller_nm->is_compiled_by_c1() || call_info.resolved_method()->mismatch()) {
1717     caller_does_not_scalarize = true;
1718   }
1719 
1720   CompiledICLocker ml(caller_nm);
1721   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1722   inline_cache->update(&call_info, receiver()->klass(), caller_does_not_scalarize);
1723 
1724   return callee_method;
1725 }
1726 
1727 //
1728 // Resets a call-site in compiled code so it will get resolved again.
1729 // This routines handles both virtual call sites, optimized virtual call
1730 // sites, and static call sites. Typically used to change a call sites
1731 // destination from compiled to interpreted.
1732 //
1733 methodHandle SharedRuntime::reresolve_call_site(bool& is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1734   JavaThread* current = THREAD;
1735   ResourceMark rm(current);
1736   RegisterMap reg_map(current,
1737                       RegisterMap::UpdateMap::skip,
1738                       RegisterMap::ProcessFrames::include,
1739                       RegisterMap::WalkContinuation::skip);
1740   frame stub_frame = current->last_frame();
1741   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1742   frame caller = stub_frame.sender(&reg_map);
1743   if (caller.is_compiled_frame()) {
1744     caller_does_not_scalarize = caller.cb()->as_nmethod()->is_compiled_by_c1();
1745   }
1746   assert(!caller.is_interpreted_frame(), "must be compiled");
1747 
1748   // If the frame isn't a live compiled frame (i.e. deoptimized by the time we get here), no IC clearing must be done
1749   // for the caller. However, when the caller is C2 compiled and the callee a C1 or C2 compiled method, then we still
1750   // need to figure out whether it was an optimized virtual call with an inline type receiver. Otherwise, we end up
1751   // using the wrong method entry point and accidentally skip the buffering of the receiver.
1752   methodHandle callee_method = find_callee_method(caller_does_not_scalarize, CHECK_(methodHandle()));
1753   const bool caller_is_compiled_and_not_deoptimized = caller.is_compiled_frame() && !caller.is_deoptimized_frame();
1754   const bool caller_is_continuation_enter_intrinsic =
1755     caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic();
1756   const bool do_IC_clearing = caller_is_compiled_and_not_deoptimized || caller_is_continuation_enter_intrinsic;
1757 
1758   const bool callee_compiled_with_scalarized_receiver = callee_method->has_compiled_code() &&
1759                                                         !callee_method()->is_static() &&
1760                                                         callee_method()->is_scalarized_arg(0);
1761   const bool compute_is_optimized = !caller_does_not_scalarize && callee_compiled_with_scalarized_receiver;
1762 
1763   if (do_IC_clearing || compute_is_optimized) {
1764     address pc = caller.pc();
1765 
1766     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1767     assert(caller_nm != nullptr, "did not find caller nmethod");
1768 
1769     // Default call_addr is the location of the "basic" call.
1770     // Determine the address of the call we a reresolving. With
1771     // Inline Caches we will always find a recognizable call.
1772     // With Inline Caches disabled we may or may not find a
1773     // recognizable call. We will always find a call for static
1774     // calls and for optimized virtual calls. For vanilla virtual
1775     // calls it depends on the state of the UseInlineCaches switch.
1776     //
1777     // With Inline Caches disabled we can get here for a virtual call
1778     // for two reasons:
1779     //   1 - calling an abstract method. The vtable for abstract methods
1780     //       will run us thru handle_wrong_method and we will eventually
1781     //       end up in the interpreter to throw the ame.
1782     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1783     //       call and between the time we fetch the entry address and
1784     //       we jump to it the target gets deoptimized. Similar to 1
1785     //       we will wind up in the interprter (thru a c2i with c2).
1786     //
1787     CompiledICLocker ml(caller_nm);
1788     address call_addr = caller_nm->call_instruction_address(pc);
1789 
1790     if (call_addr != nullptr) {
1791       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1792       // bytes back in the instruction stream so we must also check for reloc info.
1793       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1794       bool ret = iter.next(); // Get item
1795       if (ret) {
1796         is_optimized = false;
1797         switch (iter.type()) {
1798           case relocInfo::static_call_type:
1799             assert(callee_method->is_static(), "must be");
1800           case relocInfo::opt_virtual_call_type: {
1801             is_optimized = (iter.type() == relocInfo::opt_virtual_call_type);
1802             if (do_IC_clearing) {
1803               CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1804               cdc->set_to_clean();
1805             }
1806             break;
1807           }
1808 
1809           case relocInfo::virtual_call_type: {
1810             if (do_IC_clearing) {
1811               // compiled, dispatched call (which used to call an interpreted method)
1812               CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1813               inline_cache->set_to_clean();
1814             }
1815             break;
1816           }
1817           default:
1818             break;
1819         }
1820       }
1821     }
1822   }
1823 



1824 #ifndef PRODUCT
1825   AtomicAccess::inc(&_wrong_method_ctr);
1826 
1827   if (TraceCallFixup) {
1828     ResourceMark rm(current);
1829     tty->print("handle_wrong_method reresolving %s call to", (caller_does_not_scalarize) ? "non-scalar" : "");
1830     callee_method->print_short_name(tty);
1831     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1832   }
1833 #endif
1834 
1835   return callee_method;
1836 }
1837 
1838 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1839   // The faulting unsafe accesses should be changed to throw the error
1840   // synchronously instead. Meanwhile the faulting instruction will be
1841   // skipped over (effectively turning it into a no-op) and an
1842   // asynchronous exception will be raised which the thread will
1843   // handle at a later point. If the instruction is a load it will
1844   // return garbage.
1845 
1846   // Request an async exception.
1847   thread->set_pending_unsafe_access_error();
1848 
1849   // Return address of next instruction to execute.

2015   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2016 
2017   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2018   if (message == nullptr) {
2019     // Shouldn't happen, but don't cause even more problems if it does
2020     message = const_cast<char*>(caster_klass->external_name());
2021   } else {
2022     jio_snprintf(message,
2023                  msglen,
2024                  "class %s cannot be cast to class %s (%s%s%s)",
2025                  caster_name,
2026                  target_name,
2027                  caster_klass_description,
2028                  klass_separator,
2029                  target_klass_description
2030                  );
2031   }
2032   return message;
2033 }
2034 
2035 char* SharedRuntime::generate_identity_exception_message(JavaThread* current, Klass* klass) {
2036   assert(klass->is_inline_klass(), "Must be a concrete value class");
2037   const char* desc = "Cannot synchronize on an instance of value class ";
2038   const char* className = klass->external_name();
2039   size_t msglen = strlen(desc) + strlen(className) + 1;
2040   char* message = NEW_RESOURCE_ARRAY(char, msglen);
2041   if (nullptr == message) {
2042     // Out of memory: can't create detailed error message
2043     message = const_cast<char*>(klass->external_name());
2044   } else {
2045     jio_snprintf(message, msglen, "%s%s", desc, className);
2046   }
2047   return message;
2048 }
2049 
2050 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2051   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2052 JRT_END
2053 
2054 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2055   if (!SafepointSynchronize::is_synchronizing()) {
2056     // Only try quick_enter() if we're not trying to reach a safepoint
2057     // so that the calling thread reaches the safepoint more quickly.
2058     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
2059       return;
2060     }
2061   }
2062   // NO_ASYNC required because an async exception on the state transition destructor
2063   // would leave you with the lock held and it would never be released.
2064   // The normal monitorenter NullPointerException is thrown without acquiring a lock
2065   // and the model is that an exception implies the method failed.
2066   JRT_BLOCK_NO_ASYNC
2067   Handle h_obj(THREAD, obj);
2068   ObjectSynchronizer::enter(h_obj, lock, current);
2069   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2263   tty->print_cr("Note 1: counter updates are not MT-safe.");
2264   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2265   tty->print_cr("        %% in nested categories are relative to their category");
2266   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2267   tty->cr();
2268 
2269   MethodArityHistogram h;
2270 }
2271 #endif
2272 
2273 #ifndef PRODUCT
2274 static int _lookups; // number of calls to lookup
2275 static int _equals;  // number of buckets checked with matching hash
2276 static int _archived_hits; // number of successful lookups in archived table
2277 static int _runtime_hits;  // number of successful lookups in runtime table
2278 #endif
2279 
2280 // A simple wrapper class around the calling convention information
2281 // that allows sharing of adapters for the same calling convention.
2282 class AdapterFingerPrint : public MetaspaceObj {
2283 public:
2284   class Element {
2285   private:
2286     // The highest byte is the type of the argument. The remaining bytes contain the offset of the
2287     // field if it is flattened in the calling convention, -1 otherwise.
2288     juint _payload;
2289 
2290     static constexpr int offset_bit_width = 24;
2291     static constexpr juint offset_bit_mask = (1 << offset_bit_width) - 1;
2292   public:
2293     Element(BasicType bt, int offset) : _payload((static_cast<juint>(bt) << offset_bit_width) | (juint(offset) & offset_bit_mask)) {
2294       assert(offset >= -1 && offset < jint(offset_bit_mask), "invalid offset %d", offset);
2295     }
2296 
2297     BasicType bt() const {
2298       return static_cast<BasicType>(_payload >> offset_bit_width);
2299     }
2300 
2301     int offset() const {
2302       juint res = _payload & offset_bit_mask;
2303       return res == offset_bit_mask ? -1 : res;
2304     }
2305 
2306     juint hash() const {
2307       return _payload;
2308     }
2309 
2310     bool operator!=(const Element& other) const {
2311       return _payload != other._payload;
2312     }
2313   };


2314 
2315 private:
2316   const bool _has_ro_adapter;
2317   const int _length;
2318 
2319   static int data_offset() { return sizeof(AdapterFingerPrint); }
2320   Element* data_pointer() {
2321     return reinterpret_cast<Element*>(reinterpret_cast<address>(this) + data_offset());
2322   }
2323 
2324   const Element& element_at(int index) {
2325     assert(index < length(), "index %d out of bounds for length %d", index, length());
2326     Element* data = data_pointer();
2327     return data[index];
2328   }
2329 
2330   // Private construtor. Use allocate() to get an instance.
2331   AdapterFingerPrint(const GrowableArray<SigEntry>* sig, bool has_ro_adapter)
2332     : _has_ro_adapter(has_ro_adapter), _length(total_args_passed_in_sig(sig)) {
2333     Element* data = data_pointer();
2334     BasicType prev_bt = T_ILLEGAL;
2335     int vt_count = 0;

2336     for (int index = 0; index < _length; index++) {
2337       const SigEntry& sig_entry = sig->at(index);
2338       BasicType bt = sig_entry._bt;
2339       if (bt == T_METADATA) {
2340         // Found start of inline type in signature
2341         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
2342         vt_count++;
2343       } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
2344         // Found end of inline type in signature
2345         assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
2346         vt_count--;
2347         assert(vt_count >= 0, "invalid vt_count");
2348       } else if (vt_count == 0) {
2349         // Widen fields that are not part of a scalarized inline type argument
2350         assert(sig_entry._offset == -1, "invalid offset for argument that is not a flattened field %d", sig_entry._offset);
2351         bt = adapter_encoding(bt);
2352       }
2353 
2354       ::new(&data[index]) Element(bt, sig_entry._offset);
2355       prev_bt = bt;
2356     }
2357     assert(vt_count == 0, "invalid vt_count");
2358   }
2359 
2360   // Call deallocate instead
2361   ~AdapterFingerPrint() {
2362     ShouldNotCallThis();
2363   }
2364 
2365   static int total_args_passed_in_sig(const GrowableArray<SigEntry>* sig) {
2366     return (sig != nullptr) ? sig->length() : 0;
2367   }
2368 
2369   static int compute_size_in_words(int len) {
2370     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(Element)));
2371   }
2372 
2373   // Remap BasicTypes that are handled equivalently by the adapters.
2374   // These are correct for the current system but someday it might be
2375   // necessary to make this mapping platform dependent.
2376   static BasicType adapter_encoding(BasicType in) {
2377     switch (in) {
2378       case T_BOOLEAN:
2379       case T_BYTE:
2380       case T_SHORT:
2381       case T_CHAR:
2382         // They are all promoted to T_INT in the calling convention
2383         return T_INT;
2384 
2385       case T_OBJECT:
2386       case T_ARRAY:
2387         // In other words, we assume that any register good enough for
2388         // an int or long is good enough for a managed pointer.
2389 #ifdef _LP64
2390         return T_LONG;
2391 #else
2392         return T_INT;
2393 #endif
2394 
2395       case T_INT:
2396       case T_LONG:
2397       case T_FLOAT:
2398       case T_DOUBLE:
2399       case T_VOID:
2400         return in;
2401 
2402       default:
2403         ShouldNotReachHere();
2404         return T_CONFLICT;
2405     }
2406   }
2407 
2408   void* operator new(size_t size, size_t fp_size) throw() {
2409     assert(fp_size >= size, "sanity check");
2410     void* p = AllocateHeap(fp_size, mtCode);
2411     memset(p, 0, fp_size);
2412     return p;
2413   }
2414 
2415 public:
2416   template<typename Function>
2417   void iterate_args(Function function) {
2418     for (int i = 0; i < length(); i++) {
2419       function(element_at(i));









2420     }
2421   }
2422 
2423   static AdapterFingerPrint* allocate(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2424     int len = total_args_passed_in_sig(sig);

2425     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2426     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(sig, has_ro_adapter);
2427     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2428     return afp;
2429   }
2430 
2431   static void deallocate(AdapterFingerPrint* fp) {
2432     FreeHeap(fp);
2433   }
2434 
2435   bool has_ro_adapter() const {
2436     return _has_ro_adapter;

2437   }
2438 
2439   int length() const {
2440     return _length;
2441   }
2442 
2443   unsigned int compute_hash() {
2444     int hash = 0;
2445     for (int i = 0; i < length(); i++) {
2446       const Element& v = element_at(i);
2447       //Add arithmetic operation to the hash, like +3 to improve hashing
2448       hash = ((hash << 8) ^ v.hash() ^ (hash >> 5)) + 3;
2449     }
2450     return (unsigned int)hash;
2451   }
2452 
2453   const char* as_string() {
2454     stringStream st;
2455     st.print("{");
2456     if (_has_ro_adapter) {
2457       st.print("has_ro_adapter");
2458     } else {
2459       st.print("no_ro_adapter");
2460     }
2461     for (int i = 0; i < length(); i++) {
2462       st.print(", ");
2463       const Element& elem = element_at(i);
2464       st.print("{%s, %d}", type2name(elem.bt()), elem.offset());
2465     }
2466     st.print("}");
2467     return st.as_string();
2468   }
2469 
2470   const char* as_basic_args_string() {
2471     stringStream st;
2472     bool long_prev = false;
2473     iterate_args([&] (const Element& arg) {
2474       if (long_prev) {
2475         long_prev = false;
2476         if (arg.bt() == T_VOID) {
2477           st.print("J");
2478         } else {
2479           st.print("L");
2480         }
2481       }
2482       if (arg.bt() == T_LONG) {
2483         long_prev = true;
2484       } else if (arg.bt() != T_VOID) {
2485         st.print("%c", type2char(arg.bt()));



2486       }
2487     });
2488     if (long_prev) {
2489       st.print("L");
2490     }
2491     return st.as_string();
2492   }
2493 



















































2494   bool equals(AdapterFingerPrint* other) {
2495     if (other->_has_ro_adapter != _has_ro_adapter) {
2496       return false;
2497     } else if (other->_length != _length) {
2498       return false;
2499     } else {
2500       for (int i = 0; i < _length; i++) {
2501         if (element_at(i) != other->element_at(i)) {
2502           return false;
2503         }
2504       }
2505     }
2506     return true;
2507   }
2508 
2509   // methods required by virtue of being a MetaspaceObj
2510   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2511   int size() const { return compute_size_in_words(_length); }
2512   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2513 
2514   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2515     NOT_PRODUCT(_equals++);
2516     return fp1->equals(fp2);
2517   }
2518 
2519   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2520     return fp->compute_hash();
2521   }

2524 #if INCLUDE_CDS
2525 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2526   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2527 }
2528 
2529 class ArchivedAdapterTable : public OffsetCompactHashtable<
2530   AdapterFingerPrint*,
2531   AdapterHandlerEntry*,
2532   adapter_fp_equals_compact_hashtable_entry> {};
2533 #endif // INCLUDE_CDS
2534 
2535 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2536 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2537                   AnyObj::C_HEAP, mtCode,
2538                   AdapterFingerPrint::compute_hash,
2539                   AdapterFingerPrint::equals>;
2540 static AdapterHandlerTable* _adapter_handler_table;
2541 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2542 
2543 // Find a entry with the same fingerprint if it exists
2544 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(const GrowableArray<SigEntry>* sig, bool has_ro_adapter) {
2545   NOT_PRODUCT(_lookups++);
2546   assert_lock_strong(AdapterHandlerLibrary_lock);
2547   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(sig, has_ro_adapter);
2548   AdapterHandlerEntry* entry = nullptr;
2549 #if INCLUDE_CDS
2550   // if we are building the archive then the archived adapter table is
2551   // not valid and we need to use the ones added to the runtime table
2552   if (AOTCodeCache::is_using_adapter()) {
2553     // Search archived table first. It is read-only table so can be searched without lock
2554     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2555 #ifndef PRODUCT
2556     if (entry != nullptr) {
2557       _archived_hits++;
2558     }
2559 #endif
2560   }
2561 #endif // INCLUDE_CDS
2562   if (entry == nullptr) {
2563     assert_lock_strong(AdapterHandlerLibrary_lock);
2564     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2565     if (entry_p != nullptr) {
2566       entry = *entry_p;
2567       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2584   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2585   ts.print(tty, "AdapterHandlerTable");
2586   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2587                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2588   int total_hits = _archived_hits + _runtime_hits;
2589   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2590                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2591 }
2592 #endif
2593 
2594 // ---------------------------------------------------------------------------
2595 // Implementation of AdapterHandlerLibrary
2596 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2597 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2598 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2599 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2600 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2601 #if INCLUDE_CDS
2602 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2603 #endif // INCLUDE_CDS
2604 static const int AdapterHandlerLibrary_size = 48*K;
2605 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2606 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2607 
2608 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2609   assert(_buffer != nullptr, "should be initialized");
2610   return _buffer;
2611 }
2612 
2613 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2614   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2615     AdapterBlob* adapter_blob = entry->adapter_blob();
2616     char blob_id[256];
2617     jio_snprintf(blob_id,
2618                  sizeof(blob_id),
2619                  "%s(%s)",
2620                  adapter_blob->name(),
2621                  entry->fingerprint()->as_string());
2622     if (Forte::is_enabled()) {
2623       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2624     }

2632 void AdapterHandlerLibrary::initialize() {
2633   {
2634     ResourceMark rm;
2635     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2636     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2637   }
2638 
2639 #if INCLUDE_CDS
2640   // Link adapters in AOT Cache to their code in AOT Code Cache
2641   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2642     link_aot_adapters();
2643     lookup_simple_adapters();
2644     return;
2645   }
2646 #endif // INCLUDE_CDS
2647 
2648   ResourceMark rm;
2649   {
2650     MutexLocker mu(AdapterHandlerLibrary_lock);
2651 
2652     CompiledEntrySignature no_args;
2653     no_args.compute_calling_conventions();
2654     _no_arg_handler = create_adapter(no_args, true);
2655 
2656     CompiledEntrySignature obj_args;
2657     SigEntry::add_entry(obj_args.sig(), T_OBJECT);
2658     obj_args.compute_calling_conventions();
2659     _obj_arg_handler = create_adapter(obj_args, true);
2660 
2661     CompiledEntrySignature int_args;
2662     SigEntry::add_entry(int_args.sig(), T_INT);
2663     int_args.compute_calling_conventions();
2664     _int_arg_handler = create_adapter(int_args, true);
2665 
2666     CompiledEntrySignature obj_int_args;
2667     SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
2668     SigEntry::add_entry(obj_int_args.sig(), T_INT);
2669     obj_int_args.compute_calling_conventions();
2670     _obj_int_arg_handler = create_adapter(obj_int_args, true);
2671 
2672     CompiledEntrySignature obj_obj_args;
2673     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2674     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2675     obj_obj_args.compute_calling_conventions();
2676     _obj_obj_arg_handler = create_adapter(obj_obj_args, true);
2677 
2678     // we should always get an entry back but we don't have any
2679     // associated blob on Zero
2680     assert(_no_arg_handler != nullptr &&
2681            _obj_arg_handler != nullptr &&
2682            _int_arg_handler != nullptr &&
2683            _obj_int_arg_handler != nullptr &&
2684            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2685   }
2686 
2687   // Outside of the lock
2688 #ifndef ZERO
2689   // no blobs to register when we are on Zero
2690   post_adapter_creation(_no_arg_handler);
2691   post_adapter_creation(_obj_arg_handler);
2692   post_adapter_creation(_int_arg_handler);
2693   post_adapter_creation(_obj_int_arg_handler);
2694   post_adapter_creation(_obj_obj_arg_handler);
2695 #endif // ZERO
2696 }
2697 
2698 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2699   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2700   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2701   return AdapterHandlerEntry::allocate(id, fingerprint);
2702 }
2703 
2704 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2705   int total_args_passed = method->size_of_parameters(); // All args on stack
2706   if (total_args_passed == 0) {
2707     return _no_arg_handler;
2708   } else if (total_args_passed == 1) {
2709     if (!method->is_static()) {
2710       if (InlineTypePassFieldsAsArgs && method->method_holder()->is_inline_klass()) {
2711         return nullptr;
2712       }
2713       return _obj_arg_handler;
2714     }
2715     switch (method->signature()->char_at(1)) {
2716       case JVM_SIGNATURE_CLASS: {
2717         if (InlineTypePassFieldsAsArgs) {
2718           SignatureStream ss(method->signature());
2719           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2720           if (vk != nullptr) {
2721             return nullptr;
2722           }
2723         }
2724         return _obj_arg_handler;
2725       }
2726       case JVM_SIGNATURE_ARRAY:
2727         return _obj_arg_handler;
2728       case JVM_SIGNATURE_INT:
2729       case JVM_SIGNATURE_BOOLEAN:
2730       case JVM_SIGNATURE_CHAR:
2731       case JVM_SIGNATURE_BYTE:
2732       case JVM_SIGNATURE_SHORT:
2733         return _int_arg_handler;
2734     }
2735   } else if (total_args_passed == 2 &&
2736              !method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2737     switch (method->signature()->char_at(1)) {
2738       case JVM_SIGNATURE_CLASS: {
2739         if (InlineTypePassFieldsAsArgs) {
2740           SignatureStream ss(method->signature());
2741           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2742           if (vk != nullptr) {
2743             return nullptr;
2744           }
2745         }
2746         return _obj_obj_arg_handler;
2747       }
2748       case JVM_SIGNATURE_ARRAY:
2749         return _obj_obj_arg_handler;
2750       case JVM_SIGNATURE_INT:
2751       case JVM_SIGNATURE_BOOLEAN:
2752       case JVM_SIGNATURE_CHAR:
2753       case JVM_SIGNATURE_BYTE:
2754       case JVM_SIGNATURE_SHORT:
2755         return _obj_int_arg_handler;
2756     }
2757   }
2758   return nullptr;
2759 }
2760 
2761 CompiledEntrySignature::CompiledEntrySignature(Method* method) :
2762   _method(method), _num_inline_args(0), _has_inline_recv(false),
2763   _regs(nullptr), _regs_cc(nullptr), _regs_cc_ro(nullptr),
2764   _args_on_stack(0), _args_on_stack_cc(0), _args_on_stack_cc_ro(0),
2765   _c1_needs_stack_repair(false), _c2_needs_stack_repair(false), _supers(nullptr) {
2766   _sig = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2767   _sig_cc = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2768   _sig_cc_ro = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2769 }
2770 
2771 // See if we can save space by sharing the same entry for VIEP and VIEP(RO),
2772 // or the same entry for VEP and VIEP(RO).
2773 CodeOffsets::Entries CompiledEntrySignature::c1_inline_ro_entry_type() const {
2774   if (!has_scalarized_args()) {
2775     // VEP/VIEP/VIEP(RO) all share the same entry. There's no packing.
2776     return CodeOffsets::Verified_Entry;
2777   }
2778   if (_method->is_static()) {
2779     // Static methods don't need VIEP(RO)
2780     return CodeOffsets::Verified_Entry;
2781   }
2782 
2783   if (has_inline_recv()) {
2784     if (num_inline_args() == 1) {
2785       // Share same entry for VIEP and VIEP(RO).
2786       // This is quite common: we have an instance method in an InlineKlass that has
2787       // no inline type args other than <this>.
2788       return CodeOffsets::Verified_Inline_Entry;
2789     } else {
2790       assert(num_inline_args() > 1, "must be");
2791       // No sharing:
2792       //   VIEP(RO) -- <this> is passed as object
2793       //   VEP      -- <this> is passed as fields
2794       return CodeOffsets::Verified_Inline_Entry_RO;
2795     }

2796   }
2797 
2798   // Either a static method, or <this> is not an inline type
2799   if (args_on_stack_cc() != args_on_stack_cc_ro()) {
2800     // No sharing:
2801     // Some arguments are passed on the stack, and we have inserted reserved entries
2802     // into the VEP, but we never insert reserved entries into the VIEP(RO).
2803     return CodeOffsets::Verified_Inline_Entry_RO;
2804   } else {
2805     // Share same entry for VEP and VIEP(RO).
2806     return CodeOffsets::Verified_Entry;
2807   }
2808 }
2809 
2810 // Returns all super methods (transitive) in classes and interfaces that are overridden by the current method.
2811 GrowableArray<Method*>* CompiledEntrySignature::get_supers() {
2812   if (_supers != nullptr) {
2813     return _supers;
2814   }
2815   _supers = new GrowableArray<Method*>();
2816   // Skip private, static, and <init> methods
2817   if (_method->is_private() || _method->is_static() || _method->is_object_constructor()) {
2818     return _supers;
2819   }
2820   Symbol* name = _method->name();
2821   Symbol* signature = _method->signature();
2822   const Klass* holder = _method->method_holder()->super();
2823   Symbol* holder_name = holder->name();
2824   JavaThread* current = JavaThread::current();
2825   HandleMark hm(current);
2826   Handle loader(current, _method->method_holder()->class_loader());
2827 
2828   // Walk up the class hierarchy and search for super methods
2829   while (holder != nullptr) {
2830     Method* super_method = holder->lookup_method(name, signature);
2831     if (super_method == nullptr) {
2832       break;
2833     }
2834     if (!super_method->is_static() && !super_method->is_private() &&
2835         (!super_method->is_package_private() ||
2836          super_method->method_holder()->is_same_class_package(loader(), holder_name))) {
2837       _supers->push(super_method);
2838     }
2839     holder = super_method->method_holder()->super();
2840   }
2841   // Search interfaces for super methods
2842   Array<InstanceKlass*>* interfaces = _method->method_holder()->transitive_interfaces();
2843   for (int i = 0; i < interfaces->length(); ++i) {
2844     Method* m = interfaces->at(i)->lookup_method(name, signature);
2845     if (m != nullptr && !m->is_static() && m->is_public()) {
2846       _supers->push(m);
2847     }
2848   }
2849   return _supers;
2850 }
2851 
2852 bool CompiledEntrySignature::check_supers_and_deoptimize(int arg_num) {
2853   assert(JavaThread::current()->thread_state() == _thread_in_vm, "must be in vm state");
2854 
2855   bool scalar_super = false;
2856   bool non_scalar_super = false;
2857 
2858   GrowableArray<Method*>* supers = get_supers();
2859   for (int i = 0; i < supers->length(); ++i) {
2860     Method* super_method = supers->at(i);
2861     if (super_method->is_scalarized_arg(arg_num)) {
2862       scalar_super = true;
2863     } else {
2864       non_scalar_super = true;
2865     }
2866   }
2867 #ifdef ASSERT
2868   // Randomly enable below code paths for stress testing
2869   bool stress = StressCallingConvention;
2870   if (stress && (os::random() & 1) == 1) {
2871     non_scalar_super = true;
2872     if ((os::random() & 1) == 1) {
2873       scalar_super = true;
2874     }
2875   }
2876 #endif
2877   if (non_scalar_super) {
2878     // Found a super method with a non-scalarized argument. Fall back to the non-scalarized calling convention.
2879     if (scalar_super) {
2880       // Found non-scalar *and* scalar super methods. We can't handle both.
2881       // Mark the scalar method as mismatch and re-compile call sites to use non-scalarized calling convention.
2882       for (int i = 0; i < supers->length(); ++i) {
2883         Method* super_method = supers->at(i);
2884         if (super_method->is_scalarized_arg(arg_num) DEBUG_ONLY(|| (stress && (os::random() & 1) == 1))) {
2885           JavaThread* thread = JavaThread::current();
2886           HandleMark hm(thread);
2887           methodHandle mh(thread, super_method);
2888           DeoptimizationScope deopt_scope;
2889           {
2890             // Keep the lock scope minimal. Prevent interference with other
2891             // dependency checks by setting mismatch and marking within the lock.
2892             MutexLocker ml(Compile_lock, Mutex::_safepoint_check_flag);
2893             super_method->set_mismatch();
2894             CodeCache::mark_for_deoptimization(&deopt_scope, mh());
2895           }
2896           deopt_scope.deoptimize_marked();
2897         }
2898       }
2899     }
2900   }
2901 
2902   return non_scalar_super;
2903 }
2904 
2905 // Iterate over arguments and compute scalarized and non-scalarized signatures
2906 void CompiledEntrySignature::compute_calling_conventions(bool link_time) {
2907   assert(JavaThread::current()->thread_state() != _thread_in_native, "must not be in native");
2908   assert(link_time || (_method != nullptr && _method->adapter() != nullptr), "invariant");
2909   bool has_scalarized = false;
2910   if (_method != nullptr) {
2911     InstanceKlass* holder = _method->method_holder();
2912     int arg_num = 0;
2913     if (!_method->is_static()) {
2914       // We shouldn't scalarize 'this' in a value class constructor
2915       if (holder->is_inline_klass() && InlineKlass::cast(holder)->can_be_passed_as_fields() &&
2916           !_method->is_object_constructor() && (link_time || _method->is_scalarized_arg(arg_num))) {
2917         _sig_cc->appendAll(InlineKlass::cast(holder)->extended_sig());
2918         _sig_cc->insert_before(1, SigEntry(T_OBJECT, 0, nullptr, false, true)); // buffer argument
2919         has_scalarized = true;
2920         _has_inline_recv = true;
2921         _num_inline_args++;
2922       } else {
2923         SigEntry::add_entry(_sig_cc, T_OBJECT, holder->name());
2924       }
2925       SigEntry::add_entry(_sig, T_OBJECT, holder->name());
2926       SigEntry::add_entry(_sig_cc_ro, T_OBJECT, holder->name());
2927       arg_num++;
2928     }
2929     for (SignatureStream ss(_method->signature()); !ss.at_return_type(); ss.next()) {
2930       const BasicType bt = ss.type();
2931       if (InlineTypePassFieldsAsArgs && bt == T_OBJECT) {
2932         InlineKlass* vk = ss.as_inline_klass(holder);
2933         if (vk != nullptr && vk->can_be_passed_as_fields() && (link_time || _method->is_scalarized_arg(arg_num))) {
2934           // Check for a calling convention mismatch with super method(s)
2935           if (link_time && check_supers_and_deoptimize(arg_num)) {
2936             // Fall back to non-scalarized calling convention
2937             SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2938             SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2939           } else {
2940             _num_inline_args++;
2941             has_scalarized = true;
2942             int last = _sig_cc->length();
2943             int last_ro = _sig_cc_ro->length();
2944             _sig_cc->appendAll(vk->extended_sig());
2945             _sig_cc_ro->appendAll(vk->extended_sig());
2946             // buffer argument
2947             _sig_cc->insert_before(last + 1, SigEntry(T_OBJECT, 0, nullptr, false, true));
2948             _sig_cc_ro->insert_before(last_ro + 1, SigEntry(T_OBJECT, 0, nullptr, false, true));
2949             // Insert InlineTypeNode::NullMarker field right after T_METADATA delimiter
2950             _sig_cc->insert_before(last + 2, SigEntry(T_BOOLEAN, -1, nullptr, true, false));
2951             _sig_cc_ro->insert_before(last_ro + 2, SigEntry(T_BOOLEAN, -1, nullptr, true, false));
2952           }
2953         } else {
2954           SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2955           SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2956         }
2957       } else {
2958         SigEntry::add_entry(_sig_cc, ss.type(), ss.as_symbol());
2959         SigEntry::add_entry(_sig_cc_ro, ss.type(), ss.as_symbol());
2960       }
2961       SigEntry::add_entry(_sig, bt, ss.as_symbol());
2962       if (bt != T_VOID) {
2963         arg_num++;
2964       }
2965     }
2966   }

2967 
2968   // Compute the non-scalarized calling convention
2969   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
2970   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
2971 
2972   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
2973   if (has_scalarized && !_method->is_native()) {
2974     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
2975     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
2976 
2977     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
2978     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
2979 
2980     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
2981     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
2982 
2983     // Upper bound on stack arguments to avoid hitting the argument limit and
2984     // bailing out of compilation ("unsupported incoming calling sequence").
2985     // TODO 8281260 We need a reasonable limit (flag?) here
2986     if (MAX2(_args_on_stack_cc, _args_on_stack_cc_ro) <= 75) {
2987       return; // Success
2988     }
2989   }
2990 
2991   // No scalarized args
2992   _sig_cc = _sig;
2993   _regs_cc = _regs;
2994   _args_on_stack_cc = _args_on_stack;
2995 
2996   _sig_cc_ro = _sig;
2997   _regs_cc_ro = _regs;
2998   _args_on_stack_cc_ro = _args_on_stack;
2999 }
3000 
3001 void CompiledEntrySignature::initialize_from_fingerprint(AdapterFingerPrint* fingerprint) {
3002   _has_inline_recv = fingerprint->has_ro_adapter();
3003 
3004   int value_object_count = 0;
3005   BasicType prev_bt = T_ILLEGAL;
3006   bool has_scalarized_arguments = false;
3007   bool long_prev = false;
3008   int long_prev_offset = -1;
3009   bool skipping_inline_recv = false;
3010   bool receiver_handled = false;
3011 
3012   fingerprint->iterate_args([&] (const AdapterFingerPrint::Element& arg) {
3013     BasicType bt = arg.bt();
3014     int offset = arg.offset();
3015 
3016     if (long_prev) {
3017       long_prev = false;
3018       BasicType bt_to_add;
3019       if (bt == T_VOID) {
3020         bt_to_add = T_LONG;
3021       } else {
3022         bt_to_add = T_OBJECT;
3023       }
3024       if (value_object_count == 0) {
3025         SigEntry::add_entry(_sig, bt_to_add);
3026       }
3027       assert(long_prev_offset != 0, "no buffer argument here");
3028       SigEntry::add_entry(_sig_cc, bt_to_add, nullptr, long_prev_offset);
3029       if (!skipping_inline_recv) {
3030         SigEntry::add_entry(_sig_cc_ro, bt_to_add, nullptr, long_prev_offset);
3031       }
3032     }
3033 
3034     switch (bt) {
3035       case T_VOID:
3036         if (prev_bt != T_LONG && prev_bt != T_DOUBLE) {
3037           assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
3038           value_object_count--;
3039           SigEntry::add_entry(_sig_cc, T_VOID, nullptr, offset);
3040           if (!skipping_inline_recv) {
3041             SigEntry::add_entry(_sig_cc_ro, T_VOID, nullptr, offset);
3042           } else if (value_object_count == 0) {
3043             skipping_inline_recv = false;
3044           }
3045           assert(value_object_count >= 0, "invalid value object count");
3046         } else {
3047           // Nothing to add for _sig: We already added an addition T_VOID in add_entry() when adding T_LONG or T_DOUBLE.
3048         }
3049         break;
3050       case T_INT:
3051       case T_FLOAT:
3052       case T_DOUBLE:
3053         if (value_object_count == 0) {
3054           SigEntry::add_entry(_sig, bt);
3055         }
3056         SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3057         if (!skipping_inline_recv) {
3058           SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3059         }
3060         break;
3061       case T_LONG:
3062         long_prev = true;
3063         long_prev_offset = offset;
3064         break;
3065       case T_BOOLEAN:
3066       case T_CHAR:
3067       case T_BYTE:
3068       case T_SHORT:
3069       case T_OBJECT:
3070       case T_ARRAY:
3071         assert(value_object_count > 0, "must be value object field");
3072         assert(offset != 0 || (bt == T_OBJECT && prev_bt == T_METADATA), "buffer input expected here");
3073         SigEntry::add_entry(_sig_cc, bt, nullptr, offset, offset == -1, offset == 0);
3074         if (!skipping_inline_recv) {
3075           SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset, offset == -1, offset == 0);
3076         }
3077         break;
3078       case T_METADATA:
3079         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
3080         if (value_object_count == 0) {
3081           SigEntry::add_entry(_sig, T_OBJECT);
3082         }
3083         SigEntry::add_entry(_sig_cc, T_METADATA, nullptr, offset);
3084         if (!skipping_inline_recv) {
3085           if (!receiver_handled && _has_inline_recv && value_object_count == 0) {
3086             SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3087             skipping_inline_recv = true;
3088             receiver_handled = true;
3089           } else {
3090             SigEntry::add_entry(_sig_cc_ro, T_METADATA, nullptr, offset);
3091           }
3092         }
3093         value_object_count++;
3094         has_scalarized_arguments = true;
3095         break;
3096       default: {
3097         fatal("Unexpected BasicType: %s", basictype_to_str(bt));
3098       }
3099     }
3100     prev_bt = bt;
3101   });
3102 
3103   if (long_prev) {
3104     // If previous bt was T_LONG and we reached the end of the signature, we know that it must be a T_OBJECT.
3105     SigEntry::add_entry(_sig, T_OBJECT);
3106     SigEntry::add_entry(_sig_cc, T_OBJECT);
3107     SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3108   }
3109   assert(value_object_count == 0, "invalid value object count");
3110 
3111 #ifdef ASSERT
3112   if (_has_inline_recv) {
3113     // In RO signatures, inline receivers must be represented as a single T_OBJECT
3114     assert(_sig_cc_ro->length() >= 1, "sig_cc_ro must include receiver");
3115     assert(_sig_cc_ro->at(0)._bt == T_OBJECT,
3116            "sig_cc_ro must represent inline receiver as T_OBJECT");
3117     assert(_sig_cc_ro->length() <= _sig_cc->length(),
3118            "sig_cc_ro must not be longer than sig_cc");
3119   }
3120 #endif
3121 
3122   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
3123   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
3124 
3125   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
3126   if (has_scalarized_arguments) {
3127     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3128     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3129 
3130     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3131     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3132 
3133     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3134     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3135   } else {
3136     // No scalarized args
3137     _sig_cc = _sig;
3138     _regs_cc = _regs;
3139     _args_on_stack_cc = _args_on_stack;
3140 
3141     _sig_cc_ro = _sig;
3142     _regs_cc_ro = _regs;
3143     _args_on_stack_cc_ro = _args_on_stack;
3144   }
3145 
3146 #ifdef ASSERT
3147   {
3148     AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(_sig_cc, _has_inline_recv);
3149     assert(fingerprint->equals(compare_fp), "%s - %s", fingerprint->as_string(), compare_fp->as_string());
3150     AdapterFingerPrint::deallocate(compare_fp);
3151   }
3152 #endif
3153 }
3154 
3155 const char* AdapterHandlerEntry::_entry_names[] = {
3156   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
3157 };
3158 
3159 #ifdef ASSERT
3160 void AdapterHandlerLibrary::verify_adapter_sharing(CompiledEntrySignature& ces, AdapterHandlerEntry* cached_entry) {
3161   // we can only check for the same code if there is any
3162 #ifndef ZERO
3163   AdapterHandlerEntry* comparison_entry = create_adapter(ces, false, true);
3164   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
3165   assert(comparison_entry->compare_code(cached_entry), "code must match");
3166   // Release the one just created
3167   AdapterHandlerEntry::deallocate(comparison_entry);
3168 # endif // ZERO
3169 }
3170 #endif /* ASSERT*/
3171 
3172 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
3173   assert(!method->is_abstract() || InlineTypePassFieldsAsArgs, "abstract methods do not have adapters");
3174   // Use customized signature handler.  Need to lock around updates to
3175   // the _adapter_handler_table (it is not safe for concurrent readers
3176   // and a single writer: this could be fixed if it becomes a
3177   // problem).
3178 
3179   // Fast-path for trivial adapters
3180   AdapterHandlerEntry* entry = get_simple_adapter(method);
3181   if (entry != nullptr) {
3182     return entry;
3183   }
3184 
3185   ResourceMark rm;
3186   bool new_entry = false;
3187 
3188   CompiledEntrySignature ces(method());
3189   ces.compute_calling_conventions();
3190   if (ces.has_scalarized_args()) {
3191     if (!method->has_scalarized_args()) {
3192       method->set_has_scalarized_args();
3193     }
3194     if (ces.c1_needs_stack_repair()) {
3195       method->set_c1_needs_stack_repair();
3196     }
3197     if (ces.c2_needs_stack_repair() && !method->c2_needs_stack_repair()) {
3198       method->set_c2_needs_stack_repair();
3199     }
3200   }
3201 




3202   {
3203     MutexLocker mu(AdapterHandlerLibrary_lock);
3204 
3205     // Lookup method signature's fingerprint
3206     entry = lookup(ces.sig_cc(), ces.has_inline_recv());
3207 
3208     if (entry != nullptr) {
3209 #ifndef ZERO
3210       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
3211 #endif
3212 #ifdef ASSERT
3213       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
3214         verify_adapter_sharing(ces, entry);
3215       }
3216 #endif
3217     } else {
3218       entry = create_adapter(ces, /* allocate_code_blob */ true);
3219       if (entry != nullptr) {
3220         new_entry = true;
3221       }
3222     }
3223   }
3224 
3225   // Outside of the lock
3226   if (new_entry) {
3227     post_adapter_creation(entry);
3228   }
3229   return entry;
3230 }
3231 
3232 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
3233   ResourceMark rm;
3234   const char* name = AdapterHandlerLibrary::name(handler);
3235   const uint32_t id = AdapterHandlerLibrary::id(handler);
3236 
3237   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
3238   if (blob != nullptr) {

3253   }
3254   insts_size = adapter_blob->code_size();
3255   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
3256                 handler->fingerprint()->as_basic_args_string(),
3257                 handler->fingerprint()->as_string(), insts_size);
3258   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
3259   if (Verbose || PrintStubCode) {
3260     address first_pc = adapter_blob->content_begin();
3261     if (first_pc != nullptr) {
3262       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
3263       st->cr();
3264     }
3265   }
3266 }
3267 #endif // PRODUCT
3268 
3269 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
3270                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
3271   entry_offset[AdapterBlob::I2C] = 0;
3272   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];
3273   entry_offset[AdapterBlob::C2I_Inline] = entry_address[AdapterBlob::C2I_Inline] - entry_address[AdapterBlob::I2C];
3274   entry_offset[AdapterBlob::C2I_Inline_RO] = entry_address[AdapterBlob::C2I_Inline_RO] - entry_address[AdapterBlob::I2C];
3275   entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];
3276   entry_offset[AdapterBlob::C2I_Unverified_Inline] = entry_address[AdapterBlob::C2I_Unverified_Inline] - entry_address[AdapterBlob::I2C];
3277   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
3278     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
3279   } else {
3280     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
3281   }
3282 }
3283 
3284 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
3285                                                   CompiledEntrySignature& ces,
3286                                                   bool allocate_code_blob,
3287                                                   bool is_transient) {
3288   if (log_is_enabled(Info, perf, class, link)) {
3289     ClassLoader::perf_method_adapters_count()->inc();
3290   }
3291 
3292 #ifndef ZERO
3293   AdapterBlob* adapter_blob = nullptr;
3294   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3295   CodeBuffer buffer(buf);
3296   short buffer_locs[20];
3297   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3298                                          sizeof(buffer_locs)/sizeof(relocInfo));
3299   MacroAssembler masm(&buffer);
3300   address entry_address[AdapterBlob::ENTRY_COUNT];

3301 
3302   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage


3303   SharedRuntime::generate_i2c2i_adapters(&masm,
3304                                          ces.args_on_stack(),
3305                                          ces.sig(),
3306                                          ces.regs(),
3307                                          ces.sig_cc(),
3308                                          ces.regs_cc(),
3309                                          ces.sig_cc_ro(),
3310                                          ces.regs_cc_ro(),
3311                                          entry_address,
3312                                          adapter_blob,
3313                                          allocate_code_blob);
3314 
3315   if (ces.has_scalarized_args()) {
3316     // Save a C heap allocated version of the scalarized signature and store it in the adapter
3317     GrowableArray<SigEntry>* heap_sig = new (mtCode) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtCode);
3318     heap_sig->appendAll(ces.sig_cc());
3319     handler->set_sig_cc(heap_sig);
3320     heap_sig = new (mtCode) GrowableArray<SigEntry>(ces.sig_cc_ro()->length(), mtCode);
3321     heap_sig->appendAll(ces.sig_cc_ro());
3322     handler->set_sig_cc_ro(heap_sig);
3323   }
3324   // On zero there is no code to save and no need to create a blob and
3325   // or relocate the handler.
3326   int entry_offset[AdapterBlob::ENTRY_COUNT];
3327   address_to_offset(entry_address, entry_offset);
3328 #ifdef ASSERT
3329   if (VerifyAdapterSharing) {
3330     handler->save_code(buf->code_begin(), buffer.insts_size());
3331     if (is_transient) {
3332       return true;
3333     }
3334   }
3335 #endif

3336   if (adapter_blob == nullptr) {
3337     // CodeCache is full, disable compilation
3338     // Ought to log this but compile log is only per compile thread
3339     // and we're some non descript Java thread.
3340     return false;
3341   }
3342   handler->set_adapter_blob(adapter_blob);
3343   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
3344     // try to save generated code
3345     const char* name = AdapterHandlerLibrary::name(handler);
3346     const uint32_t id = AdapterHandlerLibrary::id(handler);
3347     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
3348     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
3349   }
3350 #endif // ZERO
3351 
3352 #ifndef PRODUCT
3353   // debugging support
3354   if (PrintAdapterHandlers || PrintStubCode) {
3355     print_adapter_handler_info(tty, handler);
3356   }
3357 #endif
3358 
3359   return true;
3360 }
3361 
3362 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(CompiledEntrySignature& ces,
3363                                                            bool allocate_code_blob,
3364                                                            bool is_transient) {
3365   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(ces.sig_cc(), ces.has_inline_recv());
3366 #ifdef ASSERT
3367   // Verify that we can successfully restore the compiled entry signature object.
3368   CompiledEntrySignature ces_verify;
3369   ces_verify.initialize_from_fingerprint(fp);
3370 #endif
3371   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
3372   if (!generate_adapter_code(handler, ces, allocate_code_blob, is_transient)) {
3373     AdapterHandlerEntry::deallocate(handler);
3374     return nullptr;
3375   }
3376   if (!is_transient) {
3377     assert_lock_strong(AdapterHandlerLibrary_lock);
3378     _adapter_handler_table->put(fp, handler);
3379   }
3380   return handler;
3381 }
3382 
3383 #if INCLUDE_CDS
3384 void AdapterHandlerEntry::remove_unshareable_info() {
3385 #ifdef ASSERT
3386    _saved_code = nullptr;
3387    _saved_code_length = 0;
3388 #endif // ASSERT
3389    _adapter_blob = nullptr;
3390    _linked = false;
3391    _sig_cc = nullptr;
3392    _sig_cc_ro = nullptr;
3393 }
3394 
3395 class CopyAdapterTableToArchive : StackObj {
3396 private:
3397   CompactHashtableWriter* _writer;
3398   ArchiveBuilder* _builder;
3399 public:
3400   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
3401                                                              _builder(ArchiveBuilder::current())
3402   {}
3403 
3404   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
3405     LogStreamHandle(Trace, aot) lsh;
3406     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
3407       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
3408       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
3409       assert(buffered_fp != nullptr,"sanity check");
3410       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
3411       assert(buffered_entry != nullptr,"sanity check");
3412 

3452   }
3453 #endif
3454 }
3455 
3456 // This method is used during production run to link archived adapters (stored in AOT Cache)
3457 // to their code in AOT Code Cache
3458 void AdapterHandlerEntry::link() {
3459   ResourceMark rm;
3460   assert(_fingerprint != nullptr, "_fingerprint must not be null");
3461   bool generate_code = false;
3462   // Generate code only if AOTCodeCache is not available, or
3463   // caching adapters is disabled, or we fail to link
3464   // the AdapterHandlerEntry to its code in the AOTCodeCache
3465   if (AOTCodeCache::is_using_adapter()) {
3466     AdapterHandlerLibrary::link_aot_adapter_handler(this);
3467     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
3468     if (_adapter_blob == nullptr) {
3469       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
3470       generate_code = true;
3471     }
3472 
3473     if (get_sig_cc() == nullptr) {
3474       // Calling conventions have to be regenerated at runtime and are accessed through method adapters,
3475       // which are archived in the AOT code cache. If the adapters are not regenerated, the
3476       // calling conventions should be regenerated here.
3477       CompiledEntrySignature ces;
3478       ces.initialize_from_fingerprint(_fingerprint);
3479       if (ces.has_scalarized_args()) {
3480         // Save a C heap allocated version of the scalarized signature and store it in the adapter
3481         GrowableArray<SigEntry>* heap_sig = new (mtCode) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtCode);
3482         heap_sig->appendAll(ces.sig_cc());
3483         set_sig_cc(heap_sig);
3484         heap_sig = new (mtCode) GrowableArray<SigEntry>(ces.sig_cc_ro()->length(), mtCode);
3485         heap_sig->appendAll(ces.sig_cc_ro());
3486         set_sig_cc_ro(heap_sig);
3487       }
3488     }
3489   } else {
3490     generate_code = true;
3491   }
3492   if (generate_code) {
3493     CompiledEntrySignature ces;
3494     ces.initialize_from_fingerprint(_fingerprint);
3495     if (!AdapterHandlerLibrary::generate_adapter_code(this, ces, true, false)) {
3496       // Don't throw exceptions during VM initialization because java.lang.* classes
3497       // might not have been initialized, causing problems when constructing the
3498       // Java exception object.
3499       vm_exit_during_initialization("Out of space in CodeCache for adapters");
3500     }
3501   }
3502   if (_adapter_blob != nullptr) {
3503     post_adapter_creation(this);
3504   }
3505   assert(_linked, "AdapterHandlerEntry must now be linked");
3506 }
3507 
3508 void AdapterHandlerLibrary::link_aot_adapters() {
3509   uint max_id = 0;
3510   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
3511   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
3512    * That implies adapter ids of the adapters in the cache may not be contiguous.
3513    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
3514    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
3515    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
3516    */
3517   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
3518     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
3519     entry->link();
3520     max_id = MAX2(max_id, entry->id());
3521   });
3522   // Set adapter id to the maximum id found in the AOTCache
3523   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
3524   _id_counter = max_id;
3525 }
3526 
3527 // This method is called during production run to lookup simple adapters
3528 // in the archived adapter handler table
3529 void AdapterHandlerLibrary::lookup_simple_adapters() {
3530   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3531 
3532   MutexLocker mu(AdapterHandlerLibrary_lock);
3533   ResourceMark rm;
3534   CompiledEntrySignature no_args;
3535   no_args.compute_calling_conventions();
3536   _no_arg_handler = lookup(no_args.sig_cc(), no_args.has_inline_recv());
3537 
3538   CompiledEntrySignature obj_args;
3539   SigEntry::add_entry(obj_args.sig(), T_OBJECT);
3540   obj_args.compute_calling_conventions();
3541   _obj_arg_handler = lookup(obj_args.sig_cc(), obj_args.has_inline_recv());
3542 
3543   CompiledEntrySignature int_args;
3544   SigEntry::add_entry(int_args.sig(), T_INT);
3545   int_args.compute_calling_conventions();
3546   _int_arg_handler = lookup(int_args.sig_cc(), int_args.has_inline_recv());
3547 
3548   CompiledEntrySignature obj_int_args;
3549   SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
3550   SigEntry::add_entry(obj_int_args.sig(), T_INT);
3551   obj_int_args.compute_calling_conventions();
3552   _obj_int_arg_handler = lookup(obj_int_args.sig_cc(), obj_int_args.has_inline_recv());
3553 
3554   CompiledEntrySignature obj_obj_args;
3555   SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3556   SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3557   obj_obj_args.compute_calling_conventions();
3558   _obj_obj_arg_handler = lookup(obj_obj_args.sig_cc(), obj_obj_args.has_inline_recv());
3559 
3560   assert(_no_arg_handler != nullptr &&
3561          _obj_arg_handler != nullptr &&
3562          _int_arg_handler != nullptr &&
3563          _obj_int_arg_handler != nullptr &&
3564          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3565   assert(_no_arg_handler->is_linked() &&
3566          _obj_arg_handler->is_linked() &&
3567          _int_arg_handler->is_linked() &&
3568          _obj_int_arg_handler->is_linked() &&
3569          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3570 }
3571 #endif // INCLUDE_CDS
3572 
3573 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3574   LogStreamHandle(Trace, aot) lsh;
3575   if (lsh.is_enabled()) {
3576     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3577     lsh.cr();
3578   }
3579   it->push(&_fingerprint);
3580 }
3581 
3582 AdapterHandlerEntry::~AdapterHandlerEntry() {
3583   if (_fingerprint != nullptr) {
3584     AdapterFingerPrint::deallocate(_fingerprint);
3585     _fingerprint = nullptr;
3586   }
3587   if (_sig_cc != nullptr) {
3588     delete _sig_cc;
3589   }
3590   if (_sig_cc_ro != nullptr) {
3591     delete _sig_cc_ro;
3592   }
3593 #ifdef ASSERT
3594   FREE_C_HEAP_ARRAY(_saved_code);
3595 #endif
3596   FreeHeap(this);
3597 }
3598 
3599 
3600 #ifdef ASSERT
3601 // Capture the code before relocation so that it can be compared
3602 // against other versions.  If the code is captured after relocation
3603 // then relative instructions won't be equivalent.
3604 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3605   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3606   _saved_code_length = length;
3607   memcpy(_saved_code, buffer, length);
3608 }
3609 
3610 
3611 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3612   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");

3662       struct { double data[20]; } stubs_locs_buf;
3663       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3664 #if defined(AARCH64)
3665       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3666       // in the constant pool to ensure ordering between the barrier and oops
3667       // accesses. For native_wrappers we need a constant.
3668       buffer.initialize_consts_size(8);
3669 #elif defined(PPC64) || defined(S390)
3670       // On PPC64/S390 the continuation enter intrinsic needs the constant pool for the compiled
3671       // static java call that is resolved in the runtime.
3672       if (method->is_continuation_enter_intrinsic()) {
3673         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24) S390_ONLY(+ 17));
3674       }
3675 #endif
3676       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3677       MacroAssembler _masm(&buffer);
3678 
3679       // Fill in the signature array, for the calling-convention call.
3680       const int total_args_passed = method->size_of_parameters();
3681 
3682       BasicType stack_sig_bt[16];
3683       VMRegPair stack_regs[16];
3684       BasicType* sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
3685       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3686 
3687       int i = 0;
3688       if (!method->is_static()) {  // Pass in receiver first
3689         sig_bt[i++] = T_OBJECT;
3690       }
3691       SignatureStream ss(method->signature());
3692       for (; !ss.at_return_type(); ss.next()) {
3693         sig_bt[i++] = ss.type();  // Collect remaining bits of signature
3694         if (ss.type() == T_LONG || ss.type() == T_DOUBLE) {
3695           sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
3696         }
3697       }
3698       assert(i == total_args_passed, "");
3699       BasicType ret_type = ss.type();
3700 
3701       // Now get the compiled-Java arguments layout.
3702       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3703 
3704       // Generate the compiled-to-native wrapper code
3705       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3706 
3707       if (nm != nullptr) {
3708         {
3709           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3710           if (nm->make_in_use()) {
3711             method->set_code(method, nm);
3712           }
3713         }
3714 
3715         CompilerDirectiveMatcher matcher(method, CompLevel_simple);
3716         if (matcher.directive_set()->PrintAssemblyOption) {
3717           nm->print_code();
3718         }
3719       }

3926       if (b == handler->adapter_blob()) {
3927         found = true;
3928         st->print("Adapter for signature: ");
3929         handler->print_adapter_on(st);
3930         return false; // abort iteration
3931       } else {
3932         return true; // keep looking
3933       }
3934     };
3935     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3936     _adapter_handler_table->iterate(findblob_runtime_table);
3937   }
3938   assert(found, "Should have found handler");
3939 }
3940 
3941 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3942   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3943   if (adapter_blob() != nullptr) {
3944     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3945     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3946     st->print(" c2iVE: " INTPTR_FORMAT, p2i(get_c2i_inline_entry()));
3947     st->print(" c2iVROE: " INTPTR_FORMAT, p2i(get_c2i_inline_ro_entry()));
3948     st->print(" c2iUE: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3949     st->print(" c2iUVE: " INTPTR_FORMAT, p2i(get_c2i_unverified_inline_entry()));
3950     if (get_c2i_no_clinit_check_entry() != nullptr) {
3951       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3952     }
3953   }
3954   st->cr();
3955 }
3956 
3957 #ifndef PRODUCT
3958 
3959 void AdapterHandlerLibrary::print_statistics() {
3960   print_table_statistics();
3961 }
3962 
3963 #endif /* PRODUCT */
3964 
3965 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3966   assert(current == JavaThread::current(), "pre-condition");
3967   StackOverflow* overflow_state = current->stack_overflow_state();
3968   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3969   overflow_state->set_reserved_stack_activation(current->stack_base());

4016         event.set_method(method);
4017         event.commit();
4018       }
4019     }
4020   }
4021   return activation;
4022 }
4023 
4024 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
4025   // After any safepoint, just before going back to compiled code,
4026   // we inform the GC that we will be doing initializing writes to
4027   // this object in the future without emitting card-marks, so
4028   // GC may take any compensating steps.
4029 
4030   oop new_obj = current->vm_result_oop();
4031   if (new_obj == nullptr) return;
4032 
4033   BarrierSet *bs = BarrierSet::barrier_set();
4034   bs->on_slowpath_allocation_exit(current, new_obj);
4035 }
4036 
4037 // We are at a compiled code to interpreter call. We need backing
4038 // buffers for all inline type arguments. Allocate an object array to
4039 // hold them (convenient because once we're done with it we don't have
4040 // to worry about freeing it).
4041 oop SharedRuntime::allocate_inline_types_impl(JavaThread* current, methodHandle callee, bool allocate_receiver, bool from_c1, TRAPS) {
4042   assert(InlineTypePassFieldsAsArgs, "no reason to call this");
4043   ResourceMark rm;
4044 
4045   // Retrieve arguments passed at the call
4046   RegisterMap reg_map2(THREAD,
4047                        RegisterMap::UpdateMap::include,
4048                        RegisterMap::ProcessFrames::include,
4049                        RegisterMap::WalkContinuation::skip);
4050   frame stubFrame = THREAD->last_frame();
4051   frame callerFrame = stubFrame.sender(&reg_map2);
4052   if (from_c1) {
4053     callerFrame = callerFrame.sender(&reg_map2);
4054   }
4055   int arg_size;
4056   const GrowableArray<SigEntry>* sig = allocate_receiver ? callee->adapter()->get_sig_cc() : callee->adapter()->get_sig_cc_ro();
4057   assert(sig != nullptr, "sig should never be null");
4058   TempNewSymbol tmp_sig = SigEntry::create_symbol(sig);
4059   VMRegPair* reg_pairs = find_callee_arguments(tmp_sig, false, false, &arg_size);
4060 
4061   int nb_slots = 0;
4062   InstanceKlass* holder = callee->method_holder();
4063   allocate_receiver &= !callee->is_static() && holder->is_inline_klass() && callee->is_scalarized_arg(0);
4064   if (allocate_receiver) {
4065     nb_slots++;
4066   }
4067   int arg_num = callee->is_static() ? 0 : 1;
4068   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4069     BasicType bt = ss.type();
4070     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4071       nb_slots++;
4072     }
4073     if (bt != T_VOID) {
4074       arg_num++;
4075     }
4076   }
4077   objArrayOop array_oop = nullptr;
4078   objArrayHandle array;
4079   arg_num = callee->is_static() ? 0 : 1;
4080   int i = 0;
4081   uint pos = 0;
4082   uint depth = 0;
4083   uint ignored = 0;
4084   if (allocate_receiver) {
4085     assert(sig->at(pos)._bt == T_METADATA, "scalarized value expected");
4086     pos++;
4087     ignored++;
4088     depth++;
4089     assert(sig->at(pos)._bt == T_OBJECT, "buffer argument");
4090     uint reg_pos = 0;
4091     assert(reg_pos < (uint)arg_size, "");
4092     VMRegPair reg_pair = reg_pairs[reg_pos];
4093     oop* buffer = callerFrame.oopmapreg_to_oop_location(reg_pair.first(), &reg_map2);
4094     instanceHandle h_buffer(THREAD, (instanceOop)*buffer);
4095     InlineKlass* vk = InlineKlass::cast(holder);
4096     if (h_buffer.not_null()) {
4097       assert(h_buffer->klass() == vk, "buffer not of expected class");
4098     } else {
4099       // Only allocate if buffer passed at the call is null
4100       if (array_oop == nullptr) {
4101         array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4102         array = objArrayHandle(THREAD, array_oop);
4103       }
4104       oop res = vk->allocate_instance(CHECK_NULL);
4105       array->obj_at_put(i, res);
4106     }
4107     i++;
4108   }
4109   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4110     BasicType bt = ss.type();
4111     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4112       while (true) {
4113         BasicType bt = sig->at(pos)._bt;
4114         if (bt == T_METADATA) {
4115           depth++;
4116           ignored++;
4117           if (depth == 1) {
4118             break;
4119           }
4120         } else if (bt == T_VOID && sig->at(pos - 1)._bt != T_LONG && sig->at(pos - 1)._bt != T_DOUBLE) {
4121           ignored++;
4122           depth--;
4123         }
4124         pos++;
4125       }
4126       pos++;
4127       assert(sig->at(pos)._bt == T_OBJECT, "buffer argument expected");
4128       uint reg_pos = pos - ignored;
4129       assert(reg_pos < (uint)arg_size, "out of bound register?");
4130       VMRegPair reg_pair = reg_pairs[reg_pos];
4131       oop* buffer = callerFrame.oopmapreg_to_oop_location(reg_pair.first(), &reg_map2);
4132       instanceHandle h_buffer(THREAD, (instanceOop)*buffer);
4133       InlineKlass* vk = ss.as_inline_klass(holder);
4134       assert(vk != nullptr, "Unexpected klass");
4135       if (h_buffer.not_null()) {
4136         assert(h_buffer->klass() == vk, "buffer not of expected class");
4137       } else {
4138         // Only allocate if buffer passed at the call is null
4139         if (array_oop == nullptr) {
4140           array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4141           array = objArrayHandle(THREAD, array_oop);
4142         }
4143         oop res = vk->allocate_instance(CHECK_NULL);
4144         array->obj_at_put(i, res);
4145       }
4146       i++;
4147     }
4148     if (bt != T_VOID) {
4149       arg_num++;
4150     }
4151   }
4152   return array();
4153 }
4154 
4155 JRT_ENTRY(void, SharedRuntime::allocate_inline_types(JavaThread* current, Method* callee_method, bool allocate_receiver))
4156   methodHandle callee(current, callee_method);
4157   oop array = SharedRuntime::allocate_inline_types_impl(current, callee, allocate_receiver, false, CHECK);
4158   current->set_vm_result_oop(array);
4159 JRT_END
4160 
4161 // We've returned to an interpreted method, the interpreter needs a
4162 // reference to an inline type instance. Allocate it and initialize it
4163 // from field's values in registers.
4164 JRT_BLOCK_ENTRY(void, SharedRuntime::store_inline_type_fields_to_buf(JavaThread* current, intptr_t res))
4165 {
4166   if (!is_set_nth_bit(res, 0)) {
4167     // We're not returning with inline type fields in registers (the
4168     // calling convention didn't allow it for this inline klass)
4169     assert(!Metaspace::contains((void*)res), "should be oop or pointer in buffer area");
4170     current->set_vm_result_oop((oopDesc*)res);
4171     current->set_vm_result_metadata(nullptr);
4172     return;
4173   }
4174 
4175   clear_nth_bit(res, 0);
4176   InlineKlass* vk = (InlineKlass*)res;
4177   assert(Metaspace::contains((void*)res), "should be klass");
4178 
4179   if (!vk->contains_oops()) {
4180     // No oop fields. Initialize the fields by calling the pack handler from
4181     // the stub which is much faster (see 'generate_return_value_stub').
4182     // Signal this by setting the metadata result to the value klass.
4183     JRT_BLOCK;
4184     {
4185       oop vt = vk->allocate_instance(CHECK);
4186       current->set_vm_result_oop(vt);
4187       current->set_vm_result_metadata(vk);
4188     }
4189     JRT_BLOCK_END;
4190     return;
4191   }
4192 
4193   ResourceMark rm;
4194   RegisterMap reg_map(current,
4195                       RegisterMap::UpdateMap::include,
4196                       RegisterMap::ProcessFrames::include,
4197                       RegisterMap::WalkContinuation::skip);
4198   frame stubFrame = current->last_frame();
4199   stubFrame.sender(&reg_map);
4200 
4201   assert(vk == InlineKlass::returned_inline_klass(reg_map), "broken calling convention");
4202 
4203   // Allocate handles for every oop field so they are safe in case of
4204   // a safepoint when allocating
4205   GrowableArray<Handle> handles;
4206   vk->save_oop_fields(reg_map, handles);
4207 
4208   // It's unsafe to safepoint until we are here
4209   JRT_BLOCK;
4210   {
4211     oop vt = vk->realloc_result(reg_map, handles, CHECK);
4212     current->set_vm_result_oop(vt);
4213     current->set_vm_result_metadata(nullptr);
4214   }
4215   JRT_BLOCK_END;
4216 }
4217 JRT_END
< prev index next >