1 /*
   2  * Copyright (c) 2011, 2018, 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 "precompiled.hpp"
  25 #include "ci/ciUtilities.inline.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/scopeDesc.hpp"
  28 #include "interpreter/linkResolver.hpp"
  29 #include "memory/oopFactory.hpp"
  30 #include "oops/cpCache.inline.hpp"
  31 #include "oops/generateOopMap.hpp"
  32 #include "oops/method.inline.hpp"
  33 #include "oops/objArrayOop.inline.hpp"
  34 #include "oops/typeArrayOop.inline.hpp"
  35 #include "compiler/compileBroker.hpp"
  36 #include "compiler/disassembler.hpp"
  37 #include "jvmci/jvmciCompilerToVM.hpp"
  38 #include "jvmci/jvmciCodeInstaller.hpp"
  39 #include "jvmci/jvmciRuntime.hpp"
  40 #include "runtime/frame.inline.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/jniHandles.inline.hpp"
  43 #include "runtime/timerTrace.hpp"
  44 #include "runtime/vframe_hp.hpp"
  45 
  46 
  47 void JNIHandleMark::push_jni_handle_block() {
  48   JavaThread* thread = JavaThread::current();
  49   if (thread != NULL) {
  50     // Allocate a new block for JNI handles.
  51     // Inlined code from jni_PushLocalFrame()
  52     JNIHandleBlock* java_handles = ((JavaThread*)thread)->active_handles();
  53     JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
  54     assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
  55     compile_handles->set_pop_frame_link(java_handles);
  56     thread->set_active_handles(compile_handles);
  57   }
  58 }
  59 
  60 void JNIHandleMark::pop_jni_handle_block() {
  61   JavaThread* thread = JavaThread::current();
  62   if (thread != NULL) {
  63     // Release our JNI handle block
  64     JNIHandleBlock* compile_handles = thread->active_handles();
  65     JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
  66     thread->set_active_handles(java_handles);
  67     compile_handles->set_pop_frame_link(NULL);
  68     JNIHandleBlock::release_block(compile_handles, thread); // may block
  69   }
  70 }
  71 
  72 // Entry to native method implementation that transitions current thread to '_thread_in_vm'.
  73 #define C2V_VMENTRY(result_type, name, signature) \
  74   JNIEXPORT result_type JNICALL c2v_ ## name signature { \
  75   TRACE_jvmci_1("CompilerToVM::" #name); \
  76   TRACE_CALL(result_type, jvmci_ ## name signature) \
  77   JVMCI_VM_ENTRY_MARK; \
  78 
  79 #define C2V_END }
  80 
  81 oop CompilerToVM::get_jvmci_method(const methodHandle& method, TRAPS) {
  82   if (method() != NULL) {
  83     JavaValue result(T_OBJECT);
  84     JavaCallArguments args;
  85     args.push_long((jlong) (address) method());
  86     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedJavaMethodImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::method_fromMetaspace_signature(), &args, CHECK_NULL);
  87 
  88     return (oop)result.get_jobject();
  89   }
  90   return NULL;
  91 }
  92 
  93 oop CompilerToVM::get_jvmci_type(Klass* klass, TRAPS) {
  94   if (klass != NULL) {
  95     JavaValue result(T_OBJECT);
  96     JavaCallArguments args;
  97     args.push_oop(Handle(THREAD, klass->java_mirror()));
  98     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedObjectTypeImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::klass_fromMetaspace_signature(), &args, CHECK_NULL);
  99 
 100     return (oop)result.get_jobject();
 101   }
 102   return NULL;
 103 }
 104 
 105 Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
 106   assert(_index < _args->length(), "out of bounds");
 107   oop arg=((objArrayOop) (_args))->obj_at(_index++);
 108   assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
 109   return Handle(Thread::current(), arg);
 110 }
 111 
 112 jobjectArray readConfiguration0(JNIEnv *env, TRAPS);
 113 
 114 C2V_VMENTRY(jobjectArray, readConfiguration, (JNIEnv *env))
 115    jobjectArray config = readConfiguration0(env, CHECK_NULL);
 116    return config;
 117 C2V_END
 118 
 119 C2V_VMENTRY(jobject, getFlagValue, (JNIEnv *, jobject c2vm, jobject name_handle))
 120 #define RETURN_BOXED_LONG(value) oop box; jvalue p; p.j = (jlong) (value); box = java_lang_boxing_object::create(T_LONG, &p, CHECK_NULL); return JNIHandles::make_local(THREAD, box);
 121 #define RETURN_BOXED_DOUBLE(value) oop box; jvalue p; p.d = (jdouble) (value); box = java_lang_boxing_object::create(T_DOUBLE, &p, CHECK_NULL); return JNIHandles::make_local(THREAD, box);
 122   Handle name(THREAD, JNIHandles::resolve(name_handle));
 123   if (name.is_null()) {
 124     THROW_0(vmSymbols::java_lang_NullPointerException());
 125   }
 126   ResourceMark rm;
 127   const char* cstring = java_lang_String::as_utf8_string(name());
 128   JVMFlag* flag = JVMFlag::find_flag(cstring, strlen(cstring), /* allow_locked */ true, /* return_flag */ true);
 129   if (flag == NULL) {
 130     return c2vm;
 131   }
 132   if (flag->is_bool()) {
 133     jvalue prim;
 134     prim.z = flag->get_bool();
 135     oop box = java_lang_boxing_object::create(T_BOOLEAN, &prim, CHECK_NULL);
 136     return JNIHandles::make_local(THREAD, box);
 137   } else if (flag->is_ccstr()) {
 138     Handle value = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_NULL);
 139     return JNIHandles::make_local(THREAD, value());
 140   } else if (flag->is_intx()) {
 141     RETURN_BOXED_LONG(flag->get_intx());
 142   } else if (flag->is_int()) {
 143     RETURN_BOXED_LONG(flag->get_int());
 144   } else if (flag->is_uint()) {
 145     RETURN_BOXED_LONG(flag->get_uint());
 146   } else if (flag->is_uint64_t()) {
 147     RETURN_BOXED_LONG(flag->get_uint64_t());
 148   } else if (flag->is_size_t()) {
 149     RETURN_BOXED_LONG(flag->get_size_t());
 150   } else if (flag->is_uintx()) {
 151     RETURN_BOXED_LONG(flag->get_uintx());
 152   } else if (flag->is_double()) {
 153     RETURN_BOXED_DOUBLE(flag->get_double());
 154   } else {
 155     JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->_name, flag->_type);
 156   }
 157 #undef RETURN_BOXED_LONG
 158 #undef RETURN_BOXED_DOUBLE
 159 C2V_END
 160 
 161 C2V_VMENTRY(jbyteArray, getBytecode, (JNIEnv *, jobject, jobject jvmci_method))
 162   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 163   ResourceMark rm;
 164 
 165   int code_size = method->code_size();
 166   typeArrayOop reconstituted_code = oopFactory::new_byteArray(code_size, CHECK_NULL);
 167 
 168   guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
 169   // iterate over all bytecodes and replace non-Java bytecodes
 170 
 171   for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
 172     Bytecodes::Code code = s.code();
 173     Bytecodes::Code raw_code = s.raw_code();
 174     int bci = s.bci();
 175     int len = s.instruction_size();
 176 
 177     // Restore original byte code.
 178     reconstituted_code->byte_at_put(bci, (jbyte) (s.is_wide()? Bytecodes::_wide : code));
 179     if (len > 1) {
 180       memcpy(reconstituted_code->byte_at_addr(bci + 1), s.bcp()+1, len-1);
 181     }
 182 
 183     if (len > 1) {
 184       // Restore the big-endian constant pool indexes.
 185       // Cf. Rewriter::scan_method
 186       switch (code) {
 187         case Bytecodes::_getstatic:
 188         case Bytecodes::_putstatic:
 189         case Bytecodes::_getfield:
 190         case Bytecodes::_putfield:
 191         case Bytecodes::_invokevirtual:
 192         case Bytecodes::_invokespecial:
 193         case Bytecodes::_invokestatic:
 194         case Bytecodes::_invokeinterface:
 195         case Bytecodes::_invokehandle: {
 196           int cp_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 197           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 198           break;
 199         }
 200 
 201         case Bytecodes::_invokedynamic: {
 202           int cp_index = Bytes::get_native_u4((address) reconstituted_code->byte_at_addr(bci + 1));
 203           Bytes::put_Java_u4((address) reconstituted_code->byte_at_addr(bci + 1), (u4) cp_index);
 204           break;
 205         }
 206 
 207         default:
 208           break;
 209       }
 210 
 211       // Not all ldc byte code are rewritten.
 212       switch (raw_code) {
 213         case Bytecodes::_fast_aldc: {
 214           int cpc_index = reconstituted_code->byte_at(bci + 1) & 0xff;
 215           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 216           assert(cp_index < method->constants()->length(), "sanity check");
 217           reconstituted_code->byte_at_put(bci + 1, (jbyte) cp_index);
 218           break;
 219         }
 220 
 221         case Bytecodes::_fast_aldc_w: {
 222           int cpc_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 223           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 224           assert(cp_index < method->constants()->length(), "sanity check");
 225           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 226           break;
 227         }
 228 
 229         default:
 230           break;
 231       }
 232     }
 233   }
 234 
 235   return (jbyteArray) JNIHandles::make_local(THREAD, reconstituted_code);
 236 C2V_END
 237 
 238 C2V_VMENTRY(jint, getExceptionTableLength, (JNIEnv *, jobject, jobject jvmci_method))
 239   ResourceMark rm;
 240   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 241   return method->exception_table_length();
 242 C2V_END
 243 
 244 C2V_VMENTRY(jlong, getExceptionTableStart, (JNIEnv *, jobject, jobject jvmci_method))
 245   ResourceMark rm;
 246   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 247   if (method->exception_table_length() == 0) {
 248     return 0L;
 249   }
 250   return (jlong) (address) method->exception_table_start();
 251 C2V_END
 252 
 253 C2V_VMENTRY(jobject, asResolvedJavaMethod, (JNIEnv *, jobject, jobject executable_handle))
 254   oop executable = JNIHandles::resolve(executable_handle);
 255   oop mirror = NULL;
 256   int slot = 0;
 257 
 258   if (executable->klass() == SystemDictionary::reflect_Constructor_klass()) {
 259     mirror = java_lang_reflect_Constructor::clazz(executable);
 260     slot = java_lang_reflect_Constructor::slot(executable);
 261   } else {
 262     assert(executable->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
 263     mirror = java_lang_reflect_Method::clazz(executable);
 264     slot = java_lang_reflect_Method::slot(executable);
 265   }
 266   Klass* holder = java_lang_Class::as_Klass(mirror);
 267   methodHandle method = InstanceKlass::cast(holder)->method_with_idnum(slot);
 268   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 269   return JNIHandles::make_local(THREAD, result);
 270 }
 271 
 272 C2V_VMENTRY(jobject, getResolvedJavaMethod, (JNIEnv *, jobject, jobject base, jlong offset))
 273   methodHandle method;
 274   oop base_object = JNIHandles::resolve(base);
 275   if (base_object == NULL) {
 276     method = *((Method**)(offset));
 277   } else if (base_object->is_a(SystemDictionary::ResolvedMethodName_klass())) {
 278     method = (Method*) (intptr_t) base_object->long_field(offset);
 279   } else if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 280     method = *((Method**)(HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object) + offset));
 281   } else {
 282     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 283                 err_msg("Unexpected type: %s", base_object->klass()->external_name()));
 284   }
 285   assert (method.is_null() || method->is_method(), "invalid read");
 286   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 287   return JNIHandles::make_local(THREAD, result);
 288 }
 289 
 290 C2V_VMENTRY(jobject, getConstantPool, (JNIEnv *, jobject, jobject object_handle))
 291   constantPoolHandle cp;
 292   oop object = JNIHandles::resolve(object_handle);
 293   if (object == NULL) {
 294     THROW_0(vmSymbols::java_lang_NullPointerException());
 295   }
 296   if (object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 297     cp = CompilerToVM::asMethod(object)->constMethod()->constants();
 298   } else if (object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 299     cp = InstanceKlass::cast(CompilerToVM::asKlass(object))->constants();
 300   } else {
 301     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 302                 err_msg("Unexpected type: %s", object->klass()->external_name()));
 303   }
 304   assert(!cp.is_null(), "npe");
 305   JavaValue method_result(T_OBJECT);
 306   JavaCallArguments args;
 307   args.push_long((jlong) (address) cp());
 308   JavaCalls::call_static(&method_result, SystemDictionary::HotSpotConstantPool_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::constantPool_fromMetaspace_signature(), &args, CHECK_NULL);
 309   return JNIHandles::make_local(THREAD, (oop)method_result.get_jobject());
 310 }
 311 
 312 C2V_VMENTRY(jobject, getResolvedJavaType, (JNIEnv *, jobject, jobject base, jlong offset, jboolean compressed))
 313   Klass* klass = NULL;
 314   oop base_object = JNIHandles::resolve(base);
 315   jlong base_address = 0;
 316   if (base_object != NULL && offset == oopDesc::klass_offset_in_bytes()) {
 317     klass = base_object->klass();
 318   } else if (!compressed) {
 319     if (base_object != NULL) {
 320       if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 321         base_address = HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object);
 322       } else if (base_object->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 323         base_address = HotSpotConstantPool::metaspaceConstantPool(base_object);
 324       } else if (base_object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 325         base_address = (jlong) CompilerToVM::asKlass(base_object);
 326       } else if (base_object->is_a(SystemDictionary::Class_klass())) {
 327         base_address = (jlong) (address) base_object;
 328       } else {
 329         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 330                     err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", base_object->klass()->external_name(), offset, compressed ? "true" : "false"));
 331       }
 332     }
 333     klass = *((Klass**) (intptr_t) (base_address + offset));
 334   } else {
 335     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 336                 err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", base_object->klass()->external_name(), offset, compressed ? "true" : "false"));
 337   }
 338   assert (klass == NULL || klass->is_klass(), "invalid read");
 339   oop result = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 340   return JNIHandles::make_local(THREAD, result);
 341 }
 342 
 343 C2V_VMENTRY(jobject, findUniqueConcreteMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 344   ResourceMark rm;
 345   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 346   Klass* holder = CompilerToVM::asKlass(jvmci_type);
 347   if (holder->is_interface()) {
 348     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", holder->external_name()));
 349   }
 350 
 351   methodHandle ucm;
 352   {
 353     MutexLocker locker(Compile_lock);
 354     ucm = Dependencies::find_unique_concrete_method(holder, method());
 355   }
 356   oop result = CompilerToVM::get_jvmci_method(ucm, CHECK_NULL);
 357   return JNIHandles::make_local(THREAD, result);
 358 C2V_END
 359 
 360 C2V_VMENTRY(jobject, getImplementor, (JNIEnv *, jobject, jobject jvmci_type))
 361   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 362   if (!klass->is_interface()) {
 363     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 364         err_msg("Expected interface type, got %s", klass->external_name()));
 365   }
 366   InstanceKlass* iklass = InstanceKlass::cast(klass);
 367   oop implementor = CompilerToVM::get_jvmci_type(iklass->implementor(), CHECK_NULL);
 368   return JNIHandles::make_local(THREAD, implementor);
 369 C2V_END
 370 
 371 C2V_VMENTRY(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv *, jobject, jobject jvmci_method))
 372   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 373   return method->is_ignored_by_security_stack_walk();
 374 C2V_END
 375 
 376 C2V_VMENTRY(jboolean, isCompilable,(JNIEnv *, jobject, jobject jvmci_method))
 377   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 378   constantPoolHandle cp = method->constMethod()->constants();
 379   assert(!cp.is_null(), "npe");
 380   // don't inline method when constant pool contains a CONSTANT_Dynamic
 381   return !method->is_not_compilable(CompLevel_full_optimization) && !cp->has_dynamic_constant();
 382 C2V_END
 383 
 384 C2V_VMENTRY(jboolean, hasNeverInlineDirective,(JNIEnv *, jobject, jobject jvmci_method))
 385   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 386   return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
 387 C2V_END
 388 
 389 C2V_VMENTRY(jboolean, shouldInlineMethod,(JNIEnv *, jobject, jobject jvmci_method))
 390   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 391   return CompilerOracle::should_inline(method) || method->force_inline();
 392 C2V_END
 393 
 394 C2V_VMENTRY(jobject, lookupType, (JNIEnv*, jobject, jstring jname, jclass accessing_class, jboolean resolve))
 395   ResourceMark rm;
 396   Handle name(THREAD, JNIHandles::resolve(jname));
 397   Symbol* class_name = java_lang_String::as_symbol(name(), CHECK_0);
 398   if (java_lang_String::length(name()) <= 1) {
 399     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Primitive type %s should be handled in Java code", class_name->as_C_string()));
 400   }
 401 
 402   Klass* resolved_klass = NULL;
 403   if (JNIHandles::resolve(accessing_class) == NULL) {
 404     THROW_0(vmSymbols::java_lang_NullPointerException());
 405   }
 406   Klass* accessing_klass = java_lang_Class::as_Klass(JNIHandles::resolve(accessing_class));
 407   Handle class_loader(THREAD, accessing_klass->class_loader());
 408   Handle protection_domain(THREAD, accessing_klass->protection_domain());
 409 
 410   if (resolve) {
 411     resolved_klass = SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK_0);
 412   } else {
 413     if (class_name->byte_at(0) == 'L' &&
 414       class_name->byte_at(class_name->utf8_length()-1) == ';') {
 415       // This is a name from a signature.  Strip off the trimmings.
 416       // Call recursive to keep scope of strippedsym.
 417       TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1,
 418                                                           class_name->utf8_length()-2,
 419                                                           CHECK_0);
 420       resolved_klass = SystemDictionary::find(strippedsym, class_loader, protection_domain, CHECK_0);
 421     } else if (FieldType::is_array(class_name)) {
 422       FieldArrayInfo fd;
 423       // dimension and object_key in FieldArrayInfo are assigned as a side-effect
 424       // of this call
 425       BasicType t = FieldType::get_array_info(class_name, fd, CHECK_0);
 426       if (t == T_OBJECT) {
 427         TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1+fd.dimension(),
 428                                                             class_name->utf8_length()-2-fd.dimension(),
 429                                                             CHECK_0);
 430         // naked oop "k" is OK here -- we assign back into it
 431         resolved_klass = SystemDictionary::find(strippedsym,
 432                                                              class_loader,
 433                                                              protection_domain,
 434                                                              CHECK_0);
 435         if (resolved_klass != NULL) {
 436           resolved_klass = resolved_klass->array_klass(fd.dimension(), CHECK_0);
 437         }
 438       } else {
 439         resolved_klass = Universe::typeArrayKlassObj(t);
 440         resolved_klass = TypeArrayKlass::cast(resolved_klass)->array_klass(fd.dimension(), CHECK_0);
 441       }
 442     }
 443   }
 444   oop result = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 445   return JNIHandles::make_local(THREAD, result);
 446 C2V_END
 447 
 448 C2V_VMENTRY(jobject, resolveConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 449   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 450   oop result = cp->resolve_constant_at(index, CHECK_NULL);
 451   return JNIHandles::make_local(THREAD, result);
 452 C2V_END
 453 
 454 C2V_VMENTRY(jobject, resolvePossiblyCachedConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 455   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 456   oop result = cp->resolve_possibly_cached_constant_at(index, CHECK_NULL);
 457   return JNIHandles::make_local(THREAD, result);
 458 C2V_END
 459 
 460 C2V_VMENTRY(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 461   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 462   return cp->name_and_type_ref_index_at(index);
 463 C2V_END
 464 
 465 C2V_VMENTRY(jobject, lookupNameInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 466   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 467   Handle sym = java_lang_String::create_from_symbol(cp->name_ref_at(which), CHECK_NULL);
 468   return JNIHandles::make_local(THREAD, sym());
 469 C2V_END
 470 
 471 C2V_VMENTRY(jobject, lookupSignatureInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 472   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 473   Handle sym = java_lang_String::create_from_symbol(cp->signature_ref_at(which), CHECK_NULL);
 474   return JNIHandles::make_local(THREAD, sym());
 475 C2V_END
 476 
 477 C2V_VMENTRY(jint, lookupKlassRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 478   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 479   return cp->klass_ref_index_at(index);
 480 C2V_END
 481 
 482 C2V_VMENTRY(jobject, resolveTypeInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 483   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 484   Klass* resolved_klass = cp->klass_at(index, CHECK_NULL);
 485   if (resolved_klass->is_instance_klass()) {
 486     InstanceKlass::cast(resolved_klass)->link_class_or_fail(THREAD);
 487   }
 488   oop klass = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 489   return JNIHandles::make_local(THREAD, klass);
 490 C2V_END
 491 
 492 C2V_VMENTRY(jobject, lookupKlassInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 493   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 494   Klass* loading_klass = cp->pool_holder();
 495   bool is_accessible = false;
 496   Klass* klass = JVMCIEnv::get_klass_by_index(cp, index, is_accessible, loading_klass);
 497   Symbol* symbol = NULL;
 498   if (klass == NULL) {
 499     symbol = cp->klass_name_at(index);
 500   }
 501   oop result_oop;
 502   if (klass != NULL) {
 503     result_oop = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 504   } else {
 505     Handle result = java_lang_String::create_from_symbol(symbol, CHECK_NULL);
 506     result_oop = result();
 507   }
 508   return JNIHandles::make_local(THREAD, result_oop);
 509 C2V_END
 510 
 511 C2V_VMENTRY(jobject, lookupAppendixInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 512   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 513   oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, index);
 514   return JNIHandles::make_local(THREAD, appendix_oop);
 515 C2V_END
 516 
 517 C2V_VMENTRY(jobject, lookupMethodInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 518   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 519   InstanceKlass* pool_holder = cp->pool_holder();
 520   Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
 521   methodHandle method = JVMCIEnv::get_method_by_index(cp, index, bc, pool_holder);
 522   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 523   return JNIHandles::make_local(THREAD, result);
 524 C2V_END
 525 
 526 C2V_VMENTRY(jint, constantPoolRemapInstructionOperandFromCache, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 527   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 528   return cp->remap_instruction_operand_from_cache(index);
 529 C2V_END
 530 
 531 C2V_VMENTRY(jobject, resolveFieldInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jobject jvmci_method, jbyte opcode, jintArray info_handle))
 532   ResourceMark rm;
 533   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 534   Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
 535   fieldDescriptor fd;
 536   LinkInfo link_info(cp, index, (jvmci_method != NULL) ? CompilerToVM::asMethod(jvmci_method) : NULL, CHECK_0);
 537   LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_0);
 538   typeArrayOop info = (typeArrayOop) JNIHandles::resolve(info_handle);
 539   if (info == NULL || info->length() != 3) {
 540     JVMCI_ERROR_NULL("info must not be null and have a length of 3");
 541   }
 542   info->int_at_put(0, fd.access_flags().as_int());
 543   info->int_at_put(1, fd.offset());
 544   info->int_at_put(2, fd.index());
 545   oop field_holder = CompilerToVM::get_jvmci_type(fd.field_holder(), CHECK_NULL);
 546   return JNIHandles::make_local(THREAD, field_holder);
 547 C2V_END
 548 
 549 C2V_VMENTRY(jint, getVtableIndexForInterfaceMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 550   ResourceMark rm;
 551   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 552   Method* method = CompilerToVM::asMethod(jvmci_method);
 553   if (klass->is_interface()) {
 554     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", klass->external_name()));
 555   }
 556   if (!method->method_holder()->is_interface()) {
 557     THROW_MSG_0(vmSymbols::java_lang_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()));
 558   }
 559   if (!InstanceKlass::cast(klass)->is_linked()) {
 560     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Class %s must be linked", klass->external_name()));
 561   }
 562   return LinkResolver::vtable_index_of_interface_method(klass, method);
 563 C2V_END
 564 
 565 C2V_VMENTRY(jobject, resolveMethod, (JNIEnv *, jobject, jobject receiver_jvmci_type, jobject jvmci_method, jobject caller_jvmci_type))
 566   Klass* recv_klass = CompilerToVM::asKlass(receiver_jvmci_type);
 567   Klass* caller_klass = CompilerToVM::asKlass(caller_jvmci_type);
 568   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 569 
 570   Klass* resolved     = method->method_holder();
 571   Symbol* h_name      = method->name();
 572   Symbol* h_signature = method->signature();
 573 
 574   if (MethodHandles::is_signature_polymorphic_method(method())) {
 575       // Signature polymorphic methods are already resolved, JVMCI just returns NULL in this case.
 576       return NULL;
 577   }
 578 
 579   LinkInfo link_info(resolved, h_name, h_signature, caller_klass);
 580   methodHandle m;
 581   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 582   // the vtable has not been setup, and the LinkResolver will fail.
 583   if (recv_klass->is_array_klass() ||
 584       (InstanceKlass::cast(recv_klass)->is_linked() && !recv_klass->is_interface())) {
 585     if (resolved->is_interface()) {
 586       m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
 587     } else {
 588       m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
 589     }
 590   }
 591 
 592   if (m.is_null()) {
 593     // Return NULL if there was a problem with lookup (uninitialized class, etc.)
 594     return NULL;
 595   }
 596 
 597   oop result = CompilerToVM::get_jvmci_method(m, CHECK_NULL);
 598   return JNIHandles::make_local(THREAD, result);
 599 C2V_END
 600 
 601 C2V_VMENTRY(jboolean, hasFinalizableSubclass,(JNIEnv *, jobject, jobject jvmci_type))
 602   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 603   assert(klass != NULL, "method must not be called for primitive types");
 604   return Dependencies::find_finalizable_subclass(klass) != NULL;
 605 C2V_END
 606 
 607 C2V_VMENTRY(jobject, getClassInitializer, (JNIEnv *, jobject, jobject jvmci_type))
 608   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 609   if (!klass->is_instance_klass()) {
 610     return NULL;
 611   }
 612   InstanceKlass* iklass = InstanceKlass::cast(klass);
 613   oop result = CompilerToVM::get_jvmci_method(iklass->class_initializer(), CHECK_NULL);
 614   return JNIHandles::make_local(THREAD, result);
 615 C2V_END
 616 
 617 C2V_VMENTRY(jlong, getMaxCallTargetOffset, (JNIEnv*, jobject, jlong addr))
 618   address target_addr = (address) addr;
 619   if (target_addr != 0x0) {
 620     int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
 621     int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
 622     return MAX2(ABS(off_low), ABS(off_high));
 623   }
 624   return -1;
 625 C2V_END
 626 
 627 C2V_VMENTRY(void, setNotInlinableOrCompilable,(JNIEnv *, jobject,  jobject jvmci_method))
 628   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 629   method->set_not_c1_compilable();
 630   method->set_not_c2_compilable();
 631   method->set_dont_inline(true);
 632 C2V_END
 633 
 634 C2V_VMENTRY(jint, installCode, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject installed_code, jobject speculation_log))
 635   ResourceMark rm;
 636   HandleMark hm;
 637   JNIHandleMark jni_hm;
 638 
 639   Handle target_handle(THREAD, JNIHandles::resolve(target));
 640   Handle compiled_code_handle(THREAD, JNIHandles::resolve(compiled_code));
 641   CodeBlob* cb = NULL;
 642   Handle installed_code_handle(THREAD, JNIHandles::resolve(installed_code));
 643   Handle speculation_log_handle(THREAD, JNIHandles::resolve(speculation_log));
 644 
 645   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK_JNI_ERR);
 646 
 647   TraceTime install_time("installCode", JVMCICompiler::codeInstallTimer());
 648   bool is_immutable_PIC = HotSpotCompiledCode::isImmutablePIC(compiled_code_handle) > 0;
 649   CodeInstaller installer(is_immutable_PIC);
 650   JVMCIEnv::CodeInstallResult result = installer.install(compiler, target_handle, compiled_code_handle, cb, installed_code_handle, speculation_log_handle, CHECK_0);
 651 
 652   if (PrintCodeCacheOnCompilation) {
 653     stringStream s;
 654     // Dump code cache  into a buffer before locking the tty,
 655     {
 656       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 657       CodeCache::print_summary(&s, false);
 658     }
 659     ttyLocker ttyl;
 660     tty->print_raw_cr(s.as_string());
 661   }
 662 
 663   if (result != JVMCIEnv::ok) {
 664     assert(cb == NULL, "should be");
 665   } else {
 666     if (installed_code_handle.not_null()) {
 667       assert(installed_code_handle->is_a(InstalledCode::klass()), "wrong type");
 668       nmethod::invalidate_installed_code(installed_code_handle, CHECK_0);
 669       {
 670         // Ensure that all updates to the InstalledCode fields are consistent.
 671         MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 672         InstalledCode::set_address(installed_code_handle, (jlong) cb);
 673         InstalledCode::set_version(installed_code_handle, InstalledCode::version(installed_code_handle) + 1);
 674         if (cb->is_nmethod()) {
 675           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->as_nmethod_or_null()->verified_entry_point());
 676         } else {
 677           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->code_begin());
 678         }
 679         if (installed_code_handle->is_a(HotSpotInstalledCode::klass())) {
 680           HotSpotInstalledCode::set_size(installed_code_handle, cb->size());
 681           HotSpotInstalledCode::set_codeStart(installed_code_handle, (jlong) cb->code_begin());
 682           HotSpotInstalledCode::set_codeSize(installed_code_handle, cb->code_size());
 683         }
 684       }
 685     }
 686   }
 687   return result;
 688 C2V_END
 689 
 690 C2V_VMENTRY(jint, getMetadata, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject metadata))
 691   ResourceMark rm;
 692   HandleMark hm;
 693 
 694   Handle target_handle(THREAD, JNIHandles::resolve(target));
 695   Handle compiled_code_handle(THREAD, JNIHandles::resolve(compiled_code));
 696   Handle metadata_handle(THREAD, JNIHandles::resolve(metadata));
 697 
 698   CodeMetadata code_metadata;
 699   CodeBlob *cb = NULL;
 700   CodeInstaller installer(true /* immutable PIC compilation */);
 701 
 702   JVMCIEnv::CodeInstallResult result = installer.gather_metadata(target_handle, compiled_code_handle, code_metadata, CHECK_0);
 703   if (result != JVMCIEnv::ok) {
 704     return result;
 705   }
 706 
 707   if (code_metadata.get_nr_pc_desc() > 0) {
 708     typeArrayHandle pcArrayOop = oopFactory::new_byteArray_handle(sizeof(PcDesc) * code_metadata.get_nr_pc_desc(), CHECK_(JVMCIEnv::cache_full));
 709     memcpy(pcArrayOop->byte_at_addr(0), code_metadata.get_pc_desc(), sizeof(PcDesc) * code_metadata.get_nr_pc_desc());
 710     HotSpotMetaData::set_pcDescBytes(metadata_handle, pcArrayOop());
 711   }
 712 
 713   if (code_metadata.get_scopes_size() > 0) {
 714     typeArrayHandle scopesArrayOop = oopFactory::new_byteArray_handle(code_metadata.get_scopes_size(), CHECK_(JVMCIEnv::cache_full));
 715     memcpy(scopesArrayOop->byte_at_addr(0), code_metadata.get_scopes_desc(), code_metadata.get_scopes_size());
 716     HotSpotMetaData::set_scopesDescBytes(metadata_handle, scopesArrayOop());
 717   }
 718 
 719   RelocBuffer* reloc_buffer = code_metadata.get_reloc_buffer();
 720   typeArrayHandle relocArrayOop = oopFactory::new_byteArray_handle((int) reloc_buffer->size(), CHECK_(JVMCIEnv::cache_full));
 721   if (reloc_buffer->size() > 0) {
 722     memcpy(relocArrayOop->byte_at_addr(0), reloc_buffer->begin(), reloc_buffer->size());
 723   }
 724   HotSpotMetaData::set_relocBytes(metadata_handle, relocArrayOop());
 725 
 726   const OopMapSet* oopMapSet = installer.oopMapSet();
 727   {
 728     ResourceMark mark;
 729     ImmutableOopMapBuilder builder(oopMapSet);
 730     int oopmap_size = builder.heap_size();
 731     typeArrayHandle oopMapArrayHandle = oopFactory::new_byteArray_handle(oopmap_size, CHECK_(JVMCIEnv::cache_full));
 732     builder.generate_into((address) oopMapArrayHandle->byte_at_addr(0));
 733     HotSpotMetaData::set_oopMaps(metadata_handle, oopMapArrayHandle());
 734   }
 735 
 736   AOTOopRecorder* recorder = code_metadata.get_oop_recorder();
 737 
 738   int nr_meta_refs = recorder->nr_meta_refs();
 739   objArrayOop metadataArray = oopFactory::new_objectArray(nr_meta_refs, CHECK_(JVMCIEnv::cache_full));
 740   objArrayHandle metadataArrayHandle(THREAD, metadataArray);
 741   for (int i = 0; i < nr_meta_refs; ++i) {
 742     jobject element = recorder->meta_element(i);
 743     if (element == NULL) {
 744       return JVMCIEnv::cache_full;
 745     }
 746     metadataArrayHandle->obj_at_put(i, JNIHandles::resolve(element));
 747   }
 748   HotSpotMetaData::set_metadata(metadata_handle, metadataArrayHandle());
 749 
 750   ExceptionHandlerTable* handler = code_metadata.get_exception_table();
 751   int table_size = handler->size_in_bytes();
 752   typeArrayHandle exceptionArrayOop = oopFactory::new_byteArray_handle(table_size, CHECK_(JVMCIEnv::cache_full));
 753 
 754   if (table_size > 0) {
 755     handler->copy_bytes_to((address) exceptionArrayOop->byte_at_addr(0));
 756   }
 757   HotSpotMetaData::set_exceptionBytes(metadata_handle, exceptionArrayOop());
 758 
 759   return result;
 760 C2V_END
 761 
 762 C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv *jniEnv, jobject))
 763   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK);
 764   CompilerStatistics* stats = compiler->stats();
 765   stats->_standard.reset();
 766   stats->_osr.reset();
 767 C2V_END
 768 
 769 C2V_VMENTRY(jobject, disassembleCodeBlob, (JNIEnv *jniEnv, jobject, jobject installedCode))
 770   ResourceMark rm;
 771   HandleMark hm;
 772 
 773   if (installedCode == NULL) {
 774     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), "installedCode is null");
 775   }
 776 
 777   jlong codeBlob = InstalledCode::address(installedCode);
 778   if (codeBlob == 0L) {
 779     return NULL;
 780   }
 781 
 782   CodeBlob* cb = (CodeBlob*) (address) codeBlob;
 783   if (cb == NULL) {
 784     return NULL;
 785   }
 786 
 787   // We don't want the stringStream buffer to resize during disassembly as it
 788   // uses scoped resource memory. If a nested function called during disassembly uses
 789   // a ResourceMark and the buffer expands within the scope of the mark,
 790   // the buffer becomes garbage when that scope is exited. Experience shows that
 791   // the disassembled code is typically about 10x the code size so a fixed buffer
 792   // sized to 20x code size plus a fixed amount for header info should be sufficient.
 793   int bufferSize = cb->code_size() * 20 + 1024;
 794   char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
 795   stringStream st(buffer, bufferSize);
 796   if (cb->is_nmethod()) {
 797     nmethod* nm = (nmethod*) cb;
 798     if (!nm->is_alive()) {
 799       return NULL;
 800     }
 801   }
 802   Disassembler::decode(cb, &st);
 803   if (st.size() <= 0) {
 804     return NULL;
 805   }
 806 
 807   Handle result = java_lang_String::create_from_platform_dependent_str(st.as_string(), CHECK_NULL);
 808   return JNIHandles::make_local(THREAD, result());
 809 C2V_END
 810 
 811 C2V_VMENTRY(jobject, getStackTraceElement, (JNIEnv*, jobject, jobject jvmci_method, int bci))
 812   ResourceMark rm;
 813   HandleMark hm;
 814 
 815   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 816   oop element = java_lang_StackTraceElement::create(method, bci, CHECK_NULL);
 817   return JNIHandles::make_local(THREAD, element);
 818 C2V_END
 819 
 820 C2V_VMENTRY(jobject, executeInstalledCode, (JNIEnv*, jobject, jobject args, jobject hotspotInstalledCode))
 821   ResourceMark rm;
 822   HandleMark hm;
 823 
 824   jlong nmethodValue = InstalledCode::address(hotspotInstalledCode);
 825   if (nmethodValue == 0L) {
 826     THROW_NULL(vmSymbols::jdk_vm_ci_code_InvalidInstalledCodeException());
 827   }
 828   nmethod* nm = (nmethod*) (address) nmethodValue;
 829   methodHandle mh = nm->method();
 830   Symbol* signature = mh->signature();
 831   JavaCallArguments jca(mh->size_of_parameters());
 832 
 833   JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
 834   JavaValue result(jap.get_ret_type());
 835   jca.set_alternative_target(nm);
 836   JavaCalls::call(&result, mh, &jca, CHECK_NULL);
 837 
 838   if (jap.get_ret_type() == T_VOID) {
 839     return NULL;
 840   } else if (jap.get_ret_type() == T_OBJECT || jap.get_ret_type() == T_ARRAY) {
 841     return JNIHandles::make_local(THREAD, (oop) result.get_jobject());
 842   } else {
 843     jvalue *value = (jvalue *) result.get_value_addr();
 844     // Narrow the value down if required (Important on big endian machines)
 845     switch (jap.get_ret_type()) {
 846       case T_BOOLEAN:
 847        value->z = (jboolean) value->i;
 848        break;
 849       case T_BYTE:
 850        value->b = (jbyte) value->i;
 851        break;
 852       case T_CHAR:
 853        value->c = (jchar) value->i;
 854        break;
 855       case T_SHORT:
 856        value->s = (jshort) value->i;
 857        break;
 858       default:
 859         break;
 860     }
 861     oop o = java_lang_boxing_object::create(jap.get_ret_type(), value, CHECK_NULL);
 862     return JNIHandles::make_local(THREAD, o);
 863   }
 864 C2V_END
 865 
 866 C2V_VMENTRY(jlongArray, getLineNumberTable, (JNIEnv *, jobject, jobject jvmci_method))
 867   Method* method = CompilerToVM::asMethod(jvmci_method);
 868   if (!method->has_linenumber_table()) {
 869     return NULL;
 870   }
 871   u2 num_entries = 0;
 872   CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
 873   while (streamForSize.read_pair()) {
 874     num_entries++;
 875   }
 876 
 877   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
 878   typeArrayOop result = oopFactory::new_longArray(2 * num_entries, CHECK_NULL);
 879 
 880   int i = 0;
 881   jlong value;
 882   while (stream.read_pair()) {
 883     value = ((long) stream.bci());
 884     result->long_at_put(i, value);
 885     value = ((long) stream.line());
 886     result->long_at_put(i + 1, value);
 887     i += 2;
 888   }
 889 
 890   return (jlongArray) JNIHandles::make_local(THREAD, result);
 891 C2V_END
 892 
 893 C2V_VMENTRY(jlong, getLocalVariableTableStart, (JNIEnv *, jobject, jobject jvmci_method))
 894   ResourceMark rm;
 895   Method* method = CompilerToVM::asMethod(jvmci_method);
 896   if (!method->has_localvariable_table()) {
 897     return 0;
 898   }
 899   return (jlong) (address) method->localvariable_table_start();
 900 C2V_END
 901 
 902 C2V_VMENTRY(jint, getLocalVariableTableLength, (JNIEnv *, jobject, jobject jvmci_method))
 903   ResourceMark rm;
 904   Method* method = CompilerToVM::asMethod(jvmci_method);
 905   return method->localvariable_table_length();
 906 C2V_END
 907 
 908 C2V_VMENTRY(void, reprofile, (JNIEnv*, jobject, jobject jvmci_method))
 909   Method* method = CompilerToVM::asMethod(jvmci_method);
 910   MethodCounters* mcs = method->method_counters();
 911   if (mcs != NULL) {
 912     mcs->clear_counters();
 913   }
 914   NOT_PRODUCT(method->set_compiled_invocation_count(0));
 915 
 916   CompiledMethod* code = method->code();
 917   if (code != NULL) {
 918     code->make_not_entrant();
 919   }
 920 
 921   MethodData* method_data = method->method_data();
 922   if (method_data == NULL) {
 923     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 924     method_data = MethodData::allocate(loader_data, method, CHECK);
 925     method->set_method_data(method_data);
 926   } else {
 927     method_data->initialize();
 928   }
 929 C2V_END
 930 
 931 
 932 C2V_VMENTRY(void, invalidateInstalledCode, (JNIEnv*, jobject, jobject installed_code))
 933   Handle installed_code_handle(THREAD, JNIHandles::resolve(installed_code));
 934   nmethod::invalidate_installed_code(installed_code_handle, CHECK);
 935 C2V_END
 936 
 937 C2V_VMENTRY(jlongArray, collectCounters, (JNIEnv*, jobject))
 938   typeArrayOop arrayOop = oopFactory::new_longArray(JVMCICounterSize, CHECK_NULL);
 939   JavaThread::collect_counters(arrayOop);
 940   return (jlongArray) JNIHandles::make_local(THREAD, arrayOop);
 941 C2V_END
 942 
 943 C2V_VMENTRY(int, allocateCompileId, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci))
 944   HandleMark hm;
 945   ResourceMark rm;
 946   if (JNIHandles::resolve(jvmci_method) == NULL) {
 947     THROW_0(vmSymbols::java_lang_NullPointerException());
 948   }
 949   Method* method = CompilerToVM::asMethod(jvmci_method);
 950   if (entry_bci >= method->code_size() || entry_bci < -1) {
 951     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Unexpected bci %d", entry_bci));
 952   }
 953   return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
 954 C2V_END
 955 
 956 
 957 C2V_VMENTRY(jboolean, isMature, (JNIEnv*, jobject, jlong metaspace_method_data))
 958   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
 959   return mdo != NULL && mdo->is_mature();
 960 C2V_END
 961 
 962 C2V_VMENTRY(jboolean, hasCompiledCodeForOSR, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci, int comp_level))
 963   Method* method = CompilerToVM::asMethod(jvmci_method);
 964   return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != NULL;
 965 C2V_END
 966 
 967 C2V_VMENTRY(jobject, getSymbol, (JNIEnv*, jobject, jlong symbol))
 968   Handle sym = java_lang_String::create_from_symbol((Symbol*)(address)symbol, CHECK_NULL);
 969   return JNIHandles::make_local(THREAD, sym());
 970 C2V_END
 971 
 972 bool matches(jobjectArray methods, Method* method) {
 973   objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
 974 
 975   for (int i = 0; i < methods_oop->length(); i++) {
 976     oop resolved = methods_oop->obj_at(i);
 977     if (resolved->is_a(HotSpotResolvedJavaMethodImpl::klass()) && CompilerToVM::asMethod(resolved) == method) {
 978       return true;
 979     }
 980   }
 981   return false;
 982 }
 983 
 984 void call_interface(JavaValue* result, Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
 985   CallInfo callinfo;
 986   Handle receiver = args->receiver();
 987   Klass* recvrKlass = receiver.is_null() ? (Klass*)NULL : receiver->klass();
 988   LinkInfo link_info(spec_klass, name, signature);
 989   LinkResolver::resolve_interface_call(
 990           callinfo, receiver, recvrKlass, link_info, true, CHECK);
 991   methodHandle method = callinfo.selected_method();
 992   assert(method.not_null(), "should have thrown exception");
 993 
 994   // Invoke the method
 995   JavaCalls::call(result, method, args, CHECK);
 996 }
 997 
 998 C2V_VMENTRY(jobject, iterateFrames, (JNIEnv*, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
 999   ResourceMark rm;
1000 
1001   if (!thread->has_last_Java_frame()) {
1002     return NULL;
1003   }
1004   Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
1005   Handle frame_reference = HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1006   HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1007 
1008   StackFrameStream fst(thread);
1009 
1010   jobjectArray methods = initial_methods;
1011 
1012   int frame_number = 0;
1013   vframe* vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1014 
1015   while (true) {
1016     // look for the given method
1017     bool realloc_called = false;
1018     while (true) {
1019       StackValueCollection* locals = NULL;
1020       if (vf->is_compiled_frame()) {
1021         // compiled method frame
1022         compiledVFrame* cvf = compiledVFrame::cast(vf);
1023         if (methods == NULL || matches(methods, cvf->method())) {
1024           if (initialSkip > 0) {
1025             initialSkip--;
1026           } else {
1027             ScopeDesc* scope = cvf->scope();
1028             // native wrappers do not have a scope
1029             if (scope != NULL && scope->objects() != NULL) {
1030               GrowableArray<ScopeValue*>* objects;
1031               if (!realloc_called) {
1032                 objects = scope->objects();
1033               } else {
1034                 // some object might already have been re-allocated, only reallocate the non-allocated ones
1035                 objects = new GrowableArray<ScopeValue*>(scope->objects()->length());
1036                 int ii = 0;
1037                 for (int i = 0; i < scope->objects()->length(); i++) {
1038                   ObjectValue* sv = (ObjectValue*) scope->objects()->at(i);
1039                   if (sv->value().is_null()) {
1040                     objects->at_put(ii++, sv);
1041                   }
1042                 }
1043               }
1044               bool realloc_failures = Deoptimization::realloc_objects(thread, fst.current(), objects, CHECK_NULL);
1045               Deoptimization::reassign_fields(fst.current(), fst.register_map(), objects, realloc_failures, false);
1046               realloc_called = true;
1047 
1048               GrowableArray<ScopeValue*>* local_values = scope->locals();
1049               assert(local_values != NULL, "NULL locals");
1050               typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
1051               typeArrayHandle array(THREAD, array_oop);
1052               for (int i = 0; i < local_values->length(); i++) {
1053                 ScopeValue* value = local_values->at(i);
1054                 if (value->is_object()) {
1055                   array->bool_at_put(i, true);
1056                 }
1057               }
1058               HotSpotStackFrameReference::set_localIsVirtual(frame_reference, array());
1059             } else {
1060               HotSpotStackFrameReference::set_localIsVirtual(frame_reference, NULL);
1061             }
1062 
1063             locals = cvf->locals();
1064             HotSpotStackFrameReference::set_bci(frame_reference, cvf->bci());
1065             oop method = CompilerToVM::get_jvmci_method(cvf->method(), CHECK_NULL);
1066             HotSpotStackFrameReference::set_method(frame_reference, method);
1067           }
1068         }
1069       } else if (vf->is_interpreted_frame()) {
1070         // interpreted method frame
1071         interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1072         if (methods == NULL || matches(methods, ivf->method())) {
1073           if (initialSkip > 0) {
1074             initialSkip--;
1075           } else {
1076             locals = ivf->locals();
1077             HotSpotStackFrameReference::set_bci(frame_reference, ivf->bci());
1078             oop method = CompilerToVM::get_jvmci_method(ivf->method(), CHECK_NULL);
1079             HotSpotStackFrameReference::set_method(frame_reference, method);
1080             HotSpotStackFrameReference::set_localIsVirtual(frame_reference, NULL);
1081           }
1082         }
1083       }
1084 
1085       // locals != NULL means that we found a matching frame and result is already partially initialized
1086       if (locals != NULL) {
1087         methods = match_methods;
1088         HotSpotStackFrameReference::set_compilerToVM(frame_reference, JNIHandles::resolve(compilerToVM));
1089         HotSpotStackFrameReference::set_stackPointer(frame_reference, (jlong) fst.current()->sp());
1090         HotSpotStackFrameReference::set_frameNumber(frame_reference, frame_number);
1091 
1092         // initialize the locals array
1093         objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
1094         objArrayHandle array(THREAD, array_oop);
1095         for (int i = 0; i < locals->size(); i++) {
1096           StackValue* var = locals->at(i);
1097           if (var->type() == T_OBJECT) {
1098             array->obj_at_put(i, locals->at(i)->get_obj()());
1099           }
1100         }
1101         HotSpotStackFrameReference::set_locals(frame_reference, array());
1102         HotSpotStackFrameReference::set_objectsMaterialized(frame_reference, JNI_FALSE);
1103 
1104         JavaValue result(T_OBJECT);
1105         JavaCallArguments args(visitor);
1106         args.push_oop(frame_reference);
1107         call_interface(&result, SystemDictionary::InspectedFrameVisitor_klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
1108         if (result.get_jobject() != NULL) {
1109           return JNIHandles::make_local(thread, (oop) result.get_jobject());
1110         }
1111         assert(initialSkip == 0, "There should be no match before initialSkip == 0");
1112         if (HotSpotStackFrameReference::objectsMaterialized(frame_reference) == JNI_TRUE) {
1113           // the frame has been deoptimized, we need to re-synchronize the frame and vframe
1114           intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(frame_reference);
1115           fst = StackFrameStream(thread);
1116           while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1117             fst.next();
1118           }
1119           if (fst.current()->sp() != stack_pointer) {
1120             THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1121           }
1122           vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1123           if (!vf->is_compiled_frame()) {
1124             THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1125           }
1126           for (int i = 0; i < frame_number; i++) {
1127             if (vf->is_top()) {
1128               THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
1129             }
1130             vf = vf->sender();
1131             assert(vf->is_compiled_frame(), "Wrong frame type");
1132           }
1133         }
1134         frame_reference = HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1135         HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1136       }
1137 
1138       if (vf->is_top()) {
1139         break;
1140       }
1141       frame_number++;
1142       vf = vf->sender();
1143     } // end of vframe loop
1144 
1145     if (fst.is_done()) {
1146       break;
1147     }
1148     fst.next();
1149     vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1150     frame_number = 0;
1151   } // end of frame loop
1152 
1153   // the end was reached without finding a matching method
1154   return NULL;
1155 C2V_END
1156 
1157 C2V_VMENTRY(void, resolveInvokeDynamicInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1158   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1159   CallInfo callInfo;
1160   LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokedynamic, CHECK);
1161   ConstantPoolCacheEntry* cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(index);
1162   cp_cache_entry->set_dynamic_call(cp, callInfo);
1163 C2V_END
1164 
1165 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1166   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1167   Klass* holder = cp->klass_ref_at(index, CHECK);
1168   Symbol* name = cp->name_ref_at(index);
1169   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1170     CallInfo callInfo;
1171     LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1172     ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1173     cp_cache_entry->set_method_handle(cp, callInfo);
1174   }
1175 C2V_END
1176 
1177 C2V_VMENTRY(jint, isResolvedInvokeHandleInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1178   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1179   ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1180   if (cp_cache_entry->is_resolved(Bytecodes::_invokehandle)) {
1181     // MethodHandle.invoke* --> LambdaForm?
1182     ResourceMark rm;
1183 
1184     LinkInfo link_info(cp, index, CATCH);
1185 
1186     Klass* resolved_klass = link_info.resolved_klass();
1187 
1188     Symbol* name_sym = cp->name_ref_at(index);
1189 
1190     vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
1191     vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
1192 
1193     methodHandle adapter_method(cp_cache_entry->f1_as_method());
1194 
1195     methodHandle resolved_method(adapter_method);
1196 
1197     // Can we treat it as a regular invokevirtual?
1198     if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
1199       vmassert(!resolved_method->is_static(),"!");
1200       vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
1201       vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
1202       vmassert(cp_cache_entry->appendix_if_resolved(cp) == NULL, "!");
1203       vmassert(cp_cache_entry->method_type_if_resolved(cp) == NULL, "!");
1204 
1205       methodHandle m(LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
1206       vmassert(m == resolved_method, "!!");
1207       return -1;
1208     }
1209 
1210     return Bytecodes::_invokevirtual;
1211   }
1212   if (cp_cache_entry->is_resolved(Bytecodes::_invokedynamic)) {
1213     return Bytecodes::_invokedynamic;
1214   }
1215   return -1;
1216 C2V_END
1217 
1218 
1219 C2V_VMENTRY(jobject, getSignaturePolymorphicHolders, (JNIEnv*, jobject))
1220   objArrayHandle holders = oopFactory::new_objArray_handle(SystemDictionary::String_klass(), 2, CHECK_NULL);
1221   Handle mh = java_lang_String::create_from_str("Ljava/lang/invoke/MethodHandle;", CHECK_NULL);
1222   Handle vh = java_lang_String::create_from_str("Ljava/lang/invoke/VarHandle;", CHECK_NULL);
1223   holders->obj_at_put(0, mh());
1224   holders->obj_at_put(1, vh());
1225   return JNIHandles::make_local(THREAD, holders());
1226 C2V_END
1227 
1228 C2V_VMENTRY(jboolean, shouldDebugNonSafepoints, (JNIEnv*, jobject))
1229   //see compute_recording_non_safepoints in debugInfroRec.cpp
1230   if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1231     return true;
1232   }
1233   return DebugNonSafepoints;
1234 C2V_END
1235 
1236 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1237 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv*, jobject, jobject hs_frame, bool invalidate))
1238   ResourceMark rm;
1239 
1240   if (hs_frame == NULL) {
1241     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "stack frame is null")
1242   }
1243 
1244   HotSpotStackFrameReference::klass()->initialize(CHECK);
1245 
1246   // look for the given stack frame
1247   StackFrameStream fst(thread);
1248   intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(hs_frame);
1249   while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1250     fst.next();
1251   }
1252   if (fst.current()->sp() != stack_pointer) {
1253     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found")
1254   }
1255 
1256   if (invalidate) {
1257     if (!fst.current()->is_compiled_frame()) {
1258       THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1259     }
1260     assert(fst.current()->cb()->is_nmethod(), "nmethod expected");
1261     ((nmethod*) fst.current()->cb())->make_not_entrant();
1262   }
1263   Deoptimization::deoptimize(thread, *fst.current(), fst.register_map(), Deoptimization::Reason_none);
1264   // look for the frame again as it has been updated by deopt (pc, deopt state...)
1265   StackFrameStream fstAfterDeopt(thread);
1266   while (fstAfterDeopt.current()->sp() != stack_pointer && !fstAfterDeopt.is_done()) {
1267     fstAfterDeopt.next();
1268   }
1269   if (fstAfterDeopt.current()->sp() != stack_pointer) {
1270     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1271   }
1272 
1273   vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1274   if (!vf->is_compiled_frame()) {
1275     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1276   }
1277 
1278   GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1279   while (true) {
1280     assert(vf->is_compiled_frame(), "Wrong frame type");
1281     virtualFrames->push(compiledVFrame::cast(vf));
1282     if (vf->is_top()) {
1283       break;
1284     }
1285     vf = vf->sender();
1286   }
1287 
1288   int last_frame_number = HotSpotStackFrameReference::frameNumber(hs_frame);
1289   if (last_frame_number >= virtualFrames->length()) {
1290     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "invalid frame number")
1291   }
1292 
1293   // Reallocate the non-escaping objects and restore their fields.
1294   assert (virtualFrames->at(last_frame_number)->scope() != NULL,"invalid scope");
1295   GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1296 
1297   if (objects == NULL) {
1298     // no objects to materialize
1299     return;
1300   }
1301 
1302   bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), objects, CHECK);
1303   Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
1304 
1305   for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1306     compiledVFrame* cvf = virtualFrames->at(frame_index);
1307 
1308     GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
1309     StackValueCollection* locals = cvf->locals();
1310     if (locals != NULL) {
1311       for (int i2 = 0; i2 < locals->size(); i2++) {
1312         StackValue* var = locals->at(i2);
1313         if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) {
1314           jvalue val;
1315           val.l = (jobject) locals->at(i2)->get_obj()();
1316           cvf->update_local(T_OBJECT, i2, val);
1317         }
1318       }
1319     }
1320 
1321     GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
1322     StackValueCollection* expressions = cvf->expressions();
1323     if (expressions != NULL) {
1324       for (int i2 = 0; i2 < expressions->size(); i2++) {
1325         StackValue* var = expressions->at(i2);
1326         if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
1327           jvalue val;
1328           val.l = (jobject) expressions->at(i2)->get_obj()();
1329           cvf->update_stack(T_OBJECT, i2, val);
1330         }
1331       }
1332     }
1333 
1334     GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
1335     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1336     if (monitors != NULL) {
1337       for (int i2 = 0; i2 < monitors->length(); i2++) {
1338         cvf->update_monitor(i2, monitors->at(i2));
1339       }
1340     }
1341   }
1342 
1343   // all locals are materialized by now
1344   HotSpotStackFrameReference::set_localIsVirtual(hs_frame, NULL);
1345 
1346   // update the locals array
1347   objArrayHandle array(THREAD, HotSpotStackFrameReference::locals(hs_frame));
1348   StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1349   for (int i = 0; i < locals->size(); i++) {
1350     StackValue* var = locals->at(i);
1351     if (var->type() == T_OBJECT) {
1352       array->obj_at_put(i, locals->at(i)->get_obj()());
1353     }
1354   }
1355   HotSpotStackFrameReference::set_objectsMaterialized(hs_frame, JNI_TRUE);
1356 C2V_END
1357 
1358 C2V_VMENTRY(void, writeDebugOutput, (JNIEnv*, jobject, jbyteArray bytes, jint offset, jint length))
1359   if (bytes == NULL) {
1360     THROW(vmSymbols::java_lang_NullPointerException());
1361   }
1362   typeArrayOop array = (typeArrayOop) JNIHandles::resolve(bytes);
1363 
1364   // Check if offset and length are non negative.
1365   if (offset < 0 || length < 0) {
1366     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1367   }
1368   // Check if the range is valid.
1369   if ((((unsigned int) length + (unsigned int) offset) > (unsigned int) array->length())) {
1370     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1371   }
1372   while (length > 0) {
1373     jbyte* start = array->byte_at_addr(offset);
1374     tty->write((char*) start, MIN2(length, (jint)O_BUFLEN));
1375     length -= O_BUFLEN;
1376     offset += O_BUFLEN;
1377   }
1378 C2V_END
1379 
1380 C2V_VMENTRY(void, flushDebugOutput, (JNIEnv*, jobject))
1381   tty->flush();
1382 C2V_END
1383 
1384 C2V_VMENTRY(int, methodDataProfileDataSize, (JNIEnv*, jobject, jlong metaspace_method_data, jint position))
1385   ResourceMark rm;
1386   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
1387   ProfileData* profile_data = mdo->data_at(position);
1388   if (mdo->is_valid(profile_data)) {
1389     return profile_data->size_in_bytes();
1390   }
1391   DataLayout* data    = mdo->extra_data_base();
1392   DataLayout* end   = mdo->extra_data_limit();
1393   for (;; data = mdo->next_extra(data)) {
1394     assert(data < end, "moved past end of extra data");
1395     profile_data = data->data_in();
1396     if (mdo->dp_to_di(profile_data->dp()) == position) {
1397       return profile_data->size_in_bytes();
1398     }
1399   }
1400   THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Invalid profile data position %d", position));
1401 C2V_END
1402 
1403 C2V_VMENTRY(jlong, getFingerprint, (JNIEnv*, jobject, jlong metaspace_klass))
1404   Klass *k = CompilerToVM::asKlass(metaspace_klass);
1405   if (k->is_instance_klass()) {
1406     return InstanceKlass::cast(k)->get_stored_fingerprint();
1407   } else {
1408     return 0;
1409   }
1410 C2V_END
1411 
1412 C2V_VMENTRY(jobject, getHostClass, (JNIEnv*, jobject, jobject jvmci_type))
1413   InstanceKlass* k = InstanceKlass::cast(CompilerToVM::asKlass(jvmci_type));
1414   InstanceKlass* host = k->host_klass();
1415   oop result = CompilerToVM::get_jvmci_type(host, CHECK_NULL);
1416   return JNIHandles::make_local(THREAD, result);
1417 C2V_END
1418 
1419 C2V_VMENTRY(int, interpreterFrameSize, (JNIEnv*, jobject, jobject bytecode_frame_handle))
1420   if (bytecode_frame_handle == NULL) {
1421     THROW_0(vmSymbols::java_lang_NullPointerException());
1422   }
1423 
1424   oop top_bytecode_frame = JNIHandles::resolve_non_null(bytecode_frame_handle);
1425   oop bytecode_frame = top_bytecode_frame;
1426   int size = 0;
1427   int callee_parameters = 0;
1428   int callee_locals = 0;
1429   Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1430   int extra_args = method->max_stack() - BytecodeFrame::numStack(bytecode_frame);
1431 
1432   while (bytecode_frame != NULL) {
1433     int locks = BytecodeFrame::numLocks(bytecode_frame);
1434     int temps = BytecodeFrame::numStack(bytecode_frame);
1435     bool is_top_frame = (bytecode_frame == top_bytecode_frame);
1436     Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1437 
1438     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
1439                                                                  temps + callee_parameters,
1440                                                                  extra_args,
1441                                                                  locks,
1442                                                                  callee_parameters,
1443                                                                  callee_locals,
1444                                                                  is_top_frame);
1445     size += frame_size;
1446 
1447     callee_parameters = method->size_of_parameters();
1448     callee_locals = method->max_locals();
1449     extra_args = 0;
1450     bytecode_frame = BytecodePosition::caller(bytecode_frame);
1451   }
1452   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
1453 C2V_END
1454 
1455 C2V_VMENTRY(void, compileToBytecode, (JNIEnv*, jobject, jobject lambda_form_handle))
1456   Handle lambda_form(THREAD, JNIHandles::resolve_non_null(lambda_form_handle));
1457   if (lambda_form->is_a(SystemDictionary::LambdaForm_klass())) {
1458     TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode", CHECK);
1459     JavaValue result(T_VOID);
1460     JavaCalls::call_special(&result, lambda_form, SystemDictionary::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
1461   } else {
1462     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1463                 err_msg("Unexpected type: %s", lambda_form->klass()->external_name()));
1464   }
1465 C2V_END
1466 
1467 #define CC (char*)  /*cast a literal from (const char*)*/
1468 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
1469 
1470 #define STRING                  "Ljava/lang/String;"
1471 #define OBJECT                  "Ljava/lang/Object;"
1472 #define CLASS                   "Ljava/lang/Class;"
1473 #define EXECUTABLE              "Ljava/lang/reflect/Executable;"
1474 #define STACK_TRACE_ELEMENT     "Ljava/lang/StackTraceElement;"
1475 #define INSTALLED_CODE          "Ljdk/vm/ci/code/InstalledCode;"
1476 #define TARGET_DESCRIPTION      "Ljdk/vm/ci/code/TargetDescription;"
1477 #define BYTECODE_FRAME          "Ljdk/vm/ci/code/BytecodeFrame;"
1478 #define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
1479 #define RESOLVED_METHOD         "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
1480 #define HS_RESOLVED_METHOD      "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
1481 #define HS_RESOLVED_KLASS       "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
1482 #define HS_CONSTANT_POOL        "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
1483 #define HS_COMPILED_CODE        "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
1484 #define HS_CONFIG               "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
1485 #define HS_METADATA             "Ljdk/vm/ci/hotspot/HotSpotMetaData;"
1486 #define HS_STACK_FRAME_REF      "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
1487 #define HS_SPECULATION_LOG      "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
1488 #define METASPACE_METHOD_DATA   "J"
1489 
1490 JNINativeMethod CompilerToVM::methods[] = {
1491   {CC "getBytecode",                                  CC "(" HS_RESOLVED_METHOD ")[B",                                                      FN_PTR(getBytecode)},
1492   {CC "getExceptionTableStart",                       CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getExceptionTableStart)},
1493   {CC "getExceptionTableLength",                      CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getExceptionTableLength)},
1494   {CC "findUniqueConcreteMethod",                     CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")" HS_RESOLVED_METHOD,                   FN_PTR(findUniqueConcreteMethod)},
1495   {CC "getImplementor",                               CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS,                                       FN_PTR(getImplementor)},
1496   {CC "getStackTraceElement",                         CC "(" HS_RESOLVED_METHOD "I)" STACK_TRACE_ELEMENT,                                   FN_PTR(getStackTraceElement)},
1497   {CC "methodIsIgnoredBySecurityStackWalk",           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(methodIsIgnoredBySecurityStackWalk)},
1498   {CC "setNotInlinableOrCompilable",                  CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(setNotInlinableOrCompilable)},
1499   {CC "isCompilable",                                 CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(isCompilable)},
1500   {CC "hasNeverInlineDirective",                      CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(hasNeverInlineDirective)},
1501   {CC "shouldInlineMethod",                           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(shouldInlineMethod)},
1502   {CC "lookupType",                                   CC "(" STRING CLASS "Z)" HS_RESOLVED_KLASS,                                           FN_PTR(lookupType)},
1503   {CC "lookupNameInPool",                             CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupNameInPool)},
1504   {CC "lookupNameAndTypeRefIndexInPool",              CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupNameAndTypeRefIndexInPool)},
1505   {CC "lookupSignatureInPool",                        CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupSignatureInPool)},
1506   {CC "lookupKlassRefIndexInPool",                    CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupKlassRefIndexInPool)},
1507   {CC "lookupKlassInPool",                            CC "(" HS_CONSTANT_POOL "I)Ljava/lang/Object;",                                       FN_PTR(lookupKlassInPool)},
1508   {CC "lookupAppendixInPool",                         CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(lookupAppendixInPool)},
1509   {CC "lookupMethodInPool",                           CC "(" HS_CONSTANT_POOL "IB)" HS_RESOLVED_METHOD,                                     FN_PTR(lookupMethodInPool)},
1510   {CC "constantPoolRemapInstructionOperandFromCache", CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(constantPoolRemapInstructionOperandFromCache)},
1511   {CC "resolveConstantInPool",                        CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolveConstantInPool)},
1512   {CC "resolvePossiblyCachedConstantInPool",          CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolvePossiblyCachedConstantInPool)},
1513   {CC "resolveTypeInPool",                            CC "(" HS_CONSTANT_POOL "I)" HS_RESOLVED_KLASS,                                       FN_PTR(resolveTypeInPool)},
1514   {CC "resolveFieldInPool",                           CC "(" HS_CONSTANT_POOL "I" HS_RESOLVED_METHOD "B[I)" HS_RESOLVED_KLASS,              FN_PTR(resolveFieldInPool)},
1515   {CC "resolveInvokeDynamicInPool",                   CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeDynamicInPool)},
1516   {CC "resolveInvokeHandleInPool",                    CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeHandleInPool)},
1517   {CC "isResolvedInvokeHandleInPool",                 CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(isResolvedInvokeHandleInPool)},
1518   {CC "resolveMethod",                                CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD, FN_PTR(resolveMethod)},
1519   {CC "getSignaturePolymorphicHolders",               CC "()[" STRING,                                                                      FN_PTR(getSignaturePolymorphicHolders)},
1520   {CC "getVtableIndexForInterfaceMethod",             CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")I",                                     FN_PTR(getVtableIndexForInterfaceMethod)},
1521   {CC "getClassInitializer",                          CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD,                                      FN_PTR(getClassInitializer)},
1522   {CC "hasFinalizableSubclass",                       CC "(" HS_RESOLVED_KLASS ")Z",                                                        FN_PTR(hasFinalizableSubclass)},
1523   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
1524   {CC "asResolvedJavaMethod",                         CC "(" EXECUTABLE ")" HS_RESOLVED_METHOD,                                             FN_PTR(asResolvedJavaMethod)},
1525   {CC "getResolvedJavaMethod",                        CC "(Ljava/lang/Object;J)" HS_RESOLVED_METHOD,                                        FN_PTR(getResolvedJavaMethod)},
1526   {CC "getConstantPool",                              CC "(Ljava/lang/Object;)" HS_CONSTANT_POOL,                                           FN_PTR(getConstantPool)},
1527   {CC "getResolvedJavaType",                          CC "(Ljava/lang/Object;JZ)" HS_RESOLVED_KLASS,                                        FN_PTR(getResolvedJavaType)},
1528   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
1529   {CC "installCode",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE INSTALLED_CODE HS_SPECULATION_LOG ")I",    FN_PTR(installCode)},
1530   {CC "getMetadata",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE HS_METADATA ")I",                          FN_PTR(getMetadata)},
1531   {CC "resetCompilationStatistics",                   CC "()V",                                                                             FN_PTR(resetCompilationStatistics)},
1532   {CC "disassembleCodeBlob",                          CC "(" INSTALLED_CODE ")" STRING,                                                     FN_PTR(disassembleCodeBlob)},
1533   {CC "executeInstalledCode",                         CC "([" OBJECT INSTALLED_CODE ")" OBJECT,                                             FN_PTR(executeInstalledCode)},
1534   {CC "getLineNumberTable",                           CC "(" HS_RESOLVED_METHOD ")[J",                                                      FN_PTR(getLineNumberTable)},
1535   {CC "getLocalVariableTableStart",                   CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getLocalVariableTableStart)},
1536   {CC "getLocalVariableTableLength",                  CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getLocalVariableTableLength)},
1537   {CC "reprofile",                                    CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(reprofile)},
1538   {CC "invalidateInstalledCode",                      CC "(" INSTALLED_CODE ")V",                                                           FN_PTR(invalidateInstalledCode)},
1539   {CC "collectCounters",                              CC "()[J",                                                                            FN_PTR(collectCounters)},
1540   {CC "allocateCompileId",                            CC "(" HS_RESOLVED_METHOD "I)I",                                                      FN_PTR(allocateCompileId)},
1541   {CC "isMature",                                     CC "(" METASPACE_METHOD_DATA ")Z",                                                    FN_PTR(isMature)},
1542   {CC "hasCompiledCodeForOSR",                        CC "(" HS_RESOLVED_METHOD "II)Z",                                                     FN_PTR(hasCompiledCodeForOSR)},
1543   {CC "getSymbol",                                    CC "(J)" STRING,                                                                      FN_PTR(getSymbol)},
1544   {CC "iterateFrames",                                CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT,   FN_PTR(iterateFrames)},
1545   {CC "materializeVirtualObjects",                    CC "(" HS_STACK_FRAME_REF "Z)V",                                                      FN_PTR(materializeVirtualObjects)},
1546   {CC "shouldDebugNonSafepoints",                     CC "()Z",                                                                             FN_PTR(shouldDebugNonSafepoints)},
1547   {CC "writeDebugOutput",                             CC "([BII)V",                                                                         FN_PTR(writeDebugOutput)},
1548   {CC "flushDebugOutput",                             CC "()V",                                                                             FN_PTR(flushDebugOutput)},
1549   {CC "methodDataProfileDataSize",                    CC "(JI)I",                                                                           FN_PTR(methodDataProfileDataSize)},
1550   {CC "getFingerprint",                               CC "(J)J",                                                                            FN_PTR(getFingerprint)},
1551   {CC "getHostClass",                                 CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS,                                       FN_PTR(getHostClass)},
1552   {CC "interpreterFrameSize",                         CC "(" BYTECODE_FRAME ")I",                                                           FN_PTR(interpreterFrameSize)},
1553   {CC "compileToBytecode",                            CC "(" OBJECT ")V",                                                                   FN_PTR(compileToBytecode)},
1554   {CC "getFlagValue",                                 CC "(" STRING ")" OBJECT,                                                             FN_PTR(getFlagValue)},
1555 };
1556 
1557 int CompilerToVM::methods_count() {
1558   return sizeof(methods) / sizeof(JNINativeMethod);
1559 }