1 /*
   2  * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 #include "classfile/classLoaderData.inline.hpp"
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "classfile/stringTable.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/scopeDesc.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compilerEvent.hpp"
  34 #include "compiler/compilerOracle.hpp"
  35 #include "compiler/disassembler.hpp"
  36 #include "compiler/oopMap.hpp"
  37 #include "interpreter/bytecodeStream.hpp"
  38 #include "interpreter/linkResolver.hpp"
  39 #include "interpreter/oopMapCache.hpp"
  40 #include "jfr/jfrEvents.hpp"
  41 #include "jvmci/jvmciCodeInstaller.hpp"
  42 #include "jvmci/jvmciCompilerToVM.hpp"
  43 #include "jvmci/jvmciRuntime.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logTag.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/universe.hpp"
  48 #include "oops/constantPool.inline.hpp"
  49 #include "oops/instanceKlass.inline.hpp"
  50 #include "oops/instanceMirrorKlass.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/objArrayKlass.inline.hpp"
  53 #include "oops/trainingData.hpp"
  54 #include "oops/typeArrayOop.inline.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "prims/methodHandles.hpp"
  57 #include "prims/nativeLookup.hpp"
  58 #include "runtime/arguments.hpp"
  59 #include "runtime/atomic.hpp"
  60 #include "runtime/deoptimization.hpp"
  61 #include "runtime/fieldDescriptor.inline.hpp"
  62 #include "runtime/frame.inline.hpp"
  63 #include "runtime/globals_extension.hpp"
  64 #include "runtime/interfaceSupport.inline.hpp"
  65 #include "runtime/jniHandles.inline.hpp"
  66 #include "runtime/keepStackGCProcessed.hpp"
  67 #include "runtime/reflection.hpp"
  68 #include "runtime/stackFrameStream.inline.hpp"
  69 #include "runtime/timerTrace.hpp"
  70 #include "runtime/vframe.inline.hpp"
  71 #include "runtime/vframe_hp.hpp"
  72 #if INCLUDE_JFR
  73 #include "jfr/jfr.hpp"
  74 #endif
  75 
  76 JVMCIKlassHandle::JVMCIKlassHandle(Thread* thread, Klass* klass) {
  77   _thread = thread;
  78   _klass = klass;
  79   if (klass != nullptr) {
  80     _holder = Handle(_thread, klass->klass_holder());
  81   }
  82 }
  83 
  84 JVMCIKlassHandle& JVMCIKlassHandle::operator=(Klass* klass) {
  85   _klass = klass;
  86   if (klass != nullptr) {
  87     _holder = Handle(_thread, klass->klass_holder());
  88   }
  89   return *this;
  90 }
  91 
  92 static void requireInHotSpot(const char* caller, JVMCI_TRAPS) {
  93   if (!JVMCIENV->is_hotspot()) {
  94     JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from JVMCI shared library", caller));
  95   }
  96 }
  97 
  98 static void requireNotInHotSpot(const char* caller, JVMCI_TRAPS) {
  99     if (JVMCIENV->is_hotspot()) {
 100         JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from HotSpot", caller));
 101     }
 102 }
 103 
 104 class JVMCITraceMark : public StackObj {
 105   const char* _msg;
 106  public:
 107   JVMCITraceMark(const char* msg) {
 108     _msg = msg;
 109     JVMCI_event_2("Enter %s", _msg);
 110   }
 111   ~JVMCITraceMark() {
 112     JVMCI_event_2(" Exit %s", _msg);
 113   }
 114 };
 115 
 116 class JavaArgumentUnboxer : public SignatureIterator {
 117  protected:
 118   JavaCallArguments*  _jca;
 119   arrayOop _args;
 120   int _index;
 121 
 122   Handle next_arg(BasicType expectedType);
 123 
 124  public:
 125   JavaArgumentUnboxer(Symbol* signature,
 126                       JavaCallArguments* jca,
 127                       arrayOop args,
 128                       bool is_static)
 129     : SignatureIterator(signature)
 130   {
 131     this->_return_type = T_ILLEGAL;
 132     _jca = jca;
 133     _index = 0;
 134     _args = args;
 135     if (!is_static) {
 136       _jca->push_oop(next_arg(T_OBJECT));
 137     }
 138     do_parameters_on(this);
 139     assert(_index == args->length(), "arg count mismatch with signature");
 140   }
 141 
 142  private:
 143   friend class SignatureIterator;  // so do_parameters_on can call do_type
 144   void do_type(BasicType type) {
 145     if (is_reference_type(type)) {
 146       _jca->push_oop(next_arg(T_OBJECT));
 147       return;
 148     }
 149     Handle arg = next_arg(type);
 150     int box_offset = java_lang_boxing_object::value_offset(type);
 151     switch (type) {
 152     case T_BOOLEAN:     _jca->push_int(arg->bool_field(box_offset));    break;
 153     case T_CHAR:        _jca->push_int(arg->char_field(box_offset));    break;
 154     case T_SHORT:       _jca->push_int(arg->short_field(box_offset));   break;
 155     case T_BYTE:        _jca->push_int(arg->byte_field(box_offset));    break;
 156     case T_INT:         _jca->push_int(arg->int_field(box_offset));     break;
 157     case T_LONG:        _jca->push_long(arg->long_field(box_offset));   break;
 158     case T_FLOAT:       _jca->push_float(arg->float_field(box_offset));    break;
 159     case T_DOUBLE:      _jca->push_double(arg->double_field(box_offset));  break;
 160     default:            ShouldNotReachHere();
 161     }
 162   }
 163 };
 164 
 165 Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
 166   assert(_index < _args->length(), "out of bounds");
 167   oop arg=((objArrayOop) (_args))->obj_at(_index++);
 168   assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
 169   return Handle(Thread::current(), arg);
 170 }
 171 
 172 // Bring the JVMCI compiler thread into the VM state.
 173 #define JVMCI_VM_ENTRY_MARK                                       \
 174   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));       \
 175   ThreadInVMfromNative __tiv(thread);                             \
 176   HandleMarkCleaner __hm(thread);                                 \
 177   JavaThread* THREAD = thread;                                    \
 178   DEBUG_ONLY(VMNativeEntryWrapper __vew;)
 179 
 180 // Native method block that transitions current thread to '_thread_in_vm'.
 181 // Note: CompilerThreadCanCallJava must precede JVMCIENV_FROM_JNI so that
 182 // the translation of an uncaught exception in the JVMCIEnv does not make
 183 // a Java call when __is_hotspot == false.
 184 #define C2V_BLOCK(result_type, name, signature)            \
 185   JVMCI_VM_ENTRY_MARK;                                     \
 186   ResourceMark rm;                                         \
 187   bool __is_hotspot = env == thread->jni_environment();    \
 188   bool __block_can_call_java = __is_hotspot || !thread->is_Compiler_thread() || CompilerThread::cast(thread)->can_call_java(); \
 189   CompilerThreadCanCallJava ccj(thread, __block_can_call_java); \
 190   JVMCIENV_FROM_JNI(JVMCI::compilation_tick(thread), env); \
 191 
 192 // Entry to native method implementation that transitions
 193 // current thread to '_thread_in_vm'.
 194 #define C2V_VMENTRY(result_type, name, signature)        \
 195   result_type JNICALL c2v_ ## name signature {           \
 196   JavaThread* thread = JavaThread::current_or_null();    \
 197   if (thread == nullptr) {                               \
 198     env->ThrowNew(JNIJVMCI::InternalError::clazz(),      \
 199         err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
 200     return;                                              \
 201   }                                                      \
 202   C2V_BLOCK(result_type, name, signature)                \
 203   JVMCITraceMark jtm("CompilerToVM::" #name);
 204 
 205 #define C2V_VMENTRY_(result_type, name, signature, result) \
 206   result_type JNICALL c2v_ ## name signature {           \
 207   JavaThread* thread = JavaThread::current_or_null();    \
 208   if (thread == nullptr) {                               \
 209     env->ThrowNew(JNIJVMCI::InternalError::clazz(),      \
 210         err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
 211     return result;                                       \
 212   }                                                      \
 213   C2V_BLOCK(result_type, name, signature)                \
 214   JVMCITraceMark jtm("CompilerToVM::" #name);
 215 
 216 #define C2V_VMENTRY_NULL(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, nullptr)
 217 #define C2V_VMENTRY_0(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, 0)
 218 
 219 // Entry to native method implementation that does not transition
 220 // current thread to '_thread_in_vm'.
 221 #define C2V_VMENTRY_PREFIX(result_type, name, signature) \
 222   result_type JNICALL c2v_ ## name signature {           \
 223   JavaThread* thread = JavaThread::current_or_null();
 224 
 225 #define C2V_END }
 226 
 227 #define JNI_THROW(caller, name, msg) do {                                         \
 228     jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg);               \
 229     if (__throw_res != JNI_OK) {                                                  \
 230       JVMCI_event_1("Throwing " #name " in " caller " returned %d", __throw_res); \
 231     }                                                                             \
 232     return;                                                                       \
 233   } while (0);
 234 
 235 #define JNI_THROW_(caller, name, msg, result) do {                                \
 236     jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg);               \
 237     if (__throw_res != JNI_OK) {                                                  \
 238       JVMCI_event_1("Throwing " #name " in " caller " returned %d", __throw_res); \
 239     }                                                                             \
 240     return result;                                                                \
 241   } while (0)
 242 
 243 jobjectArray readConfiguration0(JNIEnv *env, JVMCI_TRAPS);
 244 
 245 C2V_VMENTRY_NULL(jobjectArray, readConfiguration, (JNIEnv* env))
 246   jobjectArray config = readConfiguration0(env, JVMCI_CHECK_NULL);
 247   return config;
 248 }
 249 
 250 C2V_VMENTRY_NULL(jobject, getFlagValue, (JNIEnv* env, jobject c2vm, jobject name_handle))
 251 #define RETURN_BOXED_LONG(value) jvalue p; p.j = (jlong) (value); JVMCIObject box = JVMCIENV->create_box(T_LONG, &p, JVMCI_CHECK_NULL); return box.as_jobject();
 252 #define RETURN_BOXED_DOUBLE(value) jvalue p; p.d = (jdouble) (value); JVMCIObject box = JVMCIENV->create_box(T_DOUBLE, &p, JVMCI_CHECK_NULL); return box.as_jobject();
 253   JVMCIObject name = JVMCIENV->wrap(name_handle);
 254   if (name.is_null()) {
 255     JVMCI_THROW_NULL(NullPointerException);
 256   }
 257   const char* cstring = JVMCIENV->as_utf8_string(name);
 258   const JVMFlag* flag = JVMFlag::find_declared_flag(cstring);
 259   if (flag == nullptr) {
 260     return c2vm;
 261   }
 262   if (flag->is_bool()) {
 263     jvalue prim;
 264     prim.z = flag->get_bool();
 265     JVMCIObject box = JVMCIENV->create_box(T_BOOLEAN, &prim, JVMCI_CHECK_NULL);
 266     return JVMCIENV->get_jobject(box);
 267   } else if (flag->is_ccstr()) {
 268     JVMCIObject value = JVMCIENV->create_string(flag->get_ccstr(), JVMCI_CHECK_NULL);
 269     return JVMCIENV->get_jobject(value);
 270   } else if (flag->is_intx()) {
 271     RETURN_BOXED_LONG(flag->get_intx());
 272   } else if (flag->is_int()) {
 273     RETURN_BOXED_LONG(flag->get_int());
 274   } else if (flag->is_uint()) {
 275     RETURN_BOXED_LONG(flag->get_uint());
 276   } else if (flag->is_uint64_t()) {
 277     RETURN_BOXED_LONG(flag->get_uint64_t());
 278   } else if (flag->is_size_t()) {
 279     RETURN_BOXED_LONG(flag->get_size_t());
 280   } else if (flag->is_uintx()) {
 281     RETURN_BOXED_LONG(flag->get_uintx());
 282   } else if (flag->is_double()) {
 283     RETURN_BOXED_DOUBLE(flag->get_double());
 284   } else {
 285     JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->name(), flag->type_string());
 286   }
 287 #undef RETURN_BOXED_LONG
 288 #undef RETURN_BOXED_DOUBLE
 289 C2V_END
 290 
 291 // Macros for argument pairs representing a wrapper object and its wrapped VM pointer
 292 #define ARGUMENT_PAIR(name) jobject name ## _obj, jlong name ## _pointer
 293 #define UNPACK_PAIR(type, name) ((type*) name ## _pointer)
 294 
 295 C2V_VMENTRY_NULL(jbyteArray, getBytecode, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 296   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
 297 
 298   int code_size = method->code_size();
 299   jbyte* reconstituted_code = NEW_RESOURCE_ARRAY(jbyte, code_size);
 300 
 301   guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
 302   // iterate over all bytecodes and replace non-Java bytecodes
 303 
 304   for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
 305     Bytecodes::Code code = s.code();
 306     Bytecodes::Code raw_code = s.raw_code();
 307     int bci = s.bci();
 308     int len = s.instruction_size();
 309 
 310     // Restore original byte code.
 311     reconstituted_code[bci] =  (jbyte) (s.is_wide()? Bytecodes::_wide : code);
 312     if (len > 1) {
 313       memcpy(reconstituted_code + (bci + 1), s.bcp()+1, len-1);
 314     }
 315 
 316     if (len > 1) {
 317       // Restore the big-endian constant pool indexes.
 318       // Cf. Rewriter::scan_method
 319       switch (code) {
 320         case Bytecodes::_getstatic:
 321         case Bytecodes::_putstatic:
 322         case Bytecodes::_getfield:
 323         case Bytecodes::_putfield:
 324         case Bytecodes::_invokevirtual:
 325         case Bytecodes::_invokespecial:
 326         case Bytecodes::_invokestatic:
 327         case Bytecodes::_invokeinterface:
 328         case Bytecodes::_invokehandle: {
 329           int cp_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
 330           Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
 331           break;
 332         }
 333 
 334         case Bytecodes::_invokedynamic: {
 335           int cp_index = Bytes::get_native_u4((address) reconstituted_code + (bci + 1));
 336           Bytes::put_Java_u4((address) reconstituted_code + (bci + 1), (u4) cp_index);
 337           break;
 338         }
 339 
 340         default:
 341           break;
 342       }
 343 
 344       // Not all ldc byte code are rewritten.
 345       switch (raw_code) {
 346         case Bytecodes::_fast_aldc: {
 347           int cpc_index = reconstituted_code[bci + 1] & 0xff;
 348           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 349           assert(cp_index < method->constants()->length(), "sanity check");
 350           reconstituted_code[bci + 1] = (jbyte) cp_index;
 351           break;
 352         }
 353 
 354         case Bytecodes::_fast_aldc_w: {
 355           int cpc_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
 356           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 357           assert(cp_index < method->constants()->length(), "sanity check");
 358           Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
 359           break;
 360         }
 361 
 362         default:
 363           break;
 364       }
 365     }
 366   }
 367 
 368   JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
 369   JVMCIENV->copy_bytes_from(reconstituted_code, result, 0, code_size);
 370   return JVMCIENV->get_jbyteArray(result);
 371 C2V_END
 372 
 373 C2V_VMENTRY_0(jint, getExceptionTableLength, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 374   Method* method = UNPACK_PAIR(Method, method);
 375   return method->exception_table_length();
 376 C2V_END
 377 
 378 C2V_VMENTRY_0(jlong, getExceptionTableStart, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 379   Method* method = UNPACK_PAIR(Method, method);
 380   if (method->exception_table_length() == 0) {
 381     return 0L;
 382   }
 383   return (jlong) (address) method->exception_table_start();
 384 C2V_END
 385 
 386 C2V_VMENTRY_NULL(jobject, asResolvedJavaMethod, (JNIEnv* env, jobject, jobject executable_handle))
 387   requireInHotSpot("asResolvedJavaMethod", JVMCI_CHECK_NULL);
 388   oop executable = JNIHandles::resolve(executable_handle);
 389   oop mirror = nullptr;
 390   int slot = 0;
 391 
 392   if (executable->klass() == vmClasses::reflect_Constructor_klass()) {
 393     mirror = java_lang_reflect_Constructor::clazz(executable);
 394     slot = java_lang_reflect_Constructor::slot(executable);
 395   } else {
 396     assert(executable->klass() == vmClasses::reflect_Method_klass(), "wrong type");
 397     mirror = java_lang_reflect_Method::clazz(executable);
 398     slot = java_lang_reflect_Method::slot(executable);
 399   }
 400   Klass* holder = java_lang_Class::as_Klass(mirror);
 401   methodHandle method (THREAD, InstanceKlass::cast(holder)->method_with_idnum(slot));
 402   JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
 403   return JVMCIENV->get_jobject(result);
 404 }
 405 
 406 C2V_VMENTRY_PREFIX(jboolean, updateCompilerThreadCanCallJava, (JNIEnv* env, jobject, jboolean newState))
 407   return CompilerThreadCanCallJava::update(thread, newState) != nullptr;
 408 C2V_END
 409 
 410 
 411 C2V_VMENTRY_NULL(jobject, getResolvedJavaMethod, (JNIEnv* env, jobject, jobject base, jlong offset))
 412   Method* method = nullptr;
 413   JVMCIObject base_object = JVMCIENV->wrap(base);
 414   if (base_object.is_null()) {
 415     method = *((Method**)(offset));
 416   } else {
 417     Handle obj = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 418     if (obj->is_a(vmClasses::ResolvedMethodName_klass())) {
 419       method = (Method*) (intptr_t) obj->long_field(offset);
 420     } else {
 421       JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", obj->klass()->external_name()));
 422     }
 423   }
 424   if (method == nullptr) {
 425     JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", JVMCIENV->klass_name(base_object)));
 426   }
 427   assert (method->is_method(), "invalid read");
 428   JVMCIObject result = JVMCIENV->get_jvmci_method(methodHandle(THREAD, method), JVMCI_CHECK_NULL);
 429   return JVMCIENV->get_jobject(result);
 430 }
 431 
 432 C2V_VMENTRY_NULL(jobject, getConstantPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass_or_method), jboolean is_klass))
 433   ConstantPool* cp = nullptr;
 434   if (UNPACK_PAIR(address, klass_or_method) == nullptr) {
 435     JVMCI_THROW_NULL(NullPointerException);
 436   }
 437   if (!is_klass) {
 438     cp = (UNPACK_PAIR(Method, klass_or_method))->constMethod()->constants();
 439   } else {
 440     cp = InstanceKlass::cast(UNPACK_PAIR(Klass, klass_or_method))->constants();
 441   }
 442 
 443   JVMCIObject result = JVMCIENV->get_jvmci_constant_pool(constantPoolHandle(THREAD, cp), JVMCI_CHECK_NULL);
 444   return JVMCIENV->get_jobject(result);
 445 }
 446 
 447 C2V_VMENTRY_NULL(jobject, getResolvedJavaType0, (JNIEnv* env, jobject, jobject base, jlong offset, jboolean compressed))
 448   JVMCIObject base_object = JVMCIENV->wrap(base);
 449   if (base_object.is_null()) {
 450     JVMCI_THROW_MSG_NULL(NullPointerException, "base object is null");
 451   }
 452 
 453   const char* base_desc = nullptr;
 454   JVMCIKlassHandle klass(THREAD);
 455   if (offset == oopDesc::klass_offset_in_bytes()) {
 456     if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
 457       Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 458       klass = base_oop->klass();
 459     } else {
 460       goto unexpected;
 461     }
 462   } else if (!compressed) {
 463     if (JVMCIENV->isa_HotSpotConstantPool(base_object)) {
 464       ConstantPool* cp = JVMCIENV->asConstantPool(base_object);
 465       if (offset == in_bytes(ConstantPool::pool_holder_offset())) {
 466         klass = cp->pool_holder();
 467       } else {
 468         base_desc = FormatBufferResource("[constant pool for %s]", cp->pool_holder()->signature_name());
 469         goto unexpected;
 470       }
 471     } else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base_object)) {
 472       Klass* base_klass = JVMCIENV->asKlass(base_object);
 473       if (offset == in_bytes(Klass::subklass_offset())) {
 474         klass = base_klass->subklass();
 475       } else if (offset == in_bytes(Klass::super_offset())) {
 476         klass = base_klass->super();
 477       } else if (offset == in_bytes(Klass::next_sibling_offset())) {
 478         klass = base_klass->next_sibling();
 479       } else if (offset == in_bytes(ObjArrayKlass::element_klass_offset()) && base_klass->is_objArray_klass()) {
 480         klass = ObjArrayKlass::cast(base_klass)->element_klass();
 481       } else if (offset >= in_bytes(Klass::primary_supers_offset()) &&
 482                  offset < in_bytes(Klass::primary_supers_offset()) + (int) (sizeof(Klass*) * Klass::primary_super_limit()) &&
 483                  offset % sizeof(Klass*) == 0) {
 484         // Offset is within the primary supers array
 485         int index = (int) ((offset - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*));
 486         klass = base_klass->primary_super_of_depth(index);
 487       } else {
 488         base_desc = FormatBufferResource("[%s]", base_klass->signature_name());
 489         goto unexpected;
 490       }
 491     } else if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
 492       Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 493       if (base_oop->is_a(vmClasses::Class_klass())) {
 494         if (offset == java_lang_Class::klass_offset()) {
 495           klass = java_lang_Class::as_Klass(base_oop());
 496         } else if (offset == java_lang_Class::array_klass_offset()) {
 497           klass = java_lang_Class::array_klass_acquire(base_oop());
 498         } else {
 499           base_desc = FormatBufferResource("[Class=%s]", java_lang_Class::as_Klass(base_oop())->signature_name());
 500           goto unexpected;
 501         }
 502       } else {
 503         if (!base_oop.is_null()) {
 504           base_desc = FormatBufferResource("[%s]", base_oop()->klass()->signature_name());
 505         }
 506         goto unexpected;
 507       }
 508     } else if (JVMCIENV->isa_HotSpotMethodData(base_object)) {
 509       jlong base_address = (intptr_t) JVMCIENV->asMethodData(base_object);
 510       Klass* k = *((Klass**) (intptr_t) (base_address + offset));
 511       if (k == nullptr || k->class_loader_data() == nullptr || !TrainingData::is_klass_loaded(k)) {
 512         return nullptr;
 513       }
 514       if (!k->is_loader_alive()) {
 515         // Klasses in methodData might be concurrently unloading so return null in that case.
 516         return nullptr;
 517       }
 518       klass = k;
 519     } else {
 520       goto unexpected;
 521     }
 522   } else {
 523     goto unexpected;
 524   }
 525 
 526   {
 527     if (klass == nullptr) {
 528       return nullptr;
 529     }
 530     JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
 531     return JVMCIENV->get_jobject(result);
 532   }
 533 
 534 unexpected:
 535   JVMCI_THROW_MSG_NULL(IllegalArgumentException,
 536                        err_msg("Unexpected arguments: %s%s " JLONG_FORMAT " %s",
 537                                JVMCIENV->klass_name(base_object), base_desc == nullptr ? "" : base_desc,
 538                                offset, compressed ? "true" : "false"));
 539 }
 540 
 541 C2V_VMENTRY_NULL(jobject, findUniqueConcreteMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(method)))
 542   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 543   InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
 544   if (holder->is_interface()) {
 545     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Interface %s should be handled in Java code", holder->external_name()));
 546   }
 547   if (method->can_be_statically_bound()) {
 548     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Effectively static method %s.%s should be handled in Java code", method->method_holder()->external_name(), method->external_name()));
 549   }
 550 
 551   methodHandle ucm;
 552   {
 553     MutexLocker locker(Compile_lock);
 554     ucm = methodHandle(THREAD, Dependencies::find_unique_concrete_method(holder, method()));
 555   }
 556   JVMCIObject result = JVMCIENV->get_jvmci_method(ucm, JVMCI_CHECK_NULL);
 557   return JVMCIENV->get_jobject(result);
 558 C2V_END
 559 
 560 C2V_VMENTRY_NULL(jobject, getImplementor, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
 561   Klass* klass = UNPACK_PAIR(Klass, klass);
 562   if (!klass->is_interface()) {
 563     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 564                    err_msg("Expected interface type, got %s", klass->external_name()));
 565   }
 566   InstanceKlass* iklass = InstanceKlass::cast(klass);
 567   JVMCIKlassHandle handle(THREAD, iklass->implementor());
 568   JVMCIObject implementor = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
 569   return JVMCIENV->get_jobject(implementor);
 570 C2V_END
 571 
 572 C2V_VMENTRY_0(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 573   Method* method = UNPACK_PAIR(Method, method);
 574   return method->is_ignored_by_security_stack_walk();
 575 C2V_END
 576 
 577 C2V_VMENTRY_0(jboolean, isCompilable,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 578   Method* method = UNPACK_PAIR(Method, method);
 579   // Skip redefined methods
 580   if (method->is_old()) {
 581     return false;
 582   }
 583   return !method->is_not_compilable(CompLevel_full_optimization);
 584 C2V_END
 585 
 586 C2V_VMENTRY_0(jboolean, hasNeverInlineDirective,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 587   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 588   return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
 589 C2V_END
 590 
 591 C2V_VMENTRY_0(jboolean, shouldInlineMethod,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 592   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 593   return CompilerOracle::should_inline(method) || method->force_inline();
 594 C2V_END
 595 
 596 C2V_VMENTRY_NULL(jobject, lookupType, (JNIEnv* env, jobject, jstring jname, ARGUMENT_PAIR(accessing_klass), jint accessing_klass_loader, jboolean resolve))
 597   CompilerThreadCanCallJava canCallJava(thread, resolve); // Resolution requires Java calls
 598   JVMCIObject name = JVMCIENV->wrap(jname);
 599   const char* str = JVMCIENV->as_utf8_string(name);
 600   TempNewSymbol class_name = SymbolTable::new_symbol(str);
 601 
 602   if (class_name->utf8_length() <= 1) {
 603     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Primitive type %s should be handled in Java code", str));
 604   }
 605 
 606 #ifdef ASSERT
 607   const char* val = Arguments::PropertyList_get_value(Arguments::system_properties(), "test.jvmci.lookupTypeException");
 608   if (val != nullptr) {
 609     if (strstr(val, "<trace>") != nullptr) {
 610       tty->print_cr("CompilerToVM.lookupType: %s", str);
 611     } else if (strstr(str, val) != nullptr) {
 612       THROW_MSG_NULL(vmSymbols::java_lang_Exception(),
 613                      err_msg("lookupTypeException: %s", str));
 614     }
 615   }
 616 #endif
 617 
 618   JVMCIKlassHandle resolved_klass(THREAD);
 619   Klass* accessing_klass = UNPACK_PAIR(Klass, accessing_klass);
 620   Handle class_loader;
 621   if (accessing_klass != nullptr) {
 622     class_loader = Handle(THREAD, accessing_klass->class_loader());
 623   } else {
 624     switch (accessing_klass_loader) {
 625       case 0: break; // class_loader is already null, the boot loader
 626       case 1: class_loader = Handle(THREAD, SystemDictionary::java_platform_loader()); break;
 627       case 2: class_loader = Handle(THREAD, SystemDictionary::java_system_loader()); break;
 628       default:
 629         JVMCI_THROW_MSG_NULL(InternalError, err_msg("Illegal class loader value: %d", accessing_klass_loader));
 630     }
 631     JVMCIENV->runtime()->initialize(JVMCI_CHECK_NULL);
 632   }
 633 
 634   if (resolve) {
 635     resolved_klass = SystemDictionary::resolve_or_fail(class_name, class_loader, true, CHECK_NULL);
 636   } else {
 637     if (Signature::has_envelope(class_name)) {
 638       // This is a name from a signature.  Strip off the trimmings.
 639       // Call recursive to keep scope of strippedsym.
 640       TempNewSymbol strippedsym = Signature::strip_envelope(class_name);
 641       resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
 642                                                              class_loader);
 643     } else if (Signature::is_array(class_name)) {
 644       SignatureStream ss(class_name, false);
 645       int ndim = ss.skip_array_prefix();
 646       if (ss.type() == T_OBJECT) {
 647         Symbol* strippedsym = ss.as_symbol();
 648         resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
 649                                                                class_loader);
 650         if (!resolved_klass.is_null()) {
 651           resolved_klass = resolved_klass->array_klass(ndim, CHECK_NULL);
 652         }
 653       } else {
 654         resolved_klass = Universe::typeArrayKlass(ss.type())->array_klass(ndim, CHECK_NULL);
 655       }
 656     } else {
 657       resolved_klass = SystemDictionary::find_instance_klass(THREAD, class_name,
 658                                                              class_loader);
 659     }
 660   }
 661   JVMCIObject result = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
 662   return JVMCIENV->get_jobject(result);
 663 C2V_END
 664 
 665 C2V_VMENTRY_NULL(jobject, getArrayType, (JNIEnv* env, jobject, jchar type_char, ARGUMENT_PAIR(klass)))
 666   JVMCIKlassHandle array_klass(THREAD);
 667   Klass* klass = UNPACK_PAIR(Klass, klass);
 668   if (klass == nullptr) {
 669     BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_NULL);
 670     if (type == T_VOID) {
 671       return nullptr;
 672     }
 673     array_klass = Universe::typeArrayKlass(type);
 674     if (array_klass == nullptr) {
 675       JVMCI_THROW_MSG_NULL(InternalError, err_msg("No array klass for primitive type %s", type2name(type)));
 676     }
 677   } else {
 678     array_klass = klass->array_klass(CHECK_NULL);
 679   }
 680   JVMCIObject result = JVMCIENV->get_jvmci_type(array_klass, JVMCI_CHECK_NULL);
 681   return JVMCIENV->get_jobject(result);
 682 C2V_END
 683 
 684 C2V_VMENTRY_NULL(jobject, lookupClass, (JNIEnv* env, jobject, jclass mirror))
 685   requireInHotSpot("lookupClass", JVMCI_CHECK_NULL);
 686   if (mirror == nullptr) {
 687     return nullptr;
 688   }
 689   JVMCIKlassHandle klass(THREAD);
 690   klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
 691   if (klass == nullptr) {
 692     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Primitive classes are unsupported");
 693   }
 694   JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
 695   return JVMCIENV->get_jobject(result);
 696 C2V_END
 697 
 698 C2V_VMENTRY_NULL(jobject, lookupJClass, (JNIEnv* env, jobject, jlong jclass_value))
 699     if (jclass_value == 0L) {
 700         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass must not be zero");
 701     }
 702     jclass mirror = reinterpret_cast<jclass>(jclass_value);
 703     // Since the jclass_value is passed as a jlong, we perform additional checks to prevent the caller from accidentally
 704     // sending a value that is not a JNI handle.
 705     if (JNIHandles::handle_type(thread, mirror) == JNIInvalidRefType) {
 706         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass is not a valid JNI reference");
 707     }
 708     oop obj = JNIHandles::resolve(mirror);
 709     if (!java_lang_Class::is_instance(obj)) {
 710         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass must be a reference to the Class object");
 711     }
 712     JVMCIKlassHandle klass(THREAD, java_lang_Class::as_Klass(obj));
 713     JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
 714     return JVMCIENV->get_jobject(result);
 715 C2V_END
 716 
 717 C2V_VMENTRY_0(jlong, getJObjectValue, (JNIEnv* env, jobject, jobject constant_jobject))
 718     requireNotInHotSpot("getJObjectValue", JVMCI_CHECK_0);
 719     // Ensure that current JNI handle scope is not the top-most JNIHandleBlock as handles
 720     // in that scope are only released when the thread exits.
 721     if (!THREAD->has_last_Java_frame() && THREAD->active_handles()->pop_frame_link() == nullptr) {
 722         JVMCI_THROW_MSG_0(IllegalStateException, err_msg("Cannot call getJObjectValue without Java frame anchor or a pushed JNI handle block"));
 723     }
 724     JVMCIObject constant = JVMCIENV->wrap(constant_jobject);
 725     Handle constant_value = JVMCIENV->asConstant(constant, JVMCI_CHECK_0);
 726     jobject jni_handle = JNIHandles::make_local(THREAD, constant_value());
 727     return reinterpret_cast<jlong>(jni_handle);
 728 C2V_END
 729 
 730 C2V_VMENTRY_NULL(jobject, getUncachedStringInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
 731   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 732   constantTag tag = cp->tag_at(index);
 733   if (!tag.is_string()) {
 734     JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected constant pool tag at index %d: %d", index, tag.value()));
 735   }
 736   oop obj = cp->uncached_string_at(index, CHECK_NULL);
 737   return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(obj));
 738 C2V_END
 739 
 740 C2V_VMENTRY_NULL(jobject, lookupConstantInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint cp_index, bool resolve))
 741   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 742   oop obj;
 743   if (!resolve) {
 744     bool found_it;
 745     obj = cp->find_cached_constant_at(cp_index, found_it, CHECK_NULL);
 746     if (!found_it) {
 747       return nullptr;
 748     }
 749   } else {
 750     obj = cp->resolve_possibly_cached_constant_at(cp_index, CHECK_NULL);
 751   }
 752   constantTag tag = cp->tag_at(cp_index);
 753   if (tag.is_dynamic_constant()) {
 754     if (obj == nullptr) {
 755       return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
 756     }
 757     BasicType bt = Signature::basic_type(cp->uncached_signature_ref_at(cp_index));
 758     if (!is_reference_type(bt)) {
 759       if (!is_java_primitive(bt)) {
 760         return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_ILLEGAL());
 761       }
 762 
 763       // Convert standard box (e.g. java.lang.Integer) to JVMCI box (e.g. jdk.vm.ci.meta.PrimitiveConstant)
 764       jvalue value;
 765       jlong raw_value;
 766       jchar type_char;
 767       BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);
 768       assert(bt2 == bt, "");
 769       switch (bt2) {
 770         case T_LONG:    type_char = 'J'; raw_value = value.j; break;
 771         case T_DOUBLE:  type_char = 'D'; raw_value = value.j; break;
 772         case T_FLOAT:   type_char = 'F'; raw_value = value.i; break;
 773         case T_INT:     type_char = 'I'; raw_value = value.i; break;
 774         case T_SHORT:   type_char = 'S'; raw_value = value.s; break;
 775         case T_BYTE:    type_char = 'B'; raw_value = value.b; break;
 776         case T_CHAR:    type_char = 'C'; raw_value = value.c; break;
 777         case T_BOOLEAN: type_char = 'Z'; raw_value = value.z; break;
 778         default:        return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_ILLEGAL());
 779       }
 780 
 781       JVMCIObject result = JVMCIENV->call_JavaConstant_forPrimitive(type_char, raw_value, JVMCI_CHECK_NULL);
 782       return JVMCIENV->get_jobject(result);
 783     }
 784   }
 785 #ifdef ASSERT
 786   // Support for testing an OOME raised in a context where the current thread cannot call Java
 787   // 1. Put -Dtest.jvmci.oome_in_lookupConstantInPool=<trace> on the command line to
 788   //    discover possible values for step 2.
 789   //    Example output:
 790   //
 791   //      CompilerToVM.lookupConstantInPool: "Overflow: String length out of range"{0x00000007ffeb2960}
 792   //      CompilerToVM.lookupConstantInPool: "null"{0x00000007ffebdfe8}
 793   //      CompilerToVM.lookupConstantInPool: "Maximum lock count exceeded"{0x00000007ffec4f90}
 794   //      CompilerToVM.lookupConstantInPool: "Negative length"{0x00000007ffec4468}
 795   //
 796   // 2. Choose a value shown in step 1.
 797   //    Example: -Dtest.jvmci.oome_in_lookupConstantInPool=Negative
 798   const char* val = Arguments::PropertyList_get_value(Arguments::system_properties(), "test.jvmci.oome_in_lookupConstantInPool");
 799   if (val != nullptr) {
 800     const char* str = obj->print_value_string();
 801     if (strstr(val, "<trace>") != nullptr) {
 802       tty->print_cr("CompilerToVM.lookupConstantInPool: %s", str);
 803     } else if (strstr(str, val) != nullptr) {
 804       Handle garbage;
 805       while (true) {
 806         // Trigger an OutOfMemoryError
 807         objArrayOop next = oopFactory::new_objectArray(0x7FFFFFFF, CHECK_NULL);
 808         next->obj_at_put(0, garbage());
 809         garbage = Handle(THREAD, next);
 810       }
 811     }
 812   }
 813 #endif
 814   return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(obj));
 815 C2V_END
 816 
 817 C2V_VMENTRY_0(jint, getNumIndyEntries, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp)))
 818   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 819   if (cp->cache()->resolved_indy_entries() == nullptr) {
 820     return 0;
 821   }
 822   return cp->resolved_indy_entries_length();
 823 C2V_END
 824 
 825 C2V_VMENTRY_NULL(jobjectArray, resolveBootstrapMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
 826   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 827   constantTag tag = cp->tag_at(index);
 828   bool is_indy = tag.is_invoke_dynamic();
 829   bool is_condy = tag.is_dynamic_constant();
 830   if (!(is_condy || is_indy)) {
 831     JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected constant pool tag at index %d: %d", index, tag.value()));
 832   }
 833   // Get the indy entry based on CP index
 834   int indy_index = -1;
 835   if (is_indy) {
 836     for (int i = 0; i < cp->resolved_indy_entries_length(); i++) {
 837       if (cp->resolved_indy_entry_at(i)->constant_pool_index() == index) {
 838         indy_index = i;
 839       }
 840     }
 841   }
 842   // Resolve the bootstrap specifier, its name, type, and static arguments
 843   BootstrapInfo bootstrap_specifier(cp, index, indy_index);
 844   Handle bsm = bootstrap_specifier.resolve_bsm(CHECK_NULL);
 845 
 846   // call java.lang.invoke.MethodHandle::asFixedArity() -> MethodHandle
 847   // to get a DirectMethodHandle from which we can then extract a Method*
 848   JavaValue result(T_OBJECT);
 849   JavaCalls::call_virtual(&result,
 850                          bsm,
 851                          vmClasses::MethodHandle_klass(),
 852                          vmSymbols::asFixedArity_name(),
 853                          vmSymbols::asFixedArity_signature(),
 854                          CHECK_NULL);
 855   bsm = Handle(THREAD, result.get_oop());
 856 
 857   // Check assumption about getting a DirectMethodHandle
 858   if (!java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
 859     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Unexpected MethodHandle subclass: %s", bsm->klass()->external_name()));
 860   }
 861   // Create return array describing the bootstrap method invocation (BSMI)
 862   JVMCIObjectArray bsmi = JVMCIENV->new_Object_array(4, JVMCI_CHECK_NULL);
 863 
 864   // Extract Method* and wrap it in a ResolvedJavaMethod
 865   Handle member = Handle(THREAD, java_lang_invoke_DirectMethodHandle::member(bsm()));
 866   JVMCIObject bsmi_method = JVMCIENV->get_jvmci_method(methodHandle(THREAD, java_lang_invoke_MemberName::vmtarget(member())), JVMCI_CHECK_NULL);
 867   JVMCIENV->put_object_at(bsmi, 0, bsmi_method);
 868 
 869   JVMCIObject bsmi_name = JVMCIENV->create_string(bootstrap_specifier.name(), JVMCI_CHECK_NULL);
 870   JVMCIENV->put_object_at(bsmi, 1, bsmi_name);
 871 
 872   Handle type_arg = bootstrap_specifier.type_arg();
 873   JVMCIObject bsmi_type = JVMCIENV->get_object_constant(type_arg());
 874   JVMCIENV->put_object_at(bsmi, 2, bsmi_type);
 875 
 876   Handle arg_values = bootstrap_specifier.arg_values();
 877   if (arg_values.not_null()) {
 878     if (!arg_values->is_array()) {
 879       JVMCIENV->put_object_at(bsmi, 3, JVMCIENV->get_object_constant(arg_values()));
 880     } else if (arg_values->is_objArray()) {
 881       objArrayHandle args_array = objArrayHandle(THREAD, (objArrayOop) arg_values());
 882       int len = args_array->length();
 883       JVMCIObjectArray arguments = JVMCIENV->new_JavaConstant_array(len, JVMCI_CHECK_NULL);
 884       JVMCIENV->put_object_at(bsmi, 3, arguments);
 885       for (int i = 0; i < len; i++) {
 886         oop x = args_array->obj_at(i);
 887         if (x != nullptr) {
 888           JVMCIENV->put_object_at(arguments, i, JVMCIENV->get_object_constant(x));
 889         } else {
 890           JVMCIENV->put_object_at(arguments, i, JVMCIENV->get_JavaConstant_NULL_POINTER());
 891         }
 892       }
 893     } else if (arg_values->is_typeArray()) {
 894       typeArrayHandle bsci = typeArrayHandle(THREAD, (typeArrayOop) arg_values());
 895       JVMCIPrimitiveArray arguments = JVMCIENV->new_intArray(bsci->length(), JVMCI_CHECK_NULL);
 896       JVMCIENV->put_object_at(bsmi, 3, arguments);
 897       for (int i = 0; i < bsci->length(); i++) {
 898         JVMCIENV->put_int_at(arguments, i, bsci->int_at(i));
 899       }
 900     }
 901   }
 902   return JVMCIENV->get_jobjectArray(bsmi);
 903 C2V_END
 904 
 905 C2V_VMENTRY_0(jint, bootstrapArgumentIndexAt, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint cpi, jint index))
 906   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 907   return cp->bootstrap_argument_index_at(cpi, index);
 908 C2V_END
 909 
 910 C2V_VMENTRY_0(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
 911   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 912   return cp->name_and_type_ref_index_at(index, (Bytecodes::Code)opcode);
 913 C2V_END
 914 
 915 C2V_VMENTRY_NULL(jobject, lookupNameInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
 916   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 917   JVMCIObject sym = JVMCIENV->create_string(cp->name_ref_at(which, (Bytecodes::Code)opcode), JVMCI_CHECK_NULL);
 918   return JVMCIENV->get_jobject(sym);
 919 C2V_END
 920 
 921 C2V_VMENTRY_NULL(jobject, lookupSignatureInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
 922   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 923   JVMCIObject sym = JVMCIENV->create_string(cp->signature_ref_at(which, (Bytecodes::Code)opcode), JVMCI_CHECK_NULL);
 924   return JVMCIENV->get_jobject(sym);
 925 C2V_END
 926 
 927 C2V_VMENTRY_0(jint, lookupKlassRefIndexInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
 928   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 929   return cp->klass_ref_index_at(index, (Bytecodes::Code)opcode);
 930 C2V_END
 931 
 932 C2V_VMENTRY_NULL(jobject, resolveTypeInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
 933   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 934   Klass* klass = cp->klass_at(index, CHECK_NULL);
 935   JVMCIKlassHandle resolved_klass(THREAD, klass);
 936   if (resolved_klass->is_instance_klass()) {
 937     InstanceKlass::cast(resolved_klass())->link_class(CHECK_NULL);
 938     if (!InstanceKlass::cast(resolved_klass())->is_linked()) {
 939       // link_class() should not return here if there is an issue.
 940       JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be linked", resolved_klass()->external_name()));
 941     }
 942   }
 943   JVMCIObject klassObject = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
 944   return JVMCIENV->get_jobject(klassObject);
 945 C2V_END
 946 
 947 C2V_VMENTRY_NULL(jobject, lookupKlassInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
 948   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 949   Klass* loading_klass = cp->pool_holder();
 950   bool is_accessible = false;
 951   JVMCIKlassHandle klass(THREAD, JVMCIRuntime::get_klass_by_index(cp, index, is_accessible, loading_klass));
 952   Symbol* symbol = nullptr;
 953   if (klass.is_null()) {
 954     constantTag tag = cp->tag_at(index);
 955     if (tag.is_klass()) {
 956       // The klass has been inserted into the constant pool
 957       // very recently.
 958       klass = cp->resolved_klass_at(index);
 959     } else if (tag.is_symbol()) {
 960       symbol = cp->symbol_at(index);
 961     } else {
 962       if (!tag.is_unresolved_klass()) {
 963         JVMCI_THROW_MSG_NULL(InternalError, err_msg("Expected %d at index %d, got %d", JVM_CONSTANT_UnresolvedClassInError, index, tag.value()));
 964       }
 965       symbol = cp->klass_name_at(index);
 966     }
 967   }
 968   JVMCIObject result;
 969   if (!klass.is_null()) {
 970     result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
 971   } else {
 972     result = JVMCIENV->create_string(symbol, JVMCI_CHECK_NULL);
 973   }
 974   return JVMCIENV->get_jobject(result);
 975 C2V_END
 976 
 977 C2V_VMENTRY_NULL(jobject, lookupAppendixInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
 978   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 979   oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, which, Bytecodes::Code(opcode));
 980   return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(appendix_oop));
 981 C2V_END
 982 
 983 C2V_VMENTRY_NULL(jobject, lookupMethodInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jbyte opcode, ARGUMENT_PAIR(caller)))
 984   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 985   methodHandle caller(THREAD, UNPACK_PAIR(Method, caller));
 986   InstanceKlass* pool_holder = cp->pool_holder();
 987   Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
 988   methodHandle method(THREAD, JVMCIRuntime::get_method_by_index(cp, index, bc, pool_holder));
 989   JFR_ONLY(if (method.not_null()) Jfr::on_resolution(caller(), method(), CHECK_NULL);)
 990   JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
 991   return JVMCIENV->get_jobject(result);
 992 C2V_END
 993 
 994 C2V_VMENTRY_NULL(jobject, resolveFieldInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, ARGUMENT_PAIR(method), jbyte opcode, jintArray info_handle))
 995   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
 996   Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
 997   fieldDescriptor fd;
 998   methodHandle mh(THREAD, UNPACK_PAIR(Method, method));
 999 
1000   Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
1001   int holder_index = cp->klass_ref_index_at(index, bc);
1002   if (!cp->tag_at(holder_index).is_klass() && !THREAD->can_call_java()) {
1003     // If the holder is not resolved in the constant pool and the current
1004     // thread cannot call Java, return null. This avoids a Java call
1005     // in LinkInfo to load the holder.
1006     Symbol* klass_name = cp->klass_ref_at_noresolve(index, bc);
1007     return nullptr;
1008   }
1009 
1010   LinkInfo link_info(cp, index, mh, code, CHECK_NULL);
1011   LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_NULL);
1012   JVMCIPrimitiveArray info = JVMCIENV->wrap(info_handle);
1013   if (info.is_null() || JVMCIENV->get_length(info) != 4) {
1014     JVMCI_ERROR_NULL("info must not be null and have a length of 4");
1015   }
1016   JVMCIENV->put_int_at(info, 0, fd.access_flags().as_field_flags());
1017   JVMCIENV->put_int_at(info, 1, fd.offset());
1018   JVMCIENV->put_int_at(info, 2, fd.index());
1019   JVMCIENV->put_int_at(info, 3, fd.field_flags().as_uint());
1020   JVMCIKlassHandle handle(THREAD, fd.field_holder());
1021   JVMCIObject field_holder = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
1022   return JVMCIENV->get_jobject(field_holder);
1023 C2V_END
1024 
1025 C2V_VMENTRY_0(jint, getVtableIndexForInterfaceMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(method)))
1026   Klass* klass = UNPACK_PAIR(Klass, klass);
1027   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1028   InstanceKlass* holder = method->method_holder();
1029   if (klass->is_interface()) {
1030     JVMCI_THROW_MSG_0(InternalError, err_msg("Interface %s should be handled in Java code", klass->external_name()));
1031   }
1032   if (!holder->is_interface()) {
1033     JVMCI_THROW_MSG_0(InternalError, err_msg("Method %s is not held by an interface, this case should be handled in Java code", method->name_and_sig_as_C_string()));
1034   }
1035   if (!klass->is_instance_klass()) {
1036     JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
1037   }
1038   if (!InstanceKlass::cast(klass)->is_linked()) {
1039     JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be linked", klass->external_name()));
1040   }
1041   if (!klass->is_subtype_of(holder)) {
1042     JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s does not implement interface %s", klass->external_name(), holder->external_name()));
1043   }
1044   return LinkResolver::vtable_index_of_interface_method(klass, method);
1045 C2V_END
1046 
1047 C2V_VMENTRY_NULL(jobject, resolveMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(receiver), ARGUMENT_PAIR(method), ARGUMENT_PAIR(caller)))
1048   Klass* recv_klass = UNPACK_PAIR(Klass, receiver);
1049   Klass* caller_klass = UNPACK_PAIR(Klass, caller);
1050   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1051 
1052   Klass* resolved     = method->method_holder();
1053   Symbol* h_name      = method->name();
1054   Symbol* h_signature = method->signature();
1055 
1056   if (MethodHandles::is_signature_polymorphic_method(method())) {
1057       // Signature polymorphic methods are already resolved, JVMCI just returns null in this case.
1058       return nullptr;
1059   }
1060 
1061   if (method->name() == vmSymbols::clone_name() &&
1062       resolved == vmClasses::Object_klass() &&
1063       recv_klass->is_array_klass()) {
1064     // Resolution of the clone method on arrays always returns Object.clone even though that method
1065     // has protected access.  There's some trickery in the access checking to make this all work out
1066     // so it's necessary to pass in the array class as the resolved class to properly trigger this.
1067     // Otherwise it's impossible to resolve the array clone methods through JVMCI.  See
1068     // LinkResolver::check_method_accessability for the matching logic.
1069     resolved = recv_klass;
1070   }
1071 
1072   LinkInfo link_info(resolved, h_name, h_signature, caller_klass);
1073   Method* m = nullptr;
1074   // Only do exact lookup if receiver klass has been linked.  Otherwise,
1075   // the vtable has not been setup, and the LinkResolver will fail.
1076   if (recv_klass->is_array_klass() ||
1077       (InstanceKlass::cast(recv_klass)->is_linked() && !recv_klass->is_interface())) {
1078     if (resolved->is_interface()) {
1079       m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
1080     } else {
1081       m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
1082     }
1083   }
1084 
1085   if (m == nullptr) {
1086     // Return null if there was a problem with lookup (uninitialized class, etc.)
1087     return nullptr;
1088   }
1089 
1090   JVMCIObject result = JVMCIENV->get_jvmci_method(methodHandle(THREAD, m), JVMCI_CHECK_NULL);
1091   return JVMCIENV->get_jobject(result);
1092 C2V_END
1093 
1094 C2V_VMENTRY_0(jboolean, hasFinalizableSubclass,(JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1095   Klass* klass = UNPACK_PAIR(Klass, klass);
1096   assert(klass != nullptr, "method must not be called for primitive types");
1097   if (!klass->is_instance_klass()) {
1098     return false;
1099   }
1100   InstanceKlass* iklass = InstanceKlass::cast(klass);
1101   return Dependencies::find_finalizable_subclass(iklass) != nullptr;
1102 C2V_END
1103 
1104 C2V_VMENTRY_NULL(jobject, getClassInitializer, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1105   Klass* klass = UNPACK_PAIR(Klass, klass);
1106   if (!klass->is_instance_klass()) {
1107     return nullptr;
1108   }
1109   InstanceKlass* iklass = InstanceKlass::cast(klass);
1110   methodHandle clinit(THREAD, iklass->class_initializer());
1111   JVMCIObject result = JVMCIENV->get_jvmci_method(clinit, JVMCI_CHECK_NULL);
1112   return JVMCIENV->get_jobject(result);
1113 C2V_END
1114 
1115 C2V_VMENTRY_0(jlong, getMaxCallTargetOffset, (JNIEnv* env, jobject, jlong addr))
1116   address target_addr = (address) addr;
1117   if (target_addr != nullptr) {
1118     int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
1119     int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
1120     return MAX2(ABS(off_low), ABS(off_high));
1121   }
1122   return -1;
1123 C2V_END
1124 
1125 C2V_VMENTRY(void, setNotInlinableOrCompilable,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1126   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1127   method->set_is_not_c1_compilable();
1128   method->set_is_not_c2_compilable();
1129   method->set_dont_inline(true);
1130 C2V_END
1131 
1132 C2V_VMENTRY_0(jint, getInstallCodeFlags, (JNIEnv *env, jobject))
1133   int flags = 0;
1134 #ifndef PRODUCT
1135   flags |= 0x0001; // VM will install block comments
1136   flags |= 0x0004; // Enable HotSpotJVMCIRuntime.Option.CodeSerializationTypeInfo if not explicitly set
1137 #endif
1138   if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1139     // VM needs to track method dependencies
1140     flags |= 0x0002;
1141   }
1142   return flags;
1143 C2V_END
1144 
1145 C2V_VMENTRY_0(jint, installCode0, (JNIEnv *env, jobject,
1146     jlong compiled_code_buffer,
1147     jlong serialization_ns,
1148     bool with_type_info,
1149     jobject compiled_code,
1150     jobjectArray object_pool,
1151     jobject installed_code,
1152     jlong failed_speculations_address,
1153     jbyteArray speculations_obj))
1154   HandleMark hm(THREAD);
1155   JNIHandleMark jni_hm(thread);
1156 
1157   JVMCIObject compiled_code_handle = JVMCIENV->wrap(compiled_code);
1158   objArrayHandle object_pool_handle(thread, JVMCIENV->is_hotspot() ? (objArrayOop) JNIHandles::resolve(object_pool) : nullptr);
1159 
1160   CodeBlob* cb = nullptr;
1161   JVMCIObject installed_code_handle = JVMCIENV->wrap(installed_code);
1162   JVMCIPrimitiveArray speculations_handle = JVMCIENV->wrap(speculations_obj);
1163 
1164   int speculations_len = JVMCIENV->get_length(speculations_handle);
1165   char* speculations = NEW_RESOURCE_ARRAY(char, speculations_len);
1166   JVMCIENV->copy_bytes_to(speculations_handle, (jbyte*) speculations, 0, speculations_len);
1167 
1168   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK_JNI_ERR);
1169   JVMCICompiler::CodeInstallStats* stats = compiler->code_install_stats(!thread->is_Compiler_thread());
1170   elapsedTimer *timer = stats->timer();
1171   timer->add_nanoseconds(serialization_ns);
1172   TraceTime install_time("installCode", timer);
1173 
1174   CodeInstaller installer(JVMCIENV);
1175   JVMCINMethodHandle nmethod_handle(THREAD);
1176 
1177   JVMCI::CodeInstallResult result = installer.install(compiler,
1178       compiled_code_buffer,
1179       with_type_info,
1180       compiled_code_handle,
1181       object_pool_handle,
1182       cb,
1183       nmethod_handle,
1184       installed_code_handle,
1185       (FailedSpeculation**)(address) failed_speculations_address,
1186       speculations,
1187       speculations_len,
1188       JVMCI_CHECK_0);
1189 
1190   if (PrintCodeCacheOnCompilation) {
1191     stringStream s;
1192     // Dump code cache into a buffer before locking the tty,
1193     {
1194       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1195       CodeCache::print_summary(&s, false);
1196     }
1197     ttyLocker ttyl;
1198     tty->print_raw_cr(s.freeze());
1199   }
1200 
1201   if (result != JVMCI::ok) {
1202     assert(cb == nullptr, "should be");
1203   } else {
1204     stats->on_install(cb);
1205     if (installed_code_handle.is_non_null()) {
1206       if (cb->is_nmethod()) {
1207         assert(JVMCIENV->isa_HotSpotNmethod(installed_code_handle), "wrong type");
1208         // Clear the link to an old nmethod first
1209         JVMCIObject nmethod_mirror = installed_code_handle;
1210         JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, true, nmethod::ChangeReason::JVMCI_replacing_with_new_code, JVMCI_CHECK_0);
1211       } else {
1212         assert(JVMCIENV->isa_InstalledCode(installed_code_handle), "wrong type");
1213       }
1214       // Initialize the link to the new code blob
1215       JVMCIENV->initialize_installed_code(installed_code_handle, cb, JVMCI_CHECK_0);
1216     }
1217   }
1218   return result;
1219 C2V_END
1220 
1221 C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv* env, jobject))
1222   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK);
1223   CompilerStatistics* stats = compiler->stats();
1224   stats->_standard.reset();
1225   stats->_osr.reset();
1226 C2V_END
1227 
1228 C2V_VMENTRY_NULL(jobject, disassembleCodeBlob, (JNIEnv* env, jobject, jobject installedCode))
1229   HandleMark hm(THREAD);
1230 
1231   if (installedCode == nullptr) {
1232     JVMCI_THROW_MSG_NULL(NullPointerException, "installedCode is null");
1233   }
1234 
1235   JVMCIObject installedCodeObject = JVMCIENV->wrap(installedCode);
1236   CodeBlob* cb = JVMCIENV->get_code_blob(installedCodeObject);
1237   if (cb == nullptr) {
1238     return nullptr;
1239   }
1240 
1241   // We don't want the stringStream buffer to resize during disassembly as it
1242   // uses scoped resource memory. If a nested function called during disassembly uses
1243   // a ResourceMark and the buffer expands within the scope of the mark,
1244   // the buffer becomes garbage when that scope is exited. Experience shows that
1245   // the disassembled code is typically about 10x the code size so a fixed buffer
1246   // sized to 20x code size plus a fixed amount for header info should be sufficient.
1247   int bufferSize = cb->code_size() * 20 + 1024;
1248   char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
1249   stringStream st(buffer, bufferSize);
1250   Disassembler::decode(cb, &st);
1251   if (st.size() <= 0) {
1252     return nullptr;
1253   }
1254 
1255   JVMCIObject result = JVMCIENV->create_string(st.as_string(), JVMCI_CHECK_NULL);
1256   return JVMCIENV->get_jobject(result);
1257 C2V_END
1258 
1259 C2V_VMENTRY_NULL(jobject, getStackTraceElement, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int bci))
1260   HandleMark hm(THREAD);
1261 
1262   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1263   JVMCIObject element = JVMCIENV->new_StackTraceElement(method, bci, JVMCI_CHECK_NULL);
1264   return JVMCIENV->get_jobject(element);
1265 C2V_END
1266 
1267 C2V_VMENTRY_NULL(jobject, executeHotSpotNmethod, (JNIEnv* env, jobject, jobject args, jobject hs_nmethod))
1268   // The incoming arguments array would have to contain JavaConstants instead of regular objects
1269   // and the return value would have to be wrapped as a JavaConstant.
1270   requireInHotSpot("executeHotSpotNmethod", JVMCI_CHECK_NULL);
1271 
1272   HandleMark hm(THREAD);
1273 
1274   JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
1275   methodHandle mh;
1276   {
1277     // Reduce the scope of JVMCINMethodHandle so that it isn't alive across the Java call.  Once the
1278     // nmethod has been validated and the method is fetched from the nmethod it's fine for the
1279     // nmethod to be reclaimed if necessary.
1280     JVMCINMethodHandle nmethod_handle(THREAD);
1281     nmethod* nm = JVMCIENV->get_nmethod(nmethod_mirror, nmethod_handle);
1282     if (nm == nullptr || !nm->is_in_use()) {
1283       JVMCI_THROW_NULL(InvalidInstalledCodeException);
1284     }
1285     methodHandle nmh(THREAD, nm->method());
1286     mh = nmh;
1287   }
1288   Symbol* signature = mh->signature();
1289   JavaCallArguments jca(mh->size_of_parameters());
1290 
1291   JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
1292   JavaValue result(jap.return_type());
1293   jca.set_alternative_target(Handle(THREAD, JNIHandles::resolve(nmethod_mirror.as_jobject())));
1294   JavaCalls::call(&result, mh, &jca, CHECK_NULL);
1295 
1296   if (jap.return_type() == T_VOID) {
1297     return nullptr;
1298   } else if (is_reference_type(jap.return_type())) {
1299     return JNIHandles::make_local(THREAD, result.get_oop());
1300   } else {
1301     jvalue *value = (jvalue *) result.get_value_addr();
1302     // Narrow the value down if required (Important on big endian machines)
1303     switch (jap.return_type()) {
1304       case T_BOOLEAN:
1305        value->z = (jboolean) value->i;
1306        break;
1307       case T_BYTE:
1308        value->b = (jbyte) value->i;
1309        break;
1310       case T_CHAR:
1311        value->c = (jchar) value->i;
1312        break;
1313       case T_SHORT:
1314        value->s = (jshort) value->i;
1315        break;
1316       default:
1317         break;
1318     }
1319     JVMCIObject o = JVMCIENV->create_box(jap.return_type(), value, JVMCI_CHECK_NULL);
1320     return JVMCIENV->get_jobject(o);
1321   }
1322 C2V_END
1323 
1324 C2V_VMENTRY_NULL(jlongArray, getLineNumberTable, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1325   Method* method = UNPACK_PAIR(Method, method);
1326   if (!method->has_linenumber_table()) {
1327     return nullptr;
1328   }
1329   u2 num_entries = 0;
1330   CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
1331   while (streamForSize.read_pair()) {
1332     num_entries++;
1333   }
1334 
1335   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
1336   JVMCIPrimitiveArray result = JVMCIENV->new_longArray(2 * num_entries, JVMCI_CHECK_NULL);
1337 
1338   int i = 0;
1339   jlong value;
1340   while (stream.read_pair()) {
1341     value = ((jlong) stream.bci());
1342     JVMCIENV->put_long_at(result, i, value);
1343     value = ((jlong) stream.line());
1344     JVMCIENV->put_long_at(result, i + 1, value);
1345     i += 2;
1346   }
1347 
1348   return (jlongArray) JVMCIENV->get_jobject(result);
1349 C2V_END
1350 
1351 C2V_VMENTRY_0(jlong, getLocalVariableTableStart, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1352   Method* method = UNPACK_PAIR(Method, method);
1353   if (!method->has_localvariable_table()) {
1354     return 0;
1355   }
1356   return (jlong) (address) method->localvariable_table_start();
1357 C2V_END
1358 
1359 C2V_VMENTRY_0(jint, getLocalVariableTableLength, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1360   Method* method = UNPACK_PAIR(Method, method);
1361   return method->localvariable_table_length();
1362 C2V_END
1363 
1364 static MethodData* get_profiling_method_data(const methodHandle& method, TRAPS) {
1365   MethodData* method_data = method->method_data();
1366   if (method_data == nullptr) {
1367     method->build_profiling_method_data(method, CHECK_NULL);
1368     method_data = method->method_data();
1369     if (method_data == nullptr) {
1370       THROW_MSG_NULL(vmSymbols::java_lang_OutOfMemoryError(), "cannot allocate MethodData")
1371     }
1372   }
1373   return method_data;
1374 }
1375 
1376 C2V_VMENTRY(void, reprofile, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1377   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1378   MethodCounters* mcs = method->method_counters();
1379   if (mcs != nullptr) {
1380     mcs->clear_counters();
1381   }
1382   NOT_PRODUCT(method->set_compiled_invocation_count(0));
1383 
1384   nmethod* code = method->code();
1385   if (code != nullptr) {
1386     code->make_not_entrant(nmethod::ChangeReason::JVMCI_reprofile);
1387   }
1388 
1389   MethodData* method_data = method->method_data();
1390   if (method_data == nullptr) {
1391     method_data = get_profiling_method_data(method, CHECK);
1392   } else {
1393     CompilerThreadCanCallJava canCallJava(THREAD, true);
1394     method_data->reinitialize();
1395   }
1396 C2V_END
1397 
1398 
1399 C2V_VMENTRY(void, invalidateHotSpotNmethod, (JNIEnv* env, jobject, jobject hs_nmethod, jboolean deoptimize))
1400   JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
1401   JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, deoptimize, nmethod::ChangeReason::JVMCI_invalidate_nmethod, JVMCI_CHECK);
1402 C2V_END
1403 
1404 C2V_VMENTRY_NULL(jlongArray, collectCounters, (JNIEnv* env, jobject))
1405   // Returns a zero length array if counters aren't enabled
1406   JVMCIPrimitiveArray array = JVMCIENV->new_longArray(JVMCICounterSize, JVMCI_CHECK_NULL);
1407   if (JVMCICounterSize > 0) {
1408     jlong* temp_array = NEW_RESOURCE_ARRAY(jlong, JVMCICounterSize);
1409     JavaThread::collect_counters(temp_array, JVMCICounterSize);
1410     JVMCIENV->copy_longs_from(temp_array, array, 0, JVMCICounterSize);
1411   }
1412   return (jlongArray) JVMCIENV->get_jobject(array);
1413 C2V_END
1414 
1415 C2V_VMENTRY_0(jint, getCountersSize, (JNIEnv* env, jobject))
1416   return (jint) JVMCICounterSize;
1417 C2V_END
1418 
1419 C2V_VMENTRY_0(jboolean, setCountersSize, (JNIEnv* env, jobject, jint new_size))
1420   return JavaThread::resize_all_jvmci_counters(new_size);
1421 C2V_END
1422 
1423 C2V_VMENTRY_0(jint, allocateCompileId, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci))
1424   HandleMark hm(THREAD);
1425   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1426   if (method.is_null()) {
1427     JVMCI_THROW_0(NullPointerException);
1428   }
1429   if (entry_bci >= method->code_size() || entry_bci < -1) {
1430     JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Unexpected bci %d", entry_bci));
1431   }
1432   return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
1433 C2V_END
1434 
1435 
1436 C2V_VMENTRY_0(jboolean, isMature, (JNIEnv* env, jobject, jlong method_data_pointer))
1437   MethodData* mdo = (MethodData*) method_data_pointer;
1438   return mdo != nullptr && mdo->is_mature();
1439 C2V_END
1440 
1441 C2V_VMENTRY_0(jboolean, hasCompiledCodeForOSR, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci, int comp_level))
1442   Method* method = UNPACK_PAIR(Method, method);
1443   return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != nullptr;
1444 C2V_END
1445 
1446 C2V_VMENTRY_NULL(jobject, getSymbol, (JNIEnv* env, jobject, jlong symbol))
1447   JVMCIObject sym = JVMCIENV->create_string((Symbol*)(address)symbol, JVMCI_CHECK_NULL);
1448   return JVMCIENV->get_jobject(sym);
1449 C2V_END
1450 
1451 C2V_VMENTRY_NULL(jobject, getSignatureName, (JNIEnv* env, jobject, jlong klass_pointer))
1452   Klass* klass = UNPACK_PAIR(Klass, klass);
1453   JVMCIObject signature = JVMCIENV->create_string(klass->signature_name(), JVMCI_CHECK_NULL);
1454   return JVMCIENV->get_jobject(signature);
1455 C2V_END
1456 
1457 /*
1458  * Used by matches() to convert a ResolvedJavaMethod[] to an array of Method*.
1459  */
1460 static GrowableArray<Method*>* init_resolved_methods(jobjectArray methods, JVMCIEnv* JVMCIENV) {
1461   objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
1462   GrowableArray<Method*>* resolved_methods = new GrowableArray<Method*>(methods_oop->length());
1463   for (int i = 0; i < methods_oop->length(); i++) {
1464     oop resolved = methods_oop->obj_at(i);
1465     Method* resolved_method = nullptr;
1466     if (resolved->klass() == HotSpotJVMCI::HotSpotResolvedJavaMethodImpl::klass()) {
1467       resolved_method = HotSpotJVMCI::asMethod(JVMCIENV, resolved);
1468     }
1469     resolved_methods->append(resolved_method);
1470   }
1471   return resolved_methods;
1472 }
1473 
1474 /*
1475  * Used by c2v_iterateFrames to check if `method` matches one of the ResolvedJavaMethods in the `methods` array.
1476  * The ResolvedJavaMethod[] array is converted to a Method* array that is then cached in the resolved_methods_ref in/out parameter.
1477  * In case of a match, the matching ResolvedJavaMethod is returned in matched_jvmci_method_ref.
1478  */
1479 static bool matches(jobjectArray methods, Method* method, GrowableArray<Method*>** resolved_methods_ref, Handle* matched_jvmci_method_ref, Thread* THREAD, JVMCIEnv* JVMCIENV) {
1480   GrowableArray<Method*>* resolved_methods = *resolved_methods_ref;
1481   if (resolved_methods == nullptr) {
1482     resolved_methods = init_resolved_methods(methods, JVMCIENV);
1483     *resolved_methods_ref = resolved_methods;
1484   }
1485   assert(method != nullptr, "method should not be null");
1486   assert(resolved_methods->length() == ((objArrayOop) JNIHandles::resolve(methods))->length(), "arrays must have the same length");
1487   for (int i = 0; i < resolved_methods->length(); i++) {
1488     Method* m = resolved_methods->at(i);
1489     if (m == method) {
1490       *matched_jvmci_method_ref = Handle(THREAD, ((objArrayOop) JNIHandles::resolve(methods))->obj_at(i));
1491       return true;
1492     }
1493   }
1494   return false;
1495 }
1496 
1497 /*
1498  * Resolves an interface call to a concrete method handle.
1499  */
1500 static methodHandle resolve_interface_call(Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
1501   CallInfo callinfo;
1502   Handle receiver = args->receiver();
1503   Klass* recvrKlass = receiver.is_null() ? (Klass*)nullptr : receiver->klass();
1504   LinkInfo link_info(spec_klass, name, signature);
1505   LinkResolver::resolve_interface_call(
1506           callinfo, receiver, recvrKlass, link_info, true, CHECK_(methodHandle()));
1507   methodHandle method(THREAD, callinfo.selected_method());
1508   assert(method.not_null(), "should have thrown exception");
1509   return method;
1510 }
1511 
1512 /*
1513  * Used by c2v_iterateFrames to make a new vframeStream at the given compiled frame id (stack pointer) and vframe id.
1514  */
1515 static void resync_vframestream_to_compiled_frame(vframeStream& vfst, intptr_t* stack_pointer, int vframe_id, JavaThread* thread, TRAPS) {
1516   vfst = vframeStream(thread);
1517   while (vfst.frame_id() != stack_pointer && !vfst.at_end()) {
1518     vfst.next();
1519   }
1520   if (vfst.frame_id() != stack_pointer) {
1521     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1522   }
1523   if (vfst.is_interpreted_frame()) {
1524     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1525   }
1526   while (vfst.vframe_id() != vframe_id) {
1527     if (vfst.at_end()) {
1528       THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
1529     }
1530     vfst.next();
1531     assert(!vfst.is_interpreted_frame(), "Wrong frame type");
1532   }
1533 }
1534 
1535 /*
1536  * Used by c2v_iterateFrames. Returns an array of any unallocated scope objects or null if none.
1537  */
1538 static GrowableArray<ScopeValue*>* get_unallocated_objects_or_null(GrowableArray<ScopeValue*>* scope_objects) {
1539   GrowableArray<ScopeValue*>* unallocated = nullptr;
1540   for (int i = 0; i < scope_objects->length(); i++) {
1541     ObjectValue* sv = (ObjectValue*) scope_objects->at(i);
1542     if (sv->value().is_null()) {
1543       if (unallocated == nullptr) {
1544         unallocated = new GrowableArray<ScopeValue*>(scope_objects->length());
1545       }
1546       unallocated->append(sv);
1547     }
1548   }
1549   return unallocated;
1550 }
1551 
1552 C2V_VMENTRY_NULL(jobject, iterateFrames, (JNIEnv* env, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
1553 
1554   if (!thread->has_last_Java_frame()) {
1555     return nullptr;
1556   }
1557   Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
1558   KeepStackGCProcessedMark keep_stack(THREAD);
1559 
1560   requireInHotSpot("iterateFrames", JVMCI_CHECK_NULL);
1561 
1562   HotSpotJVMCI::HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1563 
1564   vframeStream vfst(thread);
1565   jobjectArray methods = initial_methods;
1566   methodHandle visitor_method;
1567   GrowableArray<Method*>* resolved_methods = nullptr;
1568 
1569   while (!vfst.at_end()) { // frame loop
1570     bool realloc_called = false;
1571     intptr_t* frame_id = vfst.frame_id();
1572 
1573     // Previous compiledVFrame of this frame; use with at_scope() to reuse scope object pool.
1574     compiledVFrame* prev_cvf = nullptr;
1575 
1576     for (; !vfst.at_end() && vfst.frame_id() == frame_id; vfst.next()) { // vframe loop
1577       int frame_number = 0;
1578       Method *method = vfst.method();
1579       int bci = vfst.bci();
1580 
1581       Handle matched_jvmci_method;
1582       if (methods == nullptr || matches(methods, method, &resolved_methods, &matched_jvmci_method, THREAD, JVMCIENV)) {
1583         if (initialSkip > 0) {
1584           initialSkip--;
1585           continue;
1586         }
1587         javaVFrame* vf;
1588         if (prev_cvf != nullptr && prev_cvf->frame_pointer()->id() == frame_id) {
1589           assert(prev_cvf->is_compiled_frame(), "expected compiled Java frame");
1590           vf = prev_cvf->at_scope(vfst.decode_offset(), vfst.vframe_id());
1591         } else {
1592           vf = vfst.asJavaVFrame();
1593         }
1594 
1595         StackValueCollection* locals = nullptr;
1596         typeArrayHandle localIsVirtual_h;
1597         if (vf->is_compiled_frame()) {
1598           // compiled method frame
1599           compiledVFrame* cvf = compiledVFrame::cast(vf);
1600 
1601           ScopeDesc* scope = cvf->scope();
1602           // native wrappers do not have a scope
1603           if (scope != nullptr && scope->objects() != nullptr) {
1604             prev_cvf = cvf;
1605 
1606             GrowableArray<ScopeValue*>* objects = nullptr;
1607             if (!realloc_called) {
1608               objects = scope->objects();
1609             } else {
1610               // some object might already have been re-allocated, only reallocate the non-allocated ones
1611               objects = get_unallocated_objects_or_null(scope->objects());
1612             }
1613 
1614             if (objects != nullptr) {
1615               RegisterMap reg_map(vf->register_map());
1616               bool realloc_failures = Deoptimization::realloc_objects(thread, vf->frame_pointer(), &reg_map, objects, CHECK_NULL);
1617               Deoptimization::reassign_fields(vf->frame_pointer(), &reg_map, objects, realloc_failures, false);
1618               realloc_called = true;
1619             }
1620 
1621             GrowableArray<ScopeValue*>* local_values = scope->locals();
1622             for (int i = 0; i < local_values->length(); i++) {
1623               ScopeValue* value = local_values->at(i);
1624               assert(!value->is_object_merge(), "Should not be.");
1625               if (value->is_object()) {
1626                 if (localIsVirtual_h.is_null()) {
1627                   typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
1628                   localIsVirtual_h = typeArrayHandle(THREAD, array_oop);
1629                 }
1630                 localIsVirtual_h->bool_at_put(i, true);
1631               }
1632             }
1633           }
1634 
1635           locals = cvf->locals();
1636           frame_number = cvf->vframe_id();
1637         } else {
1638           // interpreted method frame
1639           interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1640 
1641           locals = ivf->locals();
1642         }
1643         assert(bci == vf->bci(), "wrong bci");
1644         assert(method == vf->method(), "wrong method");
1645 
1646         Handle frame_reference = HotSpotJVMCI::HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1647         HotSpotJVMCI::HotSpotStackFrameReference::set_bci(JVMCIENV, frame_reference(), bci);
1648         if (matched_jvmci_method.is_null()) {
1649           methodHandle mh(THREAD, method);
1650           JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
1651           matched_jvmci_method = Handle(THREAD, JNIHandles::resolve(jvmci_method.as_jobject()));
1652         }
1653         HotSpotJVMCI::HotSpotStackFrameReference::set_method(JVMCIENV, frame_reference(), matched_jvmci_method());
1654         HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), localIsVirtual_h());
1655 
1656         HotSpotJVMCI::HotSpotStackFrameReference::set_compilerToVM(JVMCIENV, frame_reference(), JNIHandles::resolve(compilerToVM));
1657         HotSpotJVMCI::HotSpotStackFrameReference::set_stackPointer(JVMCIENV, frame_reference(), (jlong) frame_id);
1658         HotSpotJVMCI::HotSpotStackFrameReference::set_frameNumber(JVMCIENV, frame_reference(), frame_number);
1659 
1660         // initialize the locals array
1661         objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
1662         objArrayHandle array(THREAD, array_oop);
1663         for (int i = 0; i < locals->size(); i++) {
1664           StackValue* var = locals->at(i);
1665           if (var->type() == T_OBJECT) {
1666             array->obj_at_put(i, locals->at(i)->get_obj()());
1667           }
1668         }
1669         HotSpotJVMCI::HotSpotStackFrameReference::set_locals(JVMCIENV, frame_reference(), array());
1670         HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, frame_reference(), JNI_FALSE);
1671 
1672         JavaValue result(T_OBJECT);
1673         JavaCallArguments args(visitor);
1674         if (visitor_method.is_null()) {
1675           visitor_method = resolve_interface_call(HotSpotJVMCI::InspectedFrameVisitor::klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
1676         }
1677 
1678         args.push_oop(frame_reference);
1679         JavaCalls::call(&result, visitor_method, &args, CHECK_NULL);
1680         if (result.get_oop() != nullptr) {
1681           return JNIHandles::make_local(thread, result.get_oop());
1682         }
1683         if (methods == initial_methods) {
1684           methods = match_methods;
1685           if (resolved_methods != nullptr && JNIHandles::resolve(match_methods) != JNIHandles::resolve(initial_methods)) {
1686             resolved_methods = nullptr;
1687           }
1688         }
1689         assert(initialSkip == 0, "There should be no match before initialSkip == 0");
1690         if (HotSpotJVMCI::HotSpotStackFrameReference::objectsMaterialized(JVMCIENV, frame_reference()) == JNI_TRUE) {
1691           // the frame has been deoptimized, we need to re-synchronize the frame and vframe
1692           prev_cvf = nullptr;
1693           intptr_t* stack_pointer = (intptr_t*) HotSpotJVMCI::HotSpotStackFrameReference::stackPointer(JVMCIENV, frame_reference());
1694           resync_vframestream_to_compiled_frame(vfst, stack_pointer, frame_number, thread, CHECK_NULL);
1695         }
1696       }
1697     } // end of vframe loop
1698   } // end of frame loop
1699 
1700   // the end was reached without finding a matching method
1701   return nullptr;
1702 C2V_END
1703 
1704 C2V_VMENTRY_0(int, decodeIndyIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint indy_index, jboolean resolve))
1705   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1706   CallInfo callInfo;
1707   if (resolve) {
1708     LinkResolver::resolve_invoke(callInfo, Handle(), cp, indy_index, Bytecodes::_invokedynamic, CHECK_0);
1709     cp->cache()->set_dynamic_call(callInfo, indy_index);
1710   }
1711   return cp->resolved_indy_entry_at(indy_index)->constant_pool_index();
1712 C2V_END
1713 
1714 C2V_VMENTRY_0(int, decodeFieldIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint field_index))
1715   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1716   if (field_index < 0 || field_index >= cp->resolved_field_entries_length()) {
1717     JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid field index %d", field_index));
1718   }
1719   return cp->resolved_field_entry_at(field_index)->constant_pool_index();
1720 C2V_END
1721 
1722 C2V_VMENTRY_0(int, decodeMethodIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint method_index))
1723   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1724   if (method_index < 0 || method_index >= cp->resolved_method_entries_length()) {
1725     JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid method index %d", method_index));
1726   }
1727   return cp->resolved_method_entry_at(method_index)->constant_pool_index();
1728 C2V_END
1729 
1730 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
1731   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1732   Klass* holder = cp->klass_ref_at(index, Bytecodes::_invokehandle, CHECK);
1733   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1734   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1735     CallInfo callInfo;
1736     LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1737     cp->cache()->set_method_handle(index, callInfo);
1738   }
1739 C2V_END
1740 
1741 C2V_VMENTRY_0(jint, isResolvedInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
1742   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1743   ResolvedMethodEntry* entry = cp->cache()->resolved_method_entry_at(index);
1744   if (entry->is_resolved(Bytecodes::_invokehandle)) {
1745     // MethodHandle.invoke* --> LambdaForm?
1746     ResourceMark rm;
1747 
1748     LinkInfo link_info(cp, index, Bytecodes::_invokehandle, CATCH);
1749 
1750     Klass* resolved_klass = link_info.resolved_klass();
1751 
1752     Symbol* name_sym = cp->name_ref_at(index, Bytecodes::_invokehandle);
1753 
1754     vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
1755     vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
1756 
1757     methodHandle adapter_method(THREAD, entry->method());
1758 
1759     methodHandle resolved_method(adapter_method);
1760 
1761     // Can we treat it as a regular invokevirtual?
1762     if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
1763       vmassert(!resolved_method->is_static(),"!");
1764       vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
1765       vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
1766       vmassert(cp->cache()->appendix_if_resolved(entry) == nullptr, "!");
1767 
1768       methodHandle m(THREAD, LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
1769       vmassert(m == resolved_method, "!!");
1770       return -1;
1771     }
1772 
1773     return Bytecodes::_invokevirtual;
1774   }
1775   if ((Bytecodes::Code)opcode == Bytecodes::_invokedynamic) {
1776     if (cp->resolved_indy_entry_at(index)->is_resolved()) {
1777       return Bytecodes::_invokedynamic;
1778     }
1779   }
1780   return -1;
1781 C2V_END
1782 
1783 
1784 C2V_VMENTRY_NULL(jobject, getSignaturePolymorphicHolders, (JNIEnv* env, jobject))
1785   JVMCIObjectArray holders = JVMCIENV->new_String_array(2, JVMCI_CHECK_NULL);
1786   JVMCIObject mh = JVMCIENV->create_string("Ljava/lang/invoke/MethodHandle;", JVMCI_CHECK_NULL);
1787   JVMCIObject vh = JVMCIENV->create_string("Ljava/lang/invoke/VarHandle;", JVMCI_CHECK_NULL);
1788   JVMCIENV->put_object_at(holders, 0, mh);
1789   JVMCIENV->put_object_at(holders, 1, vh);
1790   return JVMCIENV->get_jobject(holders);
1791 C2V_END
1792 
1793 C2V_VMENTRY_0(jboolean, shouldDebugNonSafepoints, (JNIEnv* env, jobject))
1794   //see compute_recording_non_safepoints in debugInfroRec.cpp
1795   if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1796     return true;
1797   }
1798   return DebugNonSafepoints;
1799 C2V_END
1800 
1801 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1802 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv* env, jobject, jobject _hs_frame, bool invalidate))
1803   JVMCIObject hs_frame = JVMCIENV->wrap(_hs_frame);
1804   if (hs_frame.is_null()) {
1805     JVMCI_THROW_MSG(NullPointerException, "stack frame is null");
1806   }
1807 
1808   requireInHotSpot("materializeVirtualObjects", JVMCI_CHECK);
1809 
1810   JVMCIENV->HotSpotStackFrameReference_initialize(JVMCI_CHECK);
1811 
1812   // look for the given stack frame
1813   StackFrameStream fst(thread, false /* update */, true /* process_frames */);
1814   intptr_t* stack_pointer = (intptr_t*) JVMCIENV->get_HotSpotStackFrameReference_stackPointer(hs_frame);
1815   while (fst.current()->id() != stack_pointer && !fst.is_done()) {
1816     fst.next();
1817   }
1818   if (fst.current()->id() != stack_pointer) {
1819     JVMCI_THROW_MSG(IllegalStateException, "stack frame not found");
1820   }
1821 
1822   if (invalidate) {
1823     if (!fst.current()->is_compiled_frame()) {
1824       JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1825     }
1826     fst.current()->cb()->as_nmethod()->make_not_entrant(nmethod::ChangeReason::JVMCI_materialize_virtual_object);
1827   }
1828   Deoptimization::deoptimize(thread, *fst.current(), Deoptimization::Reason_none);
1829   // look for the frame again as it has been updated by deopt (pc, deopt state...)
1830   StackFrameStream fstAfterDeopt(thread, true /* update */, true /* process_frames */);
1831   while (fstAfterDeopt.current()->id() != stack_pointer && !fstAfterDeopt.is_done()) {
1832     fstAfterDeopt.next();
1833   }
1834   if (fstAfterDeopt.current()->id() != stack_pointer) {
1835     JVMCI_THROW_MSG(IllegalStateException, "stack frame not found after deopt");
1836   }
1837 
1838   vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1839   if (!vf->is_compiled_frame()) {
1840     JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1841   }
1842 
1843   GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1844   while (true) {
1845     assert(vf->is_compiled_frame(), "Wrong frame type");
1846     virtualFrames->push(compiledVFrame::cast(vf));
1847     if (vf->is_top()) {
1848       break;
1849     }
1850     vf = vf->sender();
1851   }
1852 
1853   int last_frame_number = JVMCIENV->get_HotSpotStackFrameReference_frameNumber(hs_frame);
1854   if (last_frame_number >= virtualFrames->length()) {
1855     JVMCI_THROW_MSG(IllegalStateException, "invalid frame number");
1856   }
1857 
1858   // Reallocate the non-escaping objects and restore their fields.
1859   assert (virtualFrames->at(last_frame_number)->scope() != nullptr,"invalid scope");
1860   GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1861 
1862   if (objects == nullptr) {
1863     // no objects to materialize
1864     return;
1865   }
1866 
1867   bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, CHECK);
1868   Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
1869 
1870   for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1871     compiledVFrame* cvf = virtualFrames->at(frame_index);
1872 
1873     GrowableArray<ScopeValue*>* scopedValues = cvf->scope()->locals();
1874     StackValueCollection* locals = cvf->locals();
1875     if (locals != nullptr) {
1876       for (int i2 = 0; i2 < locals->size(); i2++) {
1877         StackValue* var = locals->at(i2);
1878         assert(!scopedValues->at(i2)->is_object_merge(), "Should not be.");
1879         if (var->type() == T_OBJECT && scopedValues->at(i2)->is_object()) {
1880           jvalue val;
1881           val.l = cast_from_oop<jobject>(locals->at(i2)->get_obj()());
1882           cvf->update_local(T_OBJECT, i2, val);
1883         }
1884       }
1885     }
1886 
1887     GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
1888     StackValueCollection* expressions = cvf->expressions();
1889     if (expressions != nullptr) {
1890       for (int i2 = 0; i2 < expressions->size(); i2++) {
1891         StackValue* var = expressions->at(i2);
1892         assert(!scopeExpressions->at(i2)->is_object_merge(), "Should not be.");
1893         if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
1894           jvalue val;
1895           val.l = cast_from_oop<jobject>(expressions->at(i2)->get_obj()());
1896           cvf->update_stack(T_OBJECT, i2, val);
1897         }
1898       }
1899     }
1900 
1901     GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
1902     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1903     if (monitors != nullptr) {
1904       for (int i2 = 0; i2 < monitors->length(); i2++) {
1905         cvf->update_monitor(i2, monitors->at(i2));
1906       }
1907     }
1908   }
1909 
1910   // all locals are materialized by now
1911   JVMCIENV->set_HotSpotStackFrameReference_localIsVirtual(hs_frame, nullptr);
1912   // update the locals array
1913   JVMCIObjectArray array = JVMCIENV->get_HotSpotStackFrameReference_locals(hs_frame);
1914   StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1915   for (int i = 0; i < locals->size(); i++) {
1916     StackValue* var = locals->at(i);
1917     if (var->type() == T_OBJECT) {
1918       JVMCIENV->put_object_at(array, i, HotSpotJVMCI::wrap(locals->at(i)->get_obj()()));
1919     }
1920   }
1921   HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, hs_frame, JNI_TRUE);
1922 C2V_END
1923 
1924 // Use of tty does not require the current thread to be attached to the VM
1925 // so no need for a full C2V_VMENTRY transition.
1926 C2V_VMENTRY_PREFIX(void, writeDebugOutput, (JNIEnv* env, jobject, jlong buffer, jint length, bool flush))
1927   if (length <= 8) {
1928     tty->write((char*) &buffer, length);
1929   } else {
1930     tty->write((char*) buffer, length);
1931   }
1932   if (flush) {
1933     tty->flush();
1934   }
1935 C2V_END
1936 
1937 // Use of tty does not require the current thread to be attached to the VM
1938 // so no need for a full C2V_VMENTRY transition.
1939 C2V_VMENTRY_PREFIX(void, flushDebugOutput, (JNIEnv* env, jobject))
1940   tty->flush();
1941 C2V_END
1942 
1943 C2V_VMENTRY_0(jint, methodDataProfileDataSize, (JNIEnv* env, jobject, jlong method_data_pointer, jint position))
1944   MethodData* mdo = (MethodData*) method_data_pointer;
1945   ProfileData* profile_data = mdo->data_at(position);
1946   if (mdo->is_valid(profile_data)) {
1947     return profile_data->size_in_bytes();
1948   }
1949   // Java code should never directly access the extra data section
1950   JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Invalid profile data position %d", position));
1951 C2V_END
1952 
1953 C2V_VMENTRY_0(jint, methodDataExceptionSeen, (JNIEnv* env, jobject, jlong method_data_pointer, jint bci))
1954   MethodData* mdo = (MethodData*) method_data_pointer;
1955 
1956   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1957   MutexLocker mu(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
1958 
1959   DataLayout* data    = mdo->extra_data_base();
1960   DataLayout* end   = mdo->args_data_limit();
1961   for (;; data = mdo->next_extra(data)) {
1962     assert(data < end, "moved past end of extra data");
1963     int tag = data->tag();
1964     switch(tag) {
1965       case DataLayout::bit_data_tag: {
1966         BitData* bit_data = (BitData*) data->data_in();
1967         if (bit_data->bci() == bci) {
1968           return bit_data->exception_seen() ? 1 : 0;
1969         }
1970         break;
1971       }
1972     case DataLayout::no_tag:
1973       // There is a free slot so return false since a BitData would have been allocated to record
1974       // true if it had been seen.
1975       return 0;
1976     case DataLayout::arg_info_data_tag:
1977       // The bci wasn't found and there are no free slots to record a trap for this location, so always
1978       // return unknown.
1979       return -1;
1980     }
1981   }
1982   ShouldNotReachHere();
1983   return -1;
1984 C2V_END
1985 
1986 C2V_VMENTRY_NULL(jobject, getInterfaces, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1987   Klass* klass = UNPACK_PAIR(Klass, klass);
1988   if (klass == nullptr) {
1989     JVMCI_THROW_NULL(NullPointerException);
1990   }
1991 
1992   if (!klass->is_instance_klass()) {
1993     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
1994   }
1995   InstanceKlass* iklass = InstanceKlass::cast(klass);
1996 
1997   // Regular instance klass, fill in all local interfaces
1998   int size = iklass->local_interfaces()->length();
1999   JVMCIObjectArray interfaces = JVMCIENV->new_HotSpotResolvedObjectTypeImpl_array(size, JVMCI_CHECK_NULL);
2000   for (int index = 0; index < size; index++) {
2001     JVMCIKlassHandle klass(THREAD);
2002     Klass* k = iklass->local_interfaces()->at(index);
2003     klass = k;
2004     JVMCIObject type = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
2005     JVMCIENV->put_object_at(interfaces, index, type);
2006   }
2007   return JVMCIENV->get_jobject(interfaces);
2008 C2V_END
2009 
2010 C2V_VMENTRY_NULL(jobject, getComponentType, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2011   Klass* klass = UNPACK_PAIR(Klass, klass);
2012   if (klass == nullptr) {
2013     JVMCI_THROW_NULL(NullPointerException);
2014   }
2015 
2016   if (!klass->is_array_klass()) {
2017     return nullptr;
2018   }
2019   oop mirror = klass->java_mirror();
2020   oop component_mirror = java_lang_Class::component_mirror(mirror);
2021   if (component_mirror == nullptr) {
2022     JVMCI_THROW_MSG_NULL(NullPointerException,
2023                          err_msg("Component mirror for array class %s is null", klass->external_name()))
2024   }
2025 
2026   Klass* component_klass = java_lang_Class::as_Klass(component_mirror);
2027   if (component_klass != nullptr) {
2028     JVMCIKlassHandle klass_handle(THREAD, component_klass);
2029     JVMCIObject result = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2030     return JVMCIENV->get_jobject(result);
2031   }
2032   BasicType type = java_lang_Class::primitive_type(component_mirror);
2033   JVMCIObject result = JVMCIENV->get_jvmci_primitive_type(type);
2034   return JVMCIENV->get_jobject(result);
2035 C2V_END
2036 
2037 C2V_VMENTRY(void, ensureInitialized, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2038   Klass* klass = UNPACK_PAIR(Klass, klass);
2039   if (klass == nullptr) {
2040     JVMCI_THROW(NullPointerException);
2041   }
2042   if (klass->should_be_initialized()) {
2043     InstanceKlass* k = InstanceKlass::cast(klass);
2044     k->initialize(CHECK);
2045   }
2046 C2V_END
2047 
2048 C2V_VMENTRY(void, ensureLinked, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2049   CompilerThreadCanCallJava canCallJava(thread, true); // Linking requires Java calls
2050   Klass* klass = UNPACK_PAIR(Klass, klass);
2051   if (klass == nullptr) {
2052     JVMCI_THROW(NullPointerException);
2053   }
2054   if (klass->is_instance_klass()) {
2055     InstanceKlass* k = InstanceKlass::cast(klass);
2056     k->link_class(CHECK);
2057   }
2058 C2V_END
2059 
2060 C2V_VMENTRY_0(jint, interpreterFrameSize, (JNIEnv* env, jobject, jobject bytecode_frame_handle))
2061   if (bytecode_frame_handle == nullptr) {
2062     JVMCI_THROW_0(NullPointerException);
2063   }
2064 
2065   JVMCIObject top_bytecode_frame = JVMCIENV->wrap(bytecode_frame_handle);
2066   JVMCIObject bytecode_frame = top_bytecode_frame;
2067   int size = 0;
2068   int callee_parameters = 0;
2069   int callee_locals = 0;
2070   Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2071   int extra_args = method->max_stack() - JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2072 
2073   while (bytecode_frame.is_non_null()) {
2074     int locks = JVMCIENV->get_BytecodeFrame_numLocks(bytecode_frame);
2075     int temps = JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2076     bool is_top_frame = (JVMCIENV->equals(bytecode_frame, top_bytecode_frame));
2077     Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2078 
2079     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
2080                                                                  temps + callee_parameters,
2081                                                                  extra_args,
2082                                                                  locks,
2083                                                                  callee_parameters,
2084                                                                  callee_locals,
2085                                                                  is_top_frame);
2086     size += frame_size;
2087 
2088     callee_parameters = method->size_of_parameters();
2089     callee_locals = method->max_locals();
2090     extra_args = 0;
2091     bytecode_frame = JVMCIENV->get_BytecodePosition_caller(bytecode_frame);
2092   }
2093   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
2094 C2V_END
2095 
2096 C2V_VMENTRY(void, compileToBytecode, (JNIEnv* env, jobject, jobject lambda_form_handle))
2097   Handle lambda_form = JVMCIENV->asConstant(JVMCIENV->wrap(lambda_form_handle), JVMCI_CHECK);
2098   if (lambda_form->is_a(vmClasses::LambdaForm_klass())) {
2099     TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode");
2100     JavaValue result(T_VOID);
2101     JavaCalls::call_special(&result, lambda_form, vmClasses::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
2102   } else {
2103     JVMCI_THROW_MSG(IllegalArgumentException,
2104                     err_msg("Unexpected type: %s", lambda_form->klass()->external_name()))
2105   }
2106 C2V_END
2107 
2108 C2V_VMENTRY_0(jint, getIdentityHashCode, (JNIEnv* env, jobject, jobject object))
2109   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2110   return obj->identity_hash();
2111 C2V_END
2112 
2113 C2V_VMENTRY_0(jboolean, isInternedString, (JNIEnv* env, jobject, jobject object))
2114   Handle str = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2115   if (!java_lang_String::is_instance(str())) {
2116     return false;
2117   }
2118   int len;
2119   jchar* name = java_lang_String::as_unicode_string(str(), len, CHECK_false);
2120   return (StringTable::lookup(name, len) != nullptr);
2121 C2V_END
2122 
2123 
2124 C2V_VMENTRY_NULL(jobject, unboxPrimitive, (JNIEnv* env, jobject, jobject object))
2125   if (object == nullptr) {
2126     JVMCI_THROW_NULL(NullPointerException);
2127   }
2128   Handle box = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2129   BasicType type = java_lang_boxing_object::basic_type(box());
2130   jvalue result;
2131   if (java_lang_boxing_object::get_value(box(), &result) == T_ILLEGAL) {
2132     return nullptr;
2133   }
2134   JVMCIObject boxResult = JVMCIENV->create_box(type, &result, JVMCI_CHECK_NULL);
2135   return JVMCIENV->get_jobject(boxResult);
2136 C2V_END
2137 
2138 C2V_VMENTRY_NULL(jobject, boxPrimitive, (JNIEnv* env, jobject, jobject object))
2139   if (object == nullptr) {
2140     JVMCI_THROW_NULL(NullPointerException);
2141   }
2142   JVMCIObject box = JVMCIENV->wrap(object);
2143   BasicType type = JVMCIENV->get_box_type(box);
2144   if (type == T_ILLEGAL) {
2145     return nullptr;
2146   }
2147   jvalue value = JVMCIENV->get_boxed_value(type, box);
2148   JavaValue box_result(T_OBJECT);
2149   JavaCallArguments jargs;
2150   Klass* box_klass = nullptr;
2151   Symbol* box_signature = nullptr;
2152 #define BOX_CASE(bt, v, argtype, name)           \
2153   case bt: \
2154     jargs.push_##argtype(value.v); \
2155     box_klass = vmClasses::name##_klass(); \
2156     box_signature = vmSymbols::name##_valueOf_signature(); \
2157     break
2158 
2159   switch (type) {
2160     BOX_CASE(T_BOOLEAN, z, int, Boolean);
2161     BOX_CASE(T_BYTE, b, int, Byte);
2162     BOX_CASE(T_CHAR, c, int, Character);
2163     BOX_CASE(T_SHORT, s, int, Short);
2164     BOX_CASE(T_INT, i, int, Integer);
2165     BOX_CASE(T_LONG, j, long, Long);
2166     BOX_CASE(T_FLOAT, f, float, Float);
2167     BOX_CASE(T_DOUBLE, d, double, Double);
2168     default:
2169       ShouldNotReachHere();
2170   }
2171 #undef BOX_CASE
2172 
2173   JavaCalls::call_static(&box_result,
2174                          box_klass,
2175                          vmSymbols::valueOf_name(),
2176                          box_signature, &jargs, CHECK_NULL);
2177   oop hotspot_box = box_result.get_oop();
2178   JVMCIObject result = JVMCIENV->get_object_constant(hotspot_box, false);
2179   return JVMCIENV->get_jobject(result);
2180 C2V_END
2181 
2182 C2V_VMENTRY_NULL(jobjectArray, getDeclaredConstructors, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2183   Klass* klass = UNPACK_PAIR(Klass, klass);
2184   if (klass == nullptr) {
2185     JVMCI_THROW_NULL(NullPointerException);
2186   }
2187   if (!klass->is_instance_klass()) {
2188     JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2189     return JVMCIENV->get_jobjectArray(methods);
2190   }
2191 
2192   InstanceKlass* iklass = InstanceKlass::cast(klass);
2193   GrowableArray<Method*> constructors_array;
2194   for (int i = 0; i < iklass->methods()->length(); i++) {
2195     Method* m = iklass->methods()->at(i);
2196     if (m->is_object_initializer()) {
2197       constructors_array.append(m);
2198     }
2199   }
2200   JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(constructors_array.length(), JVMCI_CHECK_NULL);
2201   for (int i = 0; i < constructors_array.length(); i++) {
2202     methodHandle ctor(THREAD, constructors_array.at(i));
2203     JVMCIObject method = JVMCIENV->get_jvmci_method(ctor, JVMCI_CHECK_NULL);
2204     JVMCIENV->put_object_at(methods, i, method);
2205   }
2206   return JVMCIENV->get_jobjectArray(methods);
2207 C2V_END
2208 
2209 C2V_VMENTRY_NULL(jobjectArray, getDeclaredMethods, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2210   Klass* klass = UNPACK_PAIR(Klass, klass);
2211   if (klass == nullptr) {
2212     JVMCI_THROW_NULL(NullPointerException);
2213   }
2214   if (!klass->is_instance_klass()) {
2215     JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2216     return JVMCIENV->get_jobjectArray(methods);
2217   }
2218 
2219   InstanceKlass* iklass = InstanceKlass::cast(klass);
2220   GrowableArray<Method*> methods_array;
2221   for (int i = 0; i < iklass->methods()->length(); i++) {
2222     Method* m = iklass->methods()->at(i);
2223     if (!m->is_object_initializer() && !m->is_static_initializer() && !m->is_overpass()) {
2224       methods_array.append(m);
2225     }
2226   }
2227   JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(methods_array.length(), JVMCI_CHECK_NULL);
2228   for (int i = 0; i < methods_array.length(); i++) {
2229     methodHandle mh(THREAD, methods_array.at(i));
2230     JVMCIObject method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
2231     JVMCIENV->put_object_at(methods, i, method);
2232   }
2233   return JVMCIENV->get_jobjectArray(methods);
2234 C2V_END
2235 
2236 C2V_VMENTRY_NULL(jobjectArray, getAllMethods, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2237   Klass* klass = UNPACK_PAIR(Klass, klass);
2238   if (klass == nullptr) {
2239     JVMCI_THROW_NULL(NullPointerException);
2240   }
2241   if (!klass->is_instance_klass()) {
2242     JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2243     return JVMCIENV->get_jobjectArray(methods);
2244   }
2245 
2246   InstanceKlass* iklass = InstanceKlass::cast(klass);
2247   JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(iklass->methods()->length(), JVMCI_CHECK_NULL);
2248   for (int i = 0; i < iklass->methods()->length(); i++) {
2249     methodHandle mh(THREAD, iklass->methods()->at(i));
2250     JVMCIObject method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
2251     JVMCIENV->put_object_at(methods, i, method);
2252   }
2253   return JVMCIENV->get_jobjectArray(methods);
2254 C2V_END
2255 
2256 C2V_VMENTRY_NULL(jobjectArray, getDeclaredFieldsInfo, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2257   Klass* klass = UNPACK_PAIR(Klass, klass);
2258   if (klass == nullptr) {
2259     JVMCI_THROW_NULL(NullPointerException);
2260   }
2261   if (!klass->is_instance_klass()) {
2262     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "not an InstanceKlass");
2263   }
2264   InstanceKlass* iklass = InstanceKlass::cast(klass);
2265   int java_fields, injected_fields;
2266   GrowableArray<FieldInfo>* fields = FieldInfoStream::create_FieldInfoArray(iklass->fieldinfo_stream(), &java_fields, &injected_fields);
2267   JVMCIObjectArray array = JVMCIENV->new_FieldInfo_array(fields->length(), JVMCIENV);
2268   for (int i = 0; i < fields->length(); i++) {
2269     JVMCIObject field_info = JVMCIENV->new_FieldInfo(fields->adr_at(i), JVMCI_CHECK_NULL);
2270     JVMCIENV->put_object_at(array, i, field_info);
2271   }
2272   return array.as_jobject();
2273 C2V_END
2274 
2275 static jobject read_field_value(Handle obj, long displacement, jchar type_char, bool is_static, Thread* THREAD, JVMCIEnv* JVMCIENV) {
2276 
2277   BasicType basic_type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_NULL);
2278   int basic_type_elemsize = type2aelembytes(basic_type);
2279   if (displacement < 0 || ((size_t) displacement + basic_type_elemsize > HeapWordSize * obj->size())) {
2280     // Reading outside of the object bounds
2281     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading outside object bounds");
2282   }
2283 
2284   // Perform basic sanity checks on the read.  Primitive reads are permitted to read outside the
2285   // bounds of their fields but object reads must map exactly onto the underlying oop slot.
2286   bool aligned = (displacement % basic_type_elemsize) == 0;
2287   if (!aligned) {
2288     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "read is unaligned");
2289   }
2290   if (obj->is_array()) {
2291     // Disallow reading after the last element of an array
2292     size_t array_length = arrayOop(obj())->length();
2293     int lh = obj->klass()->layout_helper();
2294     size_t size_in_bytes = array_length << Klass::layout_helper_log2_element_size(lh);
2295     size_in_bytes += Klass::layout_helper_header_size(lh);
2296     if ((size_t) displacement + basic_type_elemsize > size_in_bytes) {
2297       JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading after last array element");
2298     }
2299   }
2300   if (basic_type == T_OBJECT) {
2301     if (obj->is_objArray()) {
2302       if (displacement < arrayOopDesc::base_offset_in_bytes(T_OBJECT)) {
2303         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2304       }
2305       if (((displacement - arrayOopDesc::base_offset_in_bytes(T_OBJECT)) % heapOopSize) != 0) {
2306         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "misaligned object read from array");
2307       }
2308     } else if (obj->is_instance()) {
2309       InstanceKlass* klass = InstanceKlass::cast(is_static ? java_lang_Class::as_Klass(obj()) : obj->klass());
2310       fieldDescriptor fd;
2311       if (!klass->find_field_from_offset(displacement, is_static, &fd)) {
2312         JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Can't find field at displacement %d in object of type %s", (int) displacement, klass->external_name()));
2313       }
2314       if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
2315         JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Field at displacement %d in object of type %s is %s but expected %s", (int) displacement,
2316                                                                klass->external_name(), type2name(fd.field_type()), type2name(basic_type)));
2317       }
2318     } else if (obj->is_typeArray()) {
2319       JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Can't read objects from primitive array");
2320     } else {
2321       ShouldNotReachHere();
2322     }
2323   } else {
2324     if (obj->is_objArray()) {
2325       JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Reading primitive from object array");
2326     } else if (obj->is_typeArray()) {
2327       if (displacement < arrayOopDesc::base_offset_in_bytes(ArrayKlass::cast(obj->klass())->element_type())) {
2328         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2329       }
2330     }
2331   }
2332 
2333   jlong value = 0;
2334 
2335   // Treat all reads as volatile for simplicity as this function can be used
2336   // both for reading Java fields declared as volatile as well as for constant
2337   // folding Unsafe.get* methods with volatile semantics.
2338 
2339   switch (basic_type) {
2340     case T_BOOLEAN: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jboolean>(displacement)); break;
2341     case T_BYTE:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jbyte>(displacement));    break;
2342     case T_SHORT:   value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jshort>(displacement));   break;
2343     case T_CHAR:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jchar>(displacement));    break;
2344     case T_FLOAT:
2345     case T_INT:     value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jint>(displacement));     break;
2346     case T_DOUBLE:
2347     case T_LONG:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jlong>(displacement));    break;
2348 
2349     case T_OBJECT: {
2350       if (displacement == java_lang_Class::component_mirror_offset() && java_lang_Class::is_instance(obj()) &&
2351           (java_lang_Class::as_Klass(obj()) == nullptr || !java_lang_Class::as_Klass(obj())->is_array_klass())) {
2352         // Class.componentType for non-array classes can transiently contain an int[] that's
2353         // used for locking so always return null to mimic Class.getComponentType()
2354         return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2355       }
2356 
2357       // Perform the read including any barriers required to make the reference strongly reachable
2358       // since it will be wrapped as a JavaConstant.
2359       oop value = obj->obj_field_access<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>(displacement);
2360 
2361       if (value == nullptr) {
2362         return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2363       } else {
2364         if (value != nullptr && !oopDesc::is_oop(value)) {
2365           // Throw an exception to improve debuggability.  This check isn't totally reliable because
2366           // is_oop doesn't try to be completety safe but for most invalid values it provides a good
2367           // enough answer.  It possible to crash in the is_oop call but that just means the crash happens
2368           // closer to where things went wrong.
2369           JVMCI_THROW_MSG_NULL(InternalError, err_msg("Read bad oop " INTPTR_FORMAT " at offset " JLONG_FORMAT " in object " INTPTR_FORMAT " of type %s",
2370                                                       p2i(value), displacement, p2i(obj()), obj->klass()->external_name()));
2371         }
2372 
2373         JVMCIObject result = JVMCIENV->get_object_constant(value);
2374         return JVMCIENV->get_jobject(result);
2375       }
2376     }
2377 
2378     default:
2379       ShouldNotReachHere();
2380   }
2381   JVMCIObject result = JVMCIENV->call_JavaConstant_forPrimitive(type_char, value, JVMCI_CHECK_NULL);
2382   return JVMCIENV->get_jobject(result);
2383 }
2384 
2385 C2V_VMENTRY_NULL(jobject, readStaticFieldValue, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), long displacement, jchar type_char))
2386   Klass* klass = UNPACK_PAIR(Klass, klass);
2387   Handle obj(THREAD, klass->java_mirror());
2388   return read_field_value(obj, displacement, type_char, true, THREAD, JVMCIENV);
2389 C2V_END
2390 
2391 C2V_VMENTRY_NULL(jobject, readFieldValue, (JNIEnv* env, jobject, jobject object, ARGUMENT_PAIR(expected_type), long displacement, jchar type_char))
2392   if (object == nullptr) {
2393     JVMCI_THROW_NULL(NullPointerException);
2394   }
2395 
2396   // asConstant will throw an NPE if a constant contains null
2397   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2398 
2399   Klass* expected_klass = UNPACK_PAIR(Klass, expected_type);
2400   if (expected_klass != nullptr) {
2401     InstanceKlass* expected_iklass = InstanceKlass::cast(expected_klass);
2402     if (!obj->is_a(expected_iklass)) {
2403       // Not of the expected type
2404       return nullptr;
2405     }
2406   }
2407   bool is_static = expected_klass == nullptr && java_lang_Class::is_instance(obj()) && displacement >= InstanceMirrorKlass::offset_of_static_fields();
2408   return read_field_value(obj, displacement, type_char, is_static, THREAD, JVMCIENV);
2409 C2V_END
2410 
2411 C2V_VMENTRY_0(jboolean, isInstance, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jobject object))
2412   Klass* klass = UNPACK_PAIR(Klass, klass);
2413   if (object == nullptr || klass == nullptr) {
2414     JVMCI_THROW_0(NullPointerException);
2415   }
2416   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2417   return obj->is_a(klass);
2418 C2V_END
2419 
2420 C2V_VMENTRY_0(jboolean, isAssignableFrom, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(subklass)))
2421   Klass* klass = UNPACK_PAIR(Klass, klass);
2422   Klass* subklass = UNPACK_PAIR(Klass, subklass);
2423   if (klass == nullptr || subklass == nullptr) {
2424     JVMCI_THROW_0(NullPointerException);
2425   }
2426   return subklass->is_subtype_of(klass);
2427 C2V_END
2428 
2429 C2V_VMENTRY_0(jboolean, isTrustedForIntrinsics, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2430   Klass* klass = UNPACK_PAIR(Klass, klass);
2431   if (klass == nullptr) {
2432     JVMCI_THROW_0(NullPointerException);
2433   }
2434   InstanceKlass* ik = InstanceKlass::cast(klass);
2435   if (ik->class_loader_data()->is_boot_class_loader_data() || ik->class_loader_data()->is_platform_class_loader_data()) {
2436     return true;
2437   }
2438   return false;
2439 C2V_END
2440 
2441 C2V_VMENTRY_NULL(jobject, asJavaType, (JNIEnv* env, jobject, jobject object))
2442   if (object == nullptr) {
2443     JVMCI_THROW_NULL(NullPointerException);
2444   }
2445   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2446   if (java_lang_Class::is_instance(obj())) {
2447     if (java_lang_Class::is_primitive(obj())) {
2448       JVMCIObject type = JVMCIENV->get_jvmci_primitive_type(java_lang_Class::primitive_type(obj()));
2449       return JVMCIENV->get_jobject(type);
2450     }
2451     Klass* klass = java_lang_Class::as_Klass(obj());
2452     JVMCIKlassHandle klass_handle(THREAD);
2453     klass_handle = klass;
2454     JVMCIObject type = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2455     return JVMCIENV->get_jobject(type);
2456   }
2457   return nullptr;
2458 C2V_END
2459 
2460 
2461 C2V_VMENTRY_NULL(jobject, asString, (JNIEnv* env, jobject, jobject object))
2462   if (object == nullptr) {
2463     JVMCI_THROW_NULL(NullPointerException);
2464   }
2465   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2466   const char* str = java_lang_String::as_utf8_string(obj());
2467   JVMCIObject result = JVMCIENV->create_string(str, JVMCI_CHECK_NULL);
2468   return JVMCIENV->get_jobject(result);
2469 C2V_END
2470 
2471 
2472 C2V_VMENTRY_0(jboolean, equals, (JNIEnv* env, jobject, jobject x, jlong xHandle, jobject y, jlong yHandle))
2473   if (x == nullptr || y == nullptr) {
2474     JVMCI_THROW_0(NullPointerException);
2475   }
2476   return JVMCIENV->resolve_oop_handle(xHandle) == JVMCIENV->resolve_oop_handle(yHandle);
2477 C2V_END
2478 
2479 C2V_VMENTRY_NULL(jobject, getJavaMirror, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2480   Klass* klass = UNPACK_PAIR(Klass, klass);
2481   if (klass == nullptr) {
2482     JVMCI_THROW_NULL(NullPointerException);
2483   }
2484   Handle mirror(THREAD, klass->java_mirror());
2485   JVMCIObject result = JVMCIENV->get_object_constant(mirror());
2486   return JVMCIENV->get_jobject(result);
2487 C2V_END
2488 
2489 
2490 C2V_VMENTRY_0(jint, getArrayLength, (JNIEnv* env, jobject, jobject x))
2491   if (x == nullptr) {
2492     JVMCI_THROW_0(NullPointerException);
2493   }
2494   Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
2495   if (xobj->klass()->is_array_klass()) {
2496     return arrayOop(xobj())->length();
2497   }
2498   return -1;
2499  C2V_END
2500 
2501 
2502 C2V_VMENTRY_NULL(jobject, readArrayElement, (JNIEnv* env, jobject, jobject x, int index))
2503   if (x == nullptr) {
2504     JVMCI_THROW_NULL(NullPointerException);
2505   }
2506   Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_NULL);
2507   if (xobj->klass()->is_array_klass()) {
2508     arrayOop array = arrayOop(xobj());
2509     BasicType element_type = ArrayKlass::cast(array->klass())->element_type();
2510     if (index < 0 || index >= array->length()) {
2511       return nullptr;
2512     }
2513     JVMCIObject result;
2514 
2515     if (element_type == T_OBJECT) {
2516       result = JVMCIENV->get_object_constant(objArrayOop(xobj())->obj_at(index));
2517       if (result.is_null()) {
2518         result = JVMCIENV->get_JavaConstant_NULL_POINTER();
2519       }
2520     } else {
2521       jvalue value;
2522       switch (element_type) {
2523         case T_DOUBLE:        value.d = typeArrayOop(xobj())->double_at(index);        break;
2524         case T_FLOAT:         value.f = typeArrayOop(xobj())->float_at(index);         break;
2525         case T_LONG:          value.j = typeArrayOop(xobj())->long_at(index);          break;
2526         case T_INT:           value.i = typeArrayOop(xobj())->int_at(index);            break;
2527         case T_SHORT:         value.s = typeArrayOop(xobj())->short_at(index);          break;
2528         case T_CHAR:          value.c = typeArrayOop(xobj())->char_at(index);           break;
2529         case T_BYTE:          value.b = typeArrayOop(xobj())->byte_at(index);           break;
2530         case T_BOOLEAN:       value.z = typeArrayOop(xobj())->byte_at(index) & 1;       break;
2531         default:              ShouldNotReachHere();
2532       }
2533       result = JVMCIENV->create_box(element_type, &value, JVMCI_CHECK_NULL);
2534     }
2535     assert(!result.is_null(), "must have a value");
2536     return JVMCIENV->get_jobject(result);
2537   }
2538   return nullptr;;
2539 C2V_END
2540 
2541 
2542 C2V_VMENTRY_0(jint, arrayBaseOffset, (JNIEnv* env, jobject, jchar type_char))
2543   BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2544   return arrayOopDesc::base_offset_in_bytes(type);
2545 C2V_END
2546 
2547 C2V_VMENTRY_0(jint, arrayIndexScale, (JNIEnv* env, jobject, jchar type_char))
2548   BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2549   return type2aelembytes(type);
2550 C2V_END
2551 
2552 C2V_VMENTRY(void, clearOopHandle, (JNIEnv* env, jobject, jlong oop_handle))
2553   if (oop_handle == 0L) {
2554     JVMCI_THROW(NullPointerException);
2555   }
2556   // Assert before nulling out, for better debugging.
2557   assert(JVMCIRuntime::is_oop_handle(oop_handle), "precondition");
2558   oop* oop_ptr = (oop*) oop_handle;
2559   NativeAccess<>::oop_store(oop_ptr, (oop) nullptr);
2560 C2V_END
2561 
2562 C2V_VMENTRY(void, releaseClearedOopHandles, (JNIEnv* env, jobject))
2563   JVMCIENV->runtime()->release_cleared_oop_handles();
2564 C2V_END
2565 
2566 static void requireJVMCINativeLibrary(JVMCI_TRAPS) {
2567   if (!UseJVMCINativeLibrary) {
2568     JVMCI_THROW_MSG(UnsupportedOperationException, "JVMCI shared library is not enabled (requires -XX:+UseJVMCINativeLibrary)");
2569   }
2570 }
2571 
2572 C2V_VMENTRY_NULL(jlongArray, registerNativeMethods, (JNIEnv* env, jobject, jclass mirror))
2573   requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2574   requireInHotSpot("registerNativeMethods", JVMCI_CHECK_NULL);
2575   char* sl_path;
2576   void* sl_handle;
2577   JVMCIRuntime* runtime;
2578   {
2579     // Ensure the JVMCI shared library runtime is initialized.
2580     PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2581     PEER_JVMCIENV->check_init(JVMCI_CHECK_NULL);
2582 
2583     HandleMark hm(THREAD);
2584     runtime = JVMCI::compiler_runtime(thread);
2585     if (PEER_JVMCIENV->has_pending_exception()) {
2586       PEER_JVMCIENV->describe_pending_exception(tty);
2587     }
2588     sl_handle = JVMCI::get_shared_library(sl_path, false);
2589     if (sl_handle == nullptr) {
2590       JVMCI_THROW_MSG_NULL(InternalError, err_msg("Error initializing JVMCI runtime %d", runtime->id()));
2591     }
2592   }
2593 
2594   if (mirror == nullptr) {
2595     JVMCI_THROW_NULL(NullPointerException);
2596   }
2597   Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2598   if (klass == nullptr || !klass->is_instance_klass()) {
2599     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "clazz is for primitive type");
2600   }
2601 
2602   InstanceKlass* iklass = InstanceKlass::cast(klass);
2603   for (int i = 0; i < iklass->methods()->length(); i++) {
2604     methodHandle method(THREAD, iklass->methods()->at(i));
2605     if (method->is_native()) {
2606 
2607       // Compute argument size
2608       int args_size = 1                             // JNIEnv
2609                     + (method->is_static() ? 1 : 0) // class for static methods
2610                     + method->size_of_parameters(); // actual parameters
2611 
2612       // 1) Try JNI short style
2613       stringStream st;
2614       char* pure_name = NativeLookup::pure_jni_name(method);
2615       guarantee(pure_name != nullptr, "Illegal native method name encountered");
2616       st.print_raw(pure_name);
2617       char* jni_name = st.as_string();
2618 
2619       address entry = (address) os::dll_lookup(sl_handle, jni_name);
2620       if (entry == nullptr) {
2621         // 2) Try JNI long style
2622         st.reset();
2623         char* long_name = NativeLookup::long_jni_name(method);
2624         guarantee(long_name != nullptr, "Illegal native method name encountered");
2625         st.print_raw(pure_name);
2626         st.print_raw(long_name);
2627         char* jni_long_name = st.as_string();
2628         entry = (address) os::dll_lookup(sl_handle, jni_long_name);
2629         if (entry == nullptr) {
2630           JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [neither %s nor %s exist in %s]",
2631               method->name_and_sig_as_C_string(),
2632               jni_name, jni_long_name, sl_path));
2633         }
2634       }
2635 
2636       if (method->has_native_function() && entry != method->native_function()) {
2637         JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [cannot re-link from " PTR_FORMAT " to " PTR_FORMAT "]",
2638             method->name_and_sig_as_C_string(), p2i(method->native_function()), p2i(entry)));
2639       }
2640       method->set_native_function(entry, Method::native_bind_event_is_interesting);
2641       log_debug(jni, resolve)("[Dynamic-linking native method %s.%s ... JNI] @ " PTR_FORMAT,
2642                               method->method_holder()->external_name(),
2643                               method->name()->as_C_string(),
2644                               p2i((void*) entry));
2645     }
2646   }
2647 
2648   typeArrayOop info_oop = oopFactory::new_longArray(4, CHECK_NULL);
2649   jlongArray info = (jlongArray) JNIHandles::make_local(THREAD, info_oop);
2650   runtime->init_JavaVM_info(info, JVMCI_CHECK_NULL);
2651   return info;
2652 C2V_END
2653 
2654 C2V_VMENTRY_PREFIX(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject c2vm))
2655   if (thread == nullptr || thread->libjvmci_runtime() == nullptr) {
2656     // Called from unattached JVMCI shared library thread
2657     return false;
2658   }
2659   if (thread->jni_environment() == env) {
2660     C2V_BLOCK(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject))
2661     JVMCITraceMark jtm("isCurrentThreadAttached");
2662     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2663     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2664     if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2665       JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in isCurrentThreadAttached");
2666     }
2667     JNIEnv* peerEnv;
2668     return runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) == JNI_OK;
2669   }
2670   return true;
2671 C2V_END
2672 
2673 C2V_VMENTRY_PREFIX(jlong, getCurrentJavaThread, (JNIEnv* env, jobject c2vm))
2674   if (thread == nullptr) {
2675     // Called from unattached JVMCI shared library thread
2676     return 0L;
2677   }
2678   return (jlong) p2i(thread);
2679 C2V_END
2680 
2681 // Attaches a thread started in a JVMCI shared library to a JavaThread and JVMCI runtime.
2682 static void attachSharedLibraryThread(JNIEnv* env, jbyteArray name, jboolean as_daemon) {
2683   JavaVM* javaVM = nullptr;
2684   jint res = env->GetJavaVM(&javaVM);
2685   if (res != JNI_OK) {
2686     JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Error getting shared library JavaVM from shared library JNIEnv: %d", res));
2687   }
2688   extern struct JavaVM_ main_vm;
2689   JNIEnv* hotspotEnv;
2690 
2691   int name_len = env->GetArrayLength(name);
2692   char name_buf[64]; // Cannot use Resource heap as it requires a current thread
2693   int to_copy = MIN2(name_len, (int) sizeof(name_buf) - 1);
2694   env->GetByteArrayRegion(name, 0, to_copy, (jbyte*) name_buf);
2695   name_buf[to_copy] = '\0';
2696   JavaVMAttachArgs attach_args;
2697   attach_args.version = JNI_VERSION_1_2;
2698   attach_args.name = name_buf;
2699   attach_args.group = nullptr;
2700   res = as_daemon ? main_vm.AttachCurrentThreadAsDaemon((void**)&hotspotEnv, &attach_args) :
2701                     main_vm.AttachCurrentThread((void**)&hotspotEnv, &attach_args);
2702   if (res != JNI_OK) {
2703     JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Trying to attach thread returned %d", res));
2704   }
2705   JavaThread* thread = JavaThread::thread_from_jni_environment(hotspotEnv);
2706   const char* attach_error;
2707   {
2708     // Transition to VM
2709     JVMCI_VM_ENTRY_MARK
2710     attach_error = JVMCIRuntime::attach_shared_library_thread(thread, javaVM);
2711     // Transition back to Native
2712   }
2713   if (attach_error != nullptr) {
2714     JNI_THROW("attachCurrentThread", InternalError, attach_error);
2715   }
2716 }
2717 
2718 C2V_VMENTRY_PREFIX(jboolean, attachCurrentThread, (JNIEnv* env, jobject c2vm, jbyteArray name, jboolean as_daemon, jlongArray javaVM_info))
2719   if (thread == nullptr) {
2720     attachSharedLibraryThread(env, name, as_daemon);
2721     return true;
2722   }
2723   if (thread->jni_environment() == env) {
2724     // Called from HotSpot
2725     C2V_BLOCK(jboolean, attachCurrentThread, (JNIEnv* env, jobject, jboolean))
2726     JVMCITraceMark jtm("attachCurrentThread");
2727     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2728 
2729     JVMCIRuntime* runtime = JVMCI::compiler_runtime(thread);
2730     JNIEnv* peerJNIEnv;
2731     if (runtime->has_shared_library_javavm()) {
2732       if (runtime->GetEnv(thread, (void**)&peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2733         // Already attached
2734         runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2735         return false;
2736       }
2737     }
2738 
2739     {
2740       // Ensure the JVMCI shared library runtime is initialized.
2741       PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2742       PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2743 
2744       HandleMark hm(thread);
2745       JVMCIObject receiver = runtime->get_HotSpotJVMCIRuntime(PEER_JVMCIENV);
2746       if (PEER_JVMCIENV->has_pending_exception()) {
2747         PEER_JVMCIENV->describe_pending_exception(tty);
2748       }
2749       char* sl_path;
2750       if (JVMCI::get_shared_library(sl_path, false) == nullptr) {
2751         JVMCI_THROW_MSG_0(InternalError, "Error initializing JVMCI runtime");
2752       }
2753     }
2754 
2755     JavaVMAttachArgs attach_args;
2756     attach_args.version = JNI_VERSION_1_2;
2757     attach_args.name = const_cast<char*>(thread->name());
2758     attach_args.group = nullptr;
2759     if (runtime->GetEnv(thread, (void**) &peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2760       return false;
2761     }
2762     jint res = as_daemon ? runtime->AttachCurrentThreadAsDaemon(thread, (void**) &peerJNIEnv, &attach_args) :
2763                            runtime->AttachCurrentThread(thread, (void**) &peerJNIEnv, &attach_args);
2764 
2765     if (res == JNI_OK) {
2766       guarantee(peerJNIEnv != nullptr, "must be");
2767       runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2768       JVMCI_event_1("attached to JavaVM[" JLONG_FORMAT "] for JVMCI runtime %d", runtime->get_shared_library_javavm_id(), runtime->id());
2769       return true;
2770     }
2771     JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, attach_args.name));
2772   }
2773   // Called from JVMCI shared library
2774   return false;
2775 C2V_END
2776 
2777 C2V_VMENTRY_PREFIX(jboolean, detachCurrentThread, (JNIEnv* env, jobject c2vm, jboolean release))
2778   if (thread == nullptr) {
2779     // Called from unattached JVMCI shared library thread
2780     JNI_THROW_("detachCurrentThread", IllegalStateException, "Cannot detach non-attached thread", false);
2781   }
2782   if (thread->jni_environment() == env) {
2783     // Called from HotSpot
2784     C2V_BLOCK(void, detachCurrentThread, (JNIEnv* env, jobject))
2785     JVMCITraceMark jtm("detachCurrentThread");
2786     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2787     requireInHotSpot("detachCurrentThread", JVMCI_CHECK_0);
2788     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2789     if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2790       JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in detachCurrentThread");
2791     }
2792     JNIEnv* peerEnv;
2793 
2794     if (runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) != JNI_OK) {
2795       JVMCI_THROW_MSG_0(IllegalStateException, err_msg("Cannot detach non-attached thread: %s", thread->name()));
2796     }
2797     jint res = runtime->DetachCurrentThread(thread);
2798     if (res != JNI_OK) {
2799       JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, thread->name()));
2800     }
2801     JVMCI_event_1("detached from JavaVM[" JLONG_FORMAT "] for JVMCI runtime %d",
2802         runtime->get_shared_library_javavm_id(), runtime->id());
2803     if (release) {
2804       return runtime->detach_thread(thread, "user thread detach");
2805     }
2806   } else {
2807     // Called from attached JVMCI shared library thread
2808     if (release) {
2809       JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread cannot release JVMCI shared library JavaVM", false);
2810     }
2811     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2812     if (runtime == nullptr) {
2813       JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread should have a JVMCI runtime", false);
2814     }
2815     {
2816       // Transition to VM
2817       C2V_BLOCK(jboolean, detachCurrentThread, (JNIEnv* env, jobject))
2818       // Cannot destroy shared library JavaVM as we're about to return to it.
2819       runtime->detach_thread(thread, "shared library thread detach", false);
2820       JVMCI_event_1("detaching JVMCI shared library thread from HotSpot JavaVM");
2821       // Transition back to Native
2822     }
2823     extern struct JavaVM_ main_vm;
2824     jint res = main_vm.DetachCurrentThread();
2825     if (res != JNI_OK) {
2826       JNI_THROW_("detachCurrentThread", InternalError, "Cannot detach non-attached thread", false);
2827     }
2828   }
2829   return false;
2830 C2V_END
2831 
2832 C2V_VMENTRY_0(jlong, translate, (JNIEnv* env, jobject, jobject obj_handle, jboolean callPostTranslation))
2833   requireJVMCINativeLibrary(JVMCI_CHECK_0);
2834   if (obj_handle == nullptr) {
2835     return 0L;
2836   }
2837   PEER_JVMCIENV_FROM_THREAD(THREAD, !JVMCIENV->is_hotspot());
2838   CompilerThreadCanCallJava canCallJava(thread, PEER_JVMCIENV->is_hotspot());
2839   PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2840 
2841   JVMCIEnv* thisEnv = JVMCIENV;
2842   JVMCIObject obj = thisEnv->wrap(obj_handle);
2843   JVMCIObject result;
2844   if (thisEnv->isa_HotSpotResolvedJavaMethodImpl(obj)) {
2845     methodHandle method(THREAD, thisEnv->asMethod(obj));
2846     result = PEER_JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_0);
2847   } else if (thisEnv->isa_HotSpotResolvedObjectTypeImpl(obj)) {
2848     Klass* klass = thisEnv->asKlass(obj);
2849     JVMCIKlassHandle klass_handle(THREAD);
2850     klass_handle = klass;
2851     result = PEER_JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_0);
2852   } else if (thisEnv->isa_HotSpotResolvedPrimitiveType(obj)) {
2853     BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(obj), JVMCI_CHECK_0);
2854     result = PEER_JVMCIENV->get_jvmci_primitive_type(type);
2855   } else if (thisEnv->isa_IndirectHotSpotObjectConstantImpl(obj) ||
2856              thisEnv->isa_DirectHotSpotObjectConstantImpl(obj)) {
2857     Handle constant = thisEnv->asConstant(obj, JVMCI_CHECK_0);
2858     result = PEER_JVMCIENV->get_object_constant(constant());
2859   } else if (thisEnv->isa_HotSpotNmethod(obj)) {
2860     if (PEER_JVMCIENV->is_hotspot()) {
2861       JVMCINMethodHandle nmethod_handle(THREAD);
2862       nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2863       if (nm != nullptr) {
2864         JVMCINMethodData* data = nm->jvmci_nmethod_data();
2865         if (data != nullptr) {
2866           // Only the mirror in the HotSpot heap is accessible
2867           // through JVMCINMethodData
2868           oop nmethod_mirror = data->get_nmethod_mirror(nm);
2869           if (nmethod_mirror != nullptr) {
2870             result = HotSpotJVMCI::wrap(nmethod_mirror);
2871           }
2872         }
2873       }
2874     }
2875 
2876     if (result.is_null()) {
2877       JVMCIObject methodObject = thisEnv->get_HotSpotNmethod_method(obj);
2878       methodHandle mh(THREAD, thisEnv->asMethod(methodObject));
2879       jboolean isDefault = thisEnv->get_HotSpotNmethod_isDefault(obj);
2880       jlong compileIdSnapshot = thisEnv->get_HotSpotNmethod_compileIdSnapshot(obj);
2881       JVMCIObject name_string = thisEnv->get_InstalledCode_name(obj);
2882       const char* cstring = name_string.is_null() ? nullptr : thisEnv->as_utf8_string(name_string);
2883       // Create a new HotSpotNmethod instance in the peer runtime
2884       result = PEER_JVMCIENV->new_HotSpotNmethod(mh, cstring, isDefault, compileIdSnapshot, JVMCI_CHECK_0);
2885       JVMCINMethodHandle nmethod_handle(THREAD);
2886       nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2887       if (result.is_null()) {
2888         // exception occurred (e.g. OOME) creating a new HotSpotNmethod
2889       } else if (nm == nullptr) {
2890         // nmethod must have been unloaded
2891       } else {
2892         // Link the new HotSpotNmethod to the nmethod
2893         PEER_JVMCIENV->initialize_installed_code(result, nm, JVMCI_CHECK_0);
2894         // Only non-default HotSpotNmethod instances in the HotSpot heap are tracked directly by the runtime.
2895         if (!isDefault && PEER_JVMCIENV->is_hotspot()) {
2896           JVMCINMethodData* data = nm->jvmci_nmethod_data();
2897           if (data == nullptr) {
2898             JVMCI_THROW_MSG_0(IllegalArgumentException, "Missing HotSpotNmethod data");
2899           }
2900           if (data->get_nmethod_mirror(nm) != nullptr) {
2901             JVMCI_THROW_MSG_0(IllegalArgumentException, "Cannot overwrite existing HotSpotNmethod mirror for nmethod");
2902           }
2903           oop nmethod_mirror = HotSpotJVMCI::resolve(result);
2904           data->set_nmethod_mirror(nm, nmethod_mirror);
2905         }
2906       }
2907     }
2908   } else {
2909     JVMCI_THROW_MSG_0(IllegalArgumentException,
2910                 err_msg("Cannot translate object of type: %s", thisEnv->klass_name(obj)));
2911   }
2912   if (callPostTranslation) {
2913     PEER_JVMCIENV->call_HotSpotJVMCIRuntime_postTranslation(result, JVMCI_CHECK_0);
2914   }
2915   // Propagate any exception that occurred while creating the translated object
2916   if (PEER_JVMCIENV->transfer_pending_exception(thread, thisEnv)) {
2917     return 0L;
2918   }
2919   return (jlong) PEER_JVMCIENV->make_global(result).as_jobject();
2920 C2V_END
2921 
2922 C2V_VMENTRY_NULL(jobject, unhand, (JNIEnv* env, jobject, jlong obj_handle))
2923   requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2924   if (obj_handle == 0L) {
2925     return nullptr;
2926   }
2927   jobject global_handle = (jobject) obj_handle;
2928   JVMCIObject global_handle_obj = JVMCIENV->wrap(global_handle);
2929   jobject result = JVMCIENV->make_local(global_handle_obj).as_jobject();
2930 
2931   JVMCIENV->destroy_global(global_handle_obj);
2932   return result;
2933 C2V_END
2934 
2935 C2V_VMENTRY(void, updateHotSpotNmethod, (JNIEnv* env, jobject, jobject code_handle))
2936   JVMCIObject code = JVMCIENV->wrap(code_handle);
2937   // Execute this operation for the side effect of updating the InstalledCode state
2938   JVMCINMethodHandle nmethod_handle(THREAD);
2939   JVMCIENV->get_nmethod(code, nmethod_handle);
2940 C2V_END
2941 
2942 C2V_VMENTRY_NULL(jbyteArray, getCode, (JNIEnv* env, jobject, jobject code_handle))
2943   JVMCIObject code = JVMCIENV->wrap(code_handle);
2944   CodeBlob* cb = JVMCIENV->get_code_blob(code);
2945   if (cb == nullptr) {
2946     return nullptr;
2947   }
2948   // Make a resource copy of code before the allocation causes a safepoint
2949   int code_size = cb->code_size();
2950   jbyte* code_bytes = NEW_RESOURCE_ARRAY(jbyte, code_size);
2951   memcpy(code_bytes, (jbyte*) cb->code_begin(), code_size);
2952 
2953   JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
2954   JVMCIENV->copy_bytes_from(code_bytes, result, 0, code_size);
2955   return JVMCIENV->get_jbyteArray(result);
2956 C2V_END
2957 
2958 C2V_VMENTRY_NULL(jobject, asReflectionExecutable, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
2959   requireInHotSpot("asReflectionExecutable", JVMCI_CHECK_NULL);
2960   methodHandle m(THREAD, UNPACK_PAIR(Method, method));
2961   oop executable;
2962   if (m->is_object_initializer()) {
2963     executable = Reflection::new_constructor(m, CHECK_NULL);
2964   } else if (m->is_static_initializer()) {
2965     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2966         "Cannot create java.lang.reflect.Method for class initializer");
2967   } else {
2968     executable = Reflection::new_method(m, false, CHECK_NULL);
2969   }
2970   return JNIHandles::make_local(THREAD, executable);
2971 C2V_END
2972 
2973 static InstanceKlass* check_field(Klass* klass, jint index, JVMCI_TRAPS) {
2974   if (!klass->is_instance_klass()) {
2975     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2976         err_msg("Expected non-primitive type, got %s", klass->external_name()));
2977   }
2978   InstanceKlass* iklass = InstanceKlass::cast(klass);
2979   if (index < 0 || index > iklass->total_fields_count()) {
2980     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2981         err_msg("Field index %d out of bounds for %s", index, klass->external_name()));
2982   }
2983   return iklass;
2984 }
2985 
2986 C2V_VMENTRY_NULL(jobject, asReflectionField, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index))
2987   requireInHotSpot("asReflectionField", JVMCI_CHECK_NULL);
2988   Klass* klass = UNPACK_PAIR(Klass, klass);
2989   InstanceKlass* iklass = check_field(klass, index, JVMCIENV);
2990   fieldDescriptor fd(iklass, index);
2991   oop reflected = Reflection::new_field(&fd, CHECK_NULL);
2992   return JNIHandles::make_local(THREAD, reflected);
2993 C2V_END
2994 
2995 static jbyteArray get_encoded_annotation_data(InstanceKlass* holder, AnnotationArray* annotations_array, bool for_class,
2996                                               jint filter_length, jlong filter_klass_pointers,
2997                                               JavaThread* THREAD, JVMCIEnv* JVMCIENV) {
2998   // Get a ConstantPool object for annotation parsing
2999   Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
3000   reflect_ConstantPool::set_cp(jcp(), holder->constants());
3001 
3002   // load VMSupport
3003   Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
3004   Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK_NULL);
3005 
3006   InstanceKlass* vm_support = InstanceKlass::cast(k);
3007   if (vm_support->should_be_initialized()) {
3008     vm_support->initialize(CHECK_NULL);
3009   }
3010 
3011   typeArrayOop annotations_oop = Annotations::make_java_array(annotations_array, CHECK_NULL);
3012   typeArrayHandle annotations = typeArrayHandle(THREAD, annotations_oop);
3013 
3014   InstanceKlass** filter = filter_length == 1 ?
3015       (InstanceKlass**) &filter_klass_pointers:
3016       (InstanceKlass**) filter_klass_pointers;
3017   objArrayOop filter_oop = oopFactory::new_objArray(vmClasses::Class_klass(), filter_length, CHECK_NULL);
3018   objArrayHandle filter_classes(THREAD, filter_oop);
3019   for (int i = 0; i < filter_length; i++) {
3020     filter_classes->obj_at_put(i, filter[i]->java_mirror());
3021   }
3022 
3023   // invoke VMSupport.encodeAnnotations
3024   JavaValue result(T_OBJECT);
3025   JavaCallArguments args;
3026   args.push_oop(annotations);
3027   args.push_oop(Handle(THREAD, holder->java_mirror()));
3028   args.push_oop(jcp);
3029   args.push_int(for_class);
3030   args.push_oop(filter_classes);
3031   Symbol* signature = vmSymbols::encodeAnnotations_signature();
3032   JavaCalls::call_static(&result,
3033                          vm_support,
3034                          vmSymbols::encodeAnnotations_name(),
3035                          signature,
3036                          &args,
3037                          CHECK_NULL);
3038 
3039   oop res = result.get_oop();
3040   if (JVMCIENV->is_hotspot()) {
3041     return (jbyteArray) JNIHandles::make_local(THREAD, res);
3042   }
3043 
3044   typeArrayOop ba = typeArrayOop(res);
3045   int ba_len = ba->length();
3046   jbyte* ba_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jbyte, ba_len);
3047   if (ba_buf == nullptr) {
3048     JVMCI_THROW_MSG_NULL(InternalError,
3049               err_msg("could not allocate %d bytes", ba_len));
3050 
3051   }
3052   memcpy(ba_buf, ba->byte_at_addr(0), ba_len);
3053   JVMCIPrimitiveArray ba_dest = JVMCIENV->new_byteArray(ba_len, JVMCI_CHECK_NULL);
3054   JVMCIENV->copy_bytes_from(ba_buf, ba_dest, 0, ba_len);
3055   return JVMCIENV->get_jbyteArray(ba_dest);
3056 }
3057 
3058 C2V_VMENTRY_NULL(jbyteArray, getEncodedClassAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass),
3059                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3060   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3061   InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
3062   return get_encoded_annotation_data(holder, holder->class_annotations(), true, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3063 C2V_END
3064 
3065 C2V_VMENTRY_NULL(jbyteArray, getEncodedExecutableAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3066                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3067   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3068   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3069   return get_encoded_annotation_data(method->method_holder(), method->annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3070 C2V_END
3071 
3072 C2V_VMENTRY_NULL(jbyteArray, getEncodedFieldAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index,
3073                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3074   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3075   InstanceKlass* holder = check_field(InstanceKlass::cast(UNPACK_PAIR(Klass, klass)), index, JVMCIENV);
3076   fieldDescriptor fd(holder, index);
3077   return get_encoded_annotation_data(holder, fd.annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3078 C2V_END
3079 
3080 C2V_VMENTRY_NULL(jobjectArray, getFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address, jobjectArray current))
3081   FailedSpeculation* head = *((FailedSpeculation**)(address) failed_speculations_address);
3082   int result_length = 0;
3083   for (FailedSpeculation* fs = head; fs != nullptr; fs = fs->next()) {
3084     result_length++;
3085   }
3086   int current_length = 0;
3087   JVMCIObjectArray current_array = nullptr;
3088   if (current != nullptr) {
3089     current_array = JVMCIENV->wrap(current);
3090     current_length = JVMCIENV->get_length(current_array);
3091     if (current_length == result_length) {
3092       // No new failures
3093       return current;
3094     }
3095   }
3096   JVMCIObjectArray result = JVMCIENV->new_byte_array_array(result_length, JVMCI_CHECK_NULL);
3097   int result_index = 0;
3098   for (FailedSpeculation* fs = head; result_index < result_length; fs = fs->next()) {
3099     assert(fs != nullptr, "npe");
3100     JVMCIPrimitiveArray entry;
3101     if (result_index < current_length) {
3102       entry = (JVMCIPrimitiveArray) JVMCIENV->get_object_at(current_array, result_index);
3103     } else {
3104       entry = JVMCIENV->new_byteArray(fs->data_len(), JVMCI_CHECK_NULL);
3105       JVMCIENV->copy_bytes_from((jbyte*) fs->data(), entry, 0, fs->data_len());
3106     }
3107     JVMCIENV->put_object_at(result, result_index++, entry);
3108   }
3109   return JVMCIENV->get_jobjectArray(result);
3110 C2V_END
3111 
3112 C2V_VMENTRY_0(jlong, getFailedSpeculationsAddress, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
3113   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3114   MethodData* method_data = get_profiling_method_data(method, CHECK_0);
3115   return (jlong) method_data->get_failed_speculations_address();
3116 C2V_END
3117 
3118 C2V_VMENTRY(void, releaseFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address))
3119   FailedSpeculation::free_failed_speculations((FailedSpeculation**)(address) failed_speculations_address);
3120 C2V_END
3121 
3122 C2V_VMENTRY_0(jboolean, addFailedSpeculation, (JNIEnv* env, jobject, jlong failed_speculations_address, jbyteArray speculation_obj))
3123   JVMCIPrimitiveArray speculation_handle = JVMCIENV->wrap(speculation_obj);
3124   int speculation_len = JVMCIENV->get_length(speculation_handle);
3125   char* speculation = NEW_RESOURCE_ARRAY(char, speculation_len);
3126   JVMCIENV->copy_bytes_to(speculation_handle, (jbyte*) speculation, 0, speculation_len);
3127   return FailedSpeculation::add_failed_speculation(nullptr, (FailedSpeculation**)(address) failed_speculations_address, (address) speculation, speculation_len);
3128 C2V_END
3129 
3130 C2V_VMENTRY(void, callSystemExit, (JNIEnv* env, jobject, jint status))
3131   if (!JVMCIENV->is_hotspot()) {
3132     // It's generally not safe to call Java code before the module system is initialized
3133     if (!Universe::is_module_initialized()) {
3134       JVMCI_event_1("callSystemExit(%d) before Universe::is_module_initialized() -> direct VM exit", status);
3135       vm_exit_during_initialization();
3136     }
3137   }
3138   CompilerThreadCanCallJava canCallJava(thread, true);
3139   JavaValue result(T_VOID);
3140   JavaCallArguments jargs(1);
3141   jargs.push_int(status);
3142   JavaCalls::call_static(&result,
3143                        vmClasses::System_klass(),
3144                        vmSymbols::exit_method_name(),
3145                        vmSymbols::int_void_signature(),
3146                        &jargs,
3147                        CHECK);
3148 C2V_END
3149 
3150 C2V_VMENTRY_0(jlong, ticksNow, (JNIEnv* env, jobject))
3151   return CompilerEvent::ticksNow();
3152 C2V_END
3153 
3154 C2V_VMENTRY_0(jint, registerCompilerPhase, (JNIEnv* env, jobject, jstring jphase_name))
3155 #if INCLUDE_JFR
3156   JVMCIObject phase_name = JVMCIENV->wrap(jphase_name);
3157   const char *name = JVMCIENV->as_utf8_string(phase_name);
3158   return CompilerEvent::PhaseEvent::get_phase_id(name, true, true, true);
3159 #else
3160   return -1;
3161 #endif // !INCLUDE_JFR
3162 C2V_END
3163 
3164 C2V_VMENTRY(void, notifyCompilerPhaseEvent, (JNIEnv* env, jobject, jlong startTime, jint phase, jint compileId, jint level))
3165   EventCompilerPhase event(UNTIMED);
3166   if (event.should_commit()) {
3167     CompilerEvent::PhaseEvent::post(event, startTime, phase, compileId, level);
3168   }
3169 C2V_END
3170 
3171 C2V_VMENTRY(void, notifyCompilerInliningEvent, (JNIEnv* env, jobject, jint compileId, ARGUMENT_PAIR(caller), ARGUMENT_PAIR(callee), jboolean succeeded, jstring jmessage, jint bci))
3172   EventCompilerInlining event;
3173   if (event.should_commit()) {
3174     Method* caller = UNPACK_PAIR(Method, caller);
3175     Method* callee = UNPACK_PAIR(Method, callee);
3176     JVMCIObject message = JVMCIENV->wrap(jmessage);
3177     CompilerEvent::InlineEvent::post(event, compileId, caller, callee, succeeded, JVMCIENV->as_utf8_string(message), bci);
3178   }
3179 C2V_END
3180 
3181 C2V_VMENTRY(void, setThreadLocalObject, (JNIEnv* env, jobject, jint id, jobject value))
3182   requireInHotSpot("setThreadLocalObject", JVMCI_CHECK);
3183   if (id == 0) {
3184     thread->set_jvmci_reserved_oop0(JNIHandles::resolve(value));
3185     return;
3186   }
3187   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3188             err_msg("%d is not a valid thread local id", id));
3189 C2V_END
3190 
3191 C2V_VMENTRY_NULL(jobject, getThreadLocalObject, (JNIEnv* env, jobject, jint id))
3192   requireInHotSpot("getThreadLocalObject", JVMCI_CHECK_NULL);
3193   if (id == 0) {
3194     return JNIHandles::make_local(thread->get_jvmci_reserved_oop0());
3195   }
3196   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
3197                  err_msg("%d is not a valid thread local id", id));
3198 C2V_END
3199 
3200 C2V_VMENTRY(void, setThreadLocalLong, (JNIEnv* env, jobject, jint id, jlong value))
3201   requireInHotSpot("setThreadLocalLong", JVMCI_CHECK);
3202   if (id == 0) {
3203     thread->set_jvmci_reserved0(value);
3204   } else if (id == 1) {
3205     thread->set_jvmci_reserved1(value);
3206   } else {
3207     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3208               err_msg("%d is not a valid thread local id", id));
3209   }
3210 C2V_END
3211 
3212 C2V_VMENTRY_0(jlong, getThreadLocalLong, (JNIEnv* env, jobject, jint id))
3213   requireInHotSpot("getThreadLocalLong", JVMCI_CHECK_0);
3214   if (id == 0) {
3215     return thread->get_jvmci_reserved0();
3216   } else if (id == 1) {
3217     return thread->get_jvmci_reserved1();
3218   } else {
3219     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
3220                 err_msg("%d is not a valid thread local id", id));
3221   }
3222 C2V_END
3223 
3224 C2V_VMENTRY(void, getOopMapAt, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3225                  jint bci, jlongArray oop_map_handle))
3226   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3227   if (bci < 0 || bci >= method->code_size()) {
3228     JVMCI_THROW_MSG(IllegalArgumentException,
3229                 err_msg("bci %d is out of bounds [0 .. %d)", bci, method->code_size()));
3230   }
3231   InterpreterOopMap mask;
3232   OopMapCache::compute_one_oop_map(method, bci, &mask);
3233   if (!mask.has_valid_mask()) {
3234     JVMCI_THROW_MSG(IllegalArgumentException, err_msg("bci %d is not valid", bci));
3235   }
3236   if (mask.number_of_entries() == 0) {
3237     return;
3238   }
3239 
3240   int nslots = method->max_locals() + method->max_stack();
3241   int nwords = ((nslots - 1) / 64) + 1;
3242   JVMCIPrimitiveArray oop_map = JVMCIENV->wrap(oop_map_handle);
3243   int oop_map_len = JVMCIENV->get_length(oop_map);
3244   if (nwords > oop_map_len) {
3245     JVMCI_THROW_MSG(IllegalArgumentException,
3246                 err_msg("oop map too short: %d > %d", nwords, oop_map_len));
3247   }
3248 
3249   jlong* oop_map_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jlong, nwords);
3250   if (oop_map_buf == nullptr) {
3251     JVMCI_THROW_MSG(InternalError, err_msg("could not allocate %d longs", nwords));
3252   }
3253   for (int i = 0; i < nwords; i++) {
3254     oop_map_buf[i] = 0L;
3255   }
3256 
3257   BitMapView oop_map_view = BitMapView((BitMap::bm_word_t*) oop_map_buf, nwords * BitsPerLong);
3258   for (int i = 0; i < nslots; i++) {
3259     if (mask.is_oop(i)) {
3260       oop_map_view.set_bit(i);
3261     }
3262   }
3263   JVMCIENV->copy_longs_from((jlong*)oop_map_buf, oop_map, 0, nwords);
3264 C2V_END
3265 
3266 C2V_VMENTRY_0(jint, getCompilationActivityMode, (JNIEnv* env, jobject))
3267   return CompileBroker::get_compilation_activity_mode();
3268 C2V_END
3269 
3270 C2V_VMENTRY_0(jboolean, isCompilerThread, (JNIEnv* env, jobject))
3271   return thread->is_Compiler_thread();
3272 C2V_END
3273 
3274 #define CC (char*)  /*cast a literal from (const char*)*/
3275 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
3276 
3277 #define STRING                  "Ljava/lang/String;"
3278 #define OBJECT                  "Ljava/lang/Object;"
3279 #define CLASS                   "Ljava/lang/Class;"
3280 #define OBJECTCONSTANT          "Ljdk/vm/ci/hotspot/HotSpotObjectConstantImpl;"
3281 #define EXECUTABLE              "Ljava/lang/reflect/Executable;"
3282 #define STACK_TRACE_ELEMENT     "Ljava/lang/StackTraceElement;"
3283 #define INSTALLED_CODE          "Ljdk/vm/ci/code/InstalledCode;"
3284 #define BYTECODE_FRAME          "Ljdk/vm/ci/code/BytecodeFrame;"
3285 #define JAVACONSTANT            "Ljdk/vm/ci/meta/JavaConstant;"
3286 #define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
3287 #define RESOLVED_METHOD         "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
3288 #define FIELDINFO               "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl$FieldInfo;"
3289 #define HS_RESOLVED_TYPE        "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaType;"
3290 #define HS_INSTALLED_CODE       "Ljdk/vm/ci/hotspot/HotSpotInstalledCode;"
3291 #define HS_NMETHOD              "Ljdk/vm/ci/hotspot/HotSpotNmethod;"
3292 #define HS_COMPILED_CODE        "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
3293 #define HS_CONFIG               "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
3294 #define HS_STACK_FRAME_REF      "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
3295 #define HS_SPECULATION_LOG      "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
3296 #define REFLECTION_EXECUTABLE   "Ljava/lang/reflect/Executable;"
3297 #define REFLECTION_FIELD        "Ljava/lang/reflect/Field;"
3298 
3299 // Types wrapping VM pointers. The ...2 macro is for a pair: (wrapper, pointer)
3300 #define HS_METHOD               "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
3301 #define HS_METHOD2              "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;J"
3302 #define HS_KLASS                "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
3303 #define HS_KLASS2               "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;J"
3304 #define HS_CONSTANT_POOL        "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
3305 #define HS_CONSTANT_POOL2       "Ljdk/vm/ci/hotspot/HotSpotConstantPool;J"
3306 
3307 JNINativeMethod CompilerToVM::methods[] = {
3308   {CC "getBytecode",                                  CC "(" HS_METHOD2 ")[B",                                                              FN_PTR(getBytecode)},
3309   {CC "getExceptionTableStart",                       CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getExceptionTableStart)},
3310   {CC "getExceptionTableLength",                      CC "(" HS_METHOD2 ")I",                                                               FN_PTR(getExceptionTableLength)},
3311   {CC "findUniqueConcreteMethod",                     CC "(" HS_KLASS2 HS_METHOD2 ")" HS_METHOD,                                            FN_PTR(findUniqueConcreteMethod)},
3312   {CC "getImplementor",                               CC "(" HS_KLASS2 ")" HS_KLASS,                                                        FN_PTR(getImplementor)},
3313   {CC "getStackTraceElement",                         CC "(" HS_METHOD2 "I)" STACK_TRACE_ELEMENT,                                           FN_PTR(getStackTraceElement)},
3314   {CC "methodIsIgnoredBySecurityStackWalk",           CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(methodIsIgnoredBySecurityStackWalk)},
3315   {CC "setNotInlinableOrCompilable",                  CC "(" HS_METHOD2 ")V",                                                               FN_PTR(setNotInlinableOrCompilable)},
3316   {CC "isCompilable",                                 CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(isCompilable)},
3317   {CC "hasNeverInlineDirective",                      CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(hasNeverInlineDirective)},
3318   {CC "shouldInlineMethod",                           CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(shouldInlineMethod)},
3319   {CC "lookupType",                                   CC "(" STRING HS_KLASS2 "IZ)" HS_RESOLVED_TYPE,                                       FN_PTR(lookupType)},
3320   {CC "lookupJClass",                                 CC "(J)" HS_RESOLVED_TYPE,                                                            FN_PTR(lookupJClass)},
3321   {CC "getJObjectValue",                              CC "(" OBJECTCONSTANT ")J",                                                           FN_PTR(getJObjectValue)},
3322   {CC "getArrayType",                                 CC "(C" HS_KLASS2 ")" HS_KLASS,                                                       FN_PTR(getArrayType)},
3323   {CC "lookupClass",                                  CC "(" CLASS ")" HS_RESOLVED_TYPE,                                                    FN_PTR(lookupClass)},
3324   {CC "lookupNameInPool",                             CC "(" HS_CONSTANT_POOL2 "II)" STRING,                                                FN_PTR(lookupNameInPool)},
3325   {CC "lookupNameAndTypeRefIndexInPool",              CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(lookupNameAndTypeRefIndexInPool)},
3326   {CC "lookupSignatureInPool",                        CC "(" HS_CONSTANT_POOL2 "II)" STRING,                                                FN_PTR(lookupSignatureInPool)},
3327   {CC "lookupKlassRefIndexInPool",                    CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(lookupKlassRefIndexInPool)},
3328   {CC "lookupKlassInPool",                            CC "(" HS_CONSTANT_POOL2 "I)Ljava/lang/Object;",                                      FN_PTR(lookupKlassInPool)},
3329   {CC "lookupAppendixInPool",                         CC "(" HS_CONSTANT_POOL2 "II)" OBJECTCONSTANT,                                        FN_PTR(lookupAppendixInPool)},
3330   {CC "lookupMethodInPool",                           CC "(" HS_CONSTANT_POOL2 "IB" HS_METHOD2 ")" HS_METHOD,                               FN_PTR(lookupMethodInPool)},
3331   {CC "lookupConstantInPool",                         CC "(" HS_CONSTANT_POOL2 "IZ)" JAVACONSTANT,                                          FN_PTR(lookupConstantInPool)},
3332   {CC "getNumIndyEntries",                            CC "(" HS_CONSTANT_POOL2 ")I",                                                        FN_PTR(getNumIndyEntries)},
3333   {CC "resolveBootstrapMethod",                       CC "(" HS_CONSTANT_POOL2 "I)[" OBJECT,                                                FN_PTR(resolveBootstrapMethod)},
3334   {CC "bootstrapArgumentIndexAt",                     CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(bootstrapArgumentIndexAt)},
3335   {CC "getUncachedStringInPool",                      CC "(" HS_CONSTANT_POOL2 "I)" JAVACONSTANT,                                           FN_PTR(getUncachedStringInPool)},
3336   {CC "resolveTypeInPool",                            CC "(" HS_CONSTANT_POOL2 "I)" HS_KLASS,                                               FN_PTR(resolveTypeInPool)},
3337   {CC "resolveFieldInPool",                           CC "(" HS_CONSTANT_POOL2 "I" HS_METHOD2 "B[I)" HS_KLASS,                              FN_PTR(resolveFieldInPool)},
3338   {CC "decodeFieldIndexToCPIndex",                    CC "(" HS_CONSTANT_POOL2 "I)I",                                                       FN_PTR(decodeFieldIndexToCPIndex)},
3339   {CC "decodeMethodIndexToCPIndex",                   CC "(" HS_CONSTANT_POOL2 "I)I",                                                       FN_PTR(decodeMethodIndexToCPIndex)},
3340   {CC "decodeIndyIndexToCPIndex",                     CC "(" HS_CONSTANT_POOL2 "IZ)I",                                                      FN_PTR(decodeIndyIndexToCPIndex)},
3341   {CC "resolveInvokeHandleInPool",                    CC "(" HS_CONSTANT_POOL2 "I)V",                                                       FN_PTR(resolveInvokeHandleInPool)},
3342   {CC "isResolvedInvokeHandleInPool",                 CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(isResolvedInvokeHandleInPool)},
3343   {CC "resolveMethod",                                CC "(" HS_KLASS2 HS_METHOD2 HS_KLASS2 ")" HS_METHOD,                                  FN_PTR(resolveMethod)},
3344   {CC "getSignaturePolymorphicHolders",               CC "()[" STRING,                                                                      FN_PTR(getSignaturePolymorphicHolders)},
3345   {CC "getVtableIndexForInterfaceMethod",             CC "(" HS_KLASS2 HS_METHOD2 ")I",                                                     FN_PTR(getVtableIndexForInterfaceMethod)},
3346   {CC "getClassInitializer",                          CC "(" HS_KLASS2 ")" HS_METHOD,                                                       FN_PTR(getClassInitializer)},
3347   {CC "hasFinalizableSubclass",                       CC "(" HS_KLASS2 ")Z",                                                                FN_PTR(hasFinalizableSubclass)},
3348   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
3349   {CC "asResolvedJavaMethod",                         CC "(" EXECUTABLE ")" HS_METHOD,                                                      FN_PTR(asResolvedJavaMethod)},
3350   {CC "getResolvedJavaMethod",                        CC "(" OBJECTCONSTANT "J)" HS_METHOD,                                                 FN_PTR(getResolvedJavaMethod)},
3351   {CC "getConstantPool",                              CC "(" OBJECT "JZ)" HS_CONSTANT_POOL,                                                 FN_PTR(getConstantPool)},
3352   {CC "getResolvedJavaType0",                         CC "(Ljava/lang/Object;JZ)" HS_KLASS,                                                 FN_PTR(getResolvedJavaType0)},
3353   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
3354   {CC "installCode0",                                 CC "(JJZ" HS_COMPILED_CODE "[" OBJECT INSTALLED_CODE "J[B)I",                         FN_PTR(installCode0)},
3355   {CC "getInstallCodeFlags",                          CC "()I",                                                                             FN_PTR(getInstallCodeFlags)},
3356   {CC "resetCompilationStatistics",                   CC "()V",                                                                             FN_PTR(resetCompilationStatistics)},
3357   {CC "disassembleCodeBlob",                          CC "(" INSTALLED_CODE ")" STRING,                                                     FN_PTR(disassembleCodeBlob)},
3358   {CC "executeHotSpotNmethod",                        CC "([" OBJECT HS_NMETHOD ")" OBJECT,                                                 FN_PTR(executeHotSpotNmethod)},
3359   {CC "getLineNumberTable",                           CC "(" HS_METHOD2 ")[J",                                                              FN_PTR(getLineNumberTable)},
3360   {CC "getLocalVariableTableStart",                   CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getLocalVariableTableStart)},
3361   {CC "getLocalVariableTableLength",                  CC "(" HS_METHOD2 ")I",                                                               FN_PTR(getLocalVariableTableLength)},
3362   {CC "reprofile",                                    CC "(" HS_METHOD2 ")V",                                                               FN_PTR(reprofile)},
3363   {CC "invalidateHotSpotNmethod",                     CC "(" HS_NMETHOD "Z)V",                                                              FN_PTR(invalidateHotSpotNmethod)},
3364   {CC "collectCounters",                              CC "()[J",                                                                            FN_PTR(collectCounters)},
3365   {CC "getCountersSize",                              CC "()I",                                                                             FN_PTR(getCountersSize)},
3366   {CC "setCountersSize",                              CC "(I)Z",                                                                            FN_PTR(setCountersSize)},
3367   {CC "allocateCompileId",                            CC "(" HS_METHOD2 "I)I",                                                              FN_PTR(allocateCompileId)},
3368   {CC "isMature",                                     CC "(J)Z",                                                                            FN_PTR(isMature)},
3369   {CC "hasCompiledCodeForOSR",                        CC "(" HS_METHOD2 "II)Z",                                                             FN_PTR(hasCompiledCodeForOSR)},
3370   {CC "getSymbol",                                    CC "(J)" STRING,                                                                      FN_PTR(getSymbol)},
3371   {CC "getSignatureName",                             CC "(J)" STRING,                                                                      FN_PTR(getSignatureName)},
3372   {CC "iterateFrames",                                CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT,   FN_PTR(iterateFrames)},
3373   {CC "materializeVirtualObjects",                    CC "(" HS_STACK_FRAME_REF "Z)V",                                                      FN_PTR(materializeVirtualObjects)},
3374   {CC "shouldDebugNonSafepoints",                     CC "()Z",                                                                             FN_PTR(shouldDebugNonSafepoints)},
3375   {CC "writeDebugOutput",                             CC "(JIZ)V",                                                                          FN_PTR(writeDebugOutput)},
3376   {CC "flushDebugOutput",                             CC "()V",                                                                             FN_PTR(flushDebugOutput)},
3377   {CC "methodDataProfileDataSize",                    CC "(JI)I",                                                                           FN_PTR(methodDataProfileDataSize)},
3378   {CC "methodDataExceptionSeen",                      CC "(JI)I",                                                                           FN_PTR(methodDataExceptionSeen)},
3379   {CC "interpreterFrameSize",                         CC "(" BYTECODE_FRAME ")I",                                                           FN_PTR(interpreterFrameSize)},
3380   {CC "compileToBytecode",                            CC "(" OBJECTCONSTANT ")V",                                                           FN_PTR(compileToBytecode)},
3381   {CC "getFlagValue",                                 CC "(" STRING ")" OBJECT,                                                             FN_PTR(getFlagValue)},
3382   {CC "getInterfaces",                                CC "(" HS_KLASS2 ")[" HS_KLASS,                                                       FN_PTR(getInterfaces)},
3383   {CC "getComponentType",                             CC "(" HS_KLASS2 ")" HS_RESOLVED_TYPE,                                                FN_PTR(getComponentType)},
3384   {CC "ensureInitialized",                            CC "(" HS_KLASS2 ")V",                                                                FN_PTR(ensureInitialized)},
3385   {CC "ensureLinked",                                 CC "(" HS_KLASS2 ")V",                                                                FN_PTR(ensureLinked)},
3386   {CC "getIdentityHashCode",                          CC "(" OBJECTCONSTANT ")I",                                                           FN_PTR(getIdentityHashCode)},
3387   {CC "isInternedString",                             CC "(" OBJECTCONSTANT ")Z",                                                           FN_PTR(isInternedString)},
3388   {CC "unboxPrimitive",                               CC "(" OBJECTCONSTANT ")" OBJECT,                                                     FN_PTR(unboxPrimitive)},
3389   {CC "boxPrimitive",                                 CC "(" OBJECT ")" OBJECTCONSTANT,                                                     FN_PTR(boxPrimitive)},
3390   {CC "getDeclaredConstructors",                      CC "(" HS_KLASS2 ")[" RESOLVED_METHOD,                                                FN_PTR(getDeclaredConstructors)},
3391   {CC "getDeclaredMethods",                           CC "(" HS_KLASS2 ")[" RESOLVED_METHOD,                                                FN_PTR(getDeclaredMethods)},
3392   {CC "getAllMethods",                                CC "(" HS_KLASS2 ")[" RESOLVED_METHOD,                                                FN_PTR(getAllMethods)},
3393   {CC "getDeclaredFieldsInfo",                        CC "(" HS_KLASS2 ")[" FIELDINFO,                                                      FN_PTR(getDeclaredFieldsInfo)},
3394   {CC "readStaticFieldValue",                         CC "(" HS_KLASS2 "JC)" JAVACONSTANT,                                                  FN_PTR(readStaticFieldValue)},
3395   {CC "readFieldValue",                               CC "(" OBJECTCONSTANT HS_KLASS2 "JC)" JAVACONSTANT,                                   FN_PTR(readFieldValue)},
3396   {CC "isInstance",                                   CC "(" HS_KLASS2 OBJECTCONSTANT ")Z",                                                 FN_PTR(isInstance)},
3397   {CC "isAssignableFrom",                             CC "(" HS_KLASS2 HS_KLASS2 ")Z",                                                      FN_PTR(isAssignableFrom)},
3398   {CC "isTrustedForIntrinsics",                       CC "(" HS_KLASS2 ")Z",                                                                FN_PTR(isTrustedForIntrinsics)},
3399   {CC "asJavaType",                                   CC "(" OBJECTCONSTANT ")" HS_RESOLVED_TYPE,                                           FN_PTR(asJavaType)},
3400   {CC "asString",                                     CC "(" OBJECTCONSTANT ")" STRING,                                                     FN_PTR(asString)},
3401   {CC "equals",                                       CC "(" OBJECTCONSTANT "J" OBJECTCONSTANT "J)Z",                                       FN_PTR(equals)},
3402   {CC "getJavaMirror",                                CC "(" HS_KLASS2 ")" OBJECTCONSTANT,                                                  FN_PTR(getJavaMirror)},
3403   {CC "getArrayLength",                               CC "(" OBJECTCONSTANT ")I",                                                           FN_PTR(getArrayLength)},
3404   {CC "readArrayElement",                             CC "(" OBJECTCONSTANT "I)Ljava/lang/Object;",                                         FN_PTR(readArrayElement)},
3405   {CC "arrayBaseOffset",                              CC "(C)I",                                                                            FN_PTR(arrayBaseOffset)},
3406   {CC "arrayIndexScale",                              CC "(C)I",                                                                            FN_PTR(arrayIndexScale)},
3407   {CC "clearOopHandle",                               CC "(J)V",                                                                            FN_PTR(clearOopHandle)},
3408   {CC "releaseClearedOopHandles",                     CC "()V",                                                                             FN_PTR(releaseClearedOopHandles)},
3409   {CC "registerNativeMethods",                        CC "(" CLASS ")[J",                                                                   FN_PTR(registerNativeMethods)},
3410   {CC "isCurrentThreadAttached",                      CC "()Z",                                                                             FN_PTR(isCurrentThreadAttached)},
3411   {CC "getCurrentJavaThread",                         CC "()J",                                                                             FN_PTR(getCurrentJavaThread)},
3412   {CC "attachCurrentThread",                          CC "([BZ[J)Z",                                                                        FN_PTR(attachCurrentThread)},
3413   {CC "detachCurrentThread",                          CC "(Z)Z",                                                                            FN_PTR(detachCurrentThread)},
3414   {CC "translate",                                    CC "(" OBJECT "Z)J",                                                                  FN_PTR(translate)},
3415   {CC "unhand",                                       CC "(J)" OBJECT,                                                                      FN_PTR(unhand)},
3416   {CC "updateHotSpotNmethod",                         CC "(" HS_NMETHOD ")V",                                                               FN_PTR(updateHotSpotNmethod)},
3417   {CC "getCode",                                      CC "(" HS_INSTALLED_CODE ")[B",                                                       FN_PTR(getCode)},
3418   {CC "asReflectionExecutable",                       CC "(" HS_METHOD2 ")" REFLECTION_EXECUTABLE,                                          FN_PTR(asReflectionExecutable)},
3419   {CC "asReflectionField",                            CC "(" HS_KLASS2 "I)" REFLECTION_FIELD,                                               FN_PTR(asReflectionField)},
3420   {CC "getEncodedClassAnnotationData",                CC "(" HS_KLASS2 OBJECT "IJ)[B",                                                      FN_PTR(getEncodedClassAnnotationData)},
3421   {CC "getEncodedExecutableAnnotationData",           CC "(" HS_METHOD2 OBJECT "IJ)[B",                                                     FN_PTR(getEncodedExecutableAnnotationData)},
3422   {CC "getEncodedFieldAnnotationData",                CC "(" HS_KLASS2 "I" OBJECT "IJ)[B",                                                  FN_PTR(getEncodedFieldAnnotationData)},
3423   {CC "getFailedSpeculations",                        CC "(J[[B)[[B",                                                                       FN_PTR(getFailedSpeculations)},
3424   {CC "getFailedSpeculationsAddress",                 CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getFailedSpeculationsAddress)},
3425   {CC "releaseFailedSpeculations",                    CC "(J)V",                                                                            FN_PTR(releaseFailedSpeculations)},
3426   {CC "addFailedSpeculation",                         CC "(J[B)Z",                                                                          FN_PTR(addFailedSpeculation)},
3427   {CC "callSystemExit",                               CC "(I)V",                                                                            FN_PTR(callSystemExit)},
3428   {CC "ticksNow",                                     CC "()J",                                                                             FN_PTR(ticksNow)},
3429   {CC "getThreadLocalObject",                         CC "(I)" OBJECT,                                                                      FN_PTR(getThreadLocalObject)},
3430   {CC "setThreadLocalObject",                         CC "(I" OBJECT ")V",                                                                  FN_PTR(setThreadLocalObject)},
3431   {CC "getThreadLocalLong",                           CC "(I)J",                                                                            FN_PTR(getThreadLocalLong)},
3432   {CC "setThreadLocalLong",                           CC "(IJ)V",                                                                           FN_PTR(setThreadLocalLong)},
3433   {CC "registerCompilerPhase",                        CC "(" STRING ")I",                                                                   FN_PTR(registerCompilerPhase)},
3434   {CC "notifyCompilerPhaseEvent",                     CC "(JIII)V",                                                                         FN_PTR(notifyCompilerPhaseEvent)},
3435   {CC "notifyCompilerInliningEvent",                  CC "(I" HS_METHOD2 HS_METHOD2 "ZLjava/lang/String;I)V",                               FN_PTR(notifyCompilerInliningEvent)},
3436   {CC "getOopMapAt",                                  CC "(" HS_METHOD2 "I[J)V",                                                            FN_PTR(getOopMapAt)},
3437   {CC "updateCompilerThreadCanCallJava",              CC "(Z)Z",                                                                            FN_PTR(updateCompilerThreadCanCallJava)},
3438   {CC "getCompilationActivityMode",                   CC "()I",                                                                             FN_PTR(getCompilationActivityMode)},
3439   {CC "isCompilerThread",                             CC "()Z",                                                                             FN_PTR(isCompilerThread)},
3440 };
3441 
3442 int CompilerToVM::methods_count() {
3443   return sizeof(methods) / sizeof(JNINativeMethod);
3444 }