1 /*
   2  * Copyright (c) 2012, 2016, 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 "asm/codeBuffer.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "jvmci/jvmciRuntime.hpp"
  31 #include "jvmci/jvmciCompilerToVM.hpp"
  32 #include "jvmci/jvmciCompiler.hpp"
  33 #include "jvmci/jvmciJavaClasses.hpp"
  34 #include "jvmci/jvmciEnv.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "oops/objArrayOop.inline.hpp"
  40 #include "prims/jvm.h"
  41 #include "runtime/biasedLocking.hpp"
  42 #include "runtime/interfaceSupport.hpp"
  43 #include "runtime/reflection.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "utilities/debug.hpp"
  46 #include "utilities/defaultStream.hpp"
  47 #include "utilities/macros.hpp"
  48 
  49 #if defined(_MSC_VER)
  50 #define strtoll _strtoi64
  51 #endif
  52 
  53 jobject JVMCIRuntime::_HotSpotJVMCIRuntime_instance = NULL;
  54 bool JVMCIRuntime::_HotSpotJVMCIRuntime_initialized = false;
  55 bool JVMCIRuntime::_well_known_classes_initialized = false;
  56 int JVMCIRuntime::_trivial_prefixes_count = 0;
  57 char** JVMCIRuntime::_trivial_prefixes = NULL;
  58 JVMCIRuntime::CompLevelAdjustment JVMCIRuntime::_comp_level_adjustment = JVMCIRuntime::none;
  59 bool JVMCIRuntime::_shutdown_called = false;
  60 
  61 BasicType JVMCIRuntime::kindToBasicType(Handle kind, TRAPS) {
  62   if (kind.is_null()) {
  63     THROW_(vmSymbols::java_lang_NullPointerException(), T_ILLEGAL);
  64   }
  65   jchar ch = JavaKind::typeChar(kind);
  66   switch(ch) {
  67     case 'Z': return T_BOOLEAN;
  68     case 'B': return T_BYTE;
  69     case 'S': return T_SHORT;
  70     case 'C': return T_CHAR;
  71     case 'I': return T_INT;
  72     case 'F': return T_FLOAT;
  73     case 'J': return T_LONG;
  74     case 'D': return T_DOUBLE;
  75     case 'A': return T_OBJECT;
  76     case '-': return T_ILLEGAL;
  77     default:
  78       JVMCI_ERROR_(T_ILLEGAL, "unexpected Kind: %c", ch);
  79   }
  80 }
  81 
  82 // Simple helper to see if the caller of a runtime stub which
  83 // entered the VM has been deoptimized
  84 
  85 static bool caller_is_deopted() {
  86   JavaThread* thread = JavaThread::current();
  87   RegisterMap reg_map(thread, false);
  88   frame runtime_frame = thread->last_frame();
  89   frame caller_frame = runtime_frame.sender(&reg_map);
  90   assert(caller_frame.is_compiled_frame(), "must be compiled");
  91   return caller_frame.is_deoptimized_frame();
  92 }
  93 
  94 // Stress deoptimization
  95 static void deopt_caller() {
  96   if ( !caller_is_deopted()) {
  97     JavaThread* thread = JavaThread::current();
  98     RegisterMap reg_map(thread, false);
  99     frame runtime_frame = thread->last_frame();
 100     frame caller_frame = runtime_frame.sender(&reg_map);
 101     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
 102     assert(caller_is_deopted(), "Must be deoptimized");
 103   }
 104 }
 105 
 106 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance(JavaThread* thread, Klass* klass))
 107   JRT_BLOCK;
 108   assert(klass->is_klass(), "not a class");
 109   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
 110   instanceKlassHandle h(thread, klass);
 111   h->check_valid_for_instantiation(true, CHECK);
 112   // make sure klass is initialized
 113   h->initialize(CHECK);
 114   // allocate instance and return via TLS
 115   oop obj = h->allocate_instance(CHECK);
 116   thread->set_vm_result(obj);
 117   JRT_BLOCK_END;
 118 
 119   if (ReduceInitialCardMarks) {
 120     new_store_pre_barrier(thread);
 121   }
 122 JRT_END
 123 
 124 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length))
 125   JRT_BLOCK;
 126   // Note: no handle for klass needed since they are not used
 127   //       anymore after new_objArray() and no GC can happen before.
 128   //       (This may have to change if this code changes!)
 129   assert(array_klass->is_klass(), "not a class");
 130   oop obj;
 131   if (array_klass->is_typeArray_klass()) {
 132     BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
 133     obj = oopFactory::new_typeArray(elt_type, length, CHECK);
 134   } else {
 135     Handle holder(THREAD, array_klass->klass_holder()); // keep the klass alive
 136     Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
 137     obj = oopFactory::new_objArray(elem_klass, length, CHECK);
 138   }
 139   thread->set_vm_result(obj);
 140   // This is pretty rare but this runtime patch is stressful to deoptimization
 141   // if we deoptimize here so force a deopt to stress the path.
 142   if (DeoptimizeALot) {
 143     static int deopts = 0;
 144     // Alternate between deoptimizing and raising an error (which will also cause a deopt)
 145     if (deopts++ % 2 == 0) {
 146       ResourceMark rm(THREAD);
 147       THROW(vmSymbols::java_lang_OutOfMemoryError());
 148     } else {
 149       deopt_caller();
 150     }
 151   }
 152   JRT_BLOCK_END;
 153 
 154   if (ReduceInitialCardMarks) {
 155     new_store_pre_barrier(thread);
 156   }
 157 JRT_END
 158 
 159 void JVMCIRuntime::new_store_pre_barrier(JavaThread* thread) {
 160   // After any safepoint, just before going back to compiled code,
 161   // we inform the GC that we will be doing initializing writes to
 162   // this object in the future without emitting card-marks, so
 163   // GC may take any compensating steps.
 164   // NOTE: Keep this code consistent with GraphKit::store_barrier.
 165 
 166   oop new_obj = thread->vm_result();
 167   if (new_obj == NULL)  return;
 168 
 169   assert(Universe::heap()->can_elide_tlab_store_barriers(),
 170          "compiler must check this first");
 171   // GC may decide to give back a safer copy of new_obj.
 172   new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj);
 173   thread->set_vm_result(new_obj);
 174 }
 175 
 176 JRT_ENTRY(void, JVMCIRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims))
 177   assert(klass->is_klass(), "not a class");
 178   assert(rank >= 1, "rank must be nonzero");
 179   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
 180   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
 181   thread->set_vm_result(obj);
 182 JRT_END
 183 
 184 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length))
 185   oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
 186   thread->set_vm_result(obj);
 187 JRT_END
 188 
 189 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror))
 190   instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(type_mirror));
 191 
 192   if (klass == NULL) {
 193     ResourceMark rm(THREAD);
 194     THROW(vmSymbols::java_lang_InstantiationException());
 195   }
 196 
 197   // Create new instance (the receiver)
 198   klass->check_valid_for_instantiation(false, CHECK);
 199 
 200   // Make sure klass gets initialized
 201   klass->initialize(CHECK);
 202 
 203   oop obj = klass->allocate_instance(CHECK);
 204   thread->set_vm_result(obj);
 205 JRT_END
 206 
 207 extern void vm_exit(int code);
 208 
 209 // Enter this method from compiled code handler below. This is where we transition
 210 // to VM mode. This is done as a helper routine so that the method called directly
 211 // from compiled code does not have to transition to VM. This allows the entry
 212 // method to see if the nmethod that we have just looked up a handler for has
 213 // been deoptimized while we were in the vm. This simplifies the assembly code
 214 // cpu directories.
 215 //
 216 // We are entering here from exception stub (via the entry method below)
 217 // If there is a compiled exception handler in this method, we will continue there;
 218 // otherwise we will unwind the stack and continue at the caller of top frame method
 219 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
 220 // control the area where we can allow a safepoint. After we exit the safepoint area we can
 221 // check to see if the handler we are going to return is now in a nmethod that has
 222 // been deoptimized. If that is the case we return the deopt blob
 223 // unpack_with_exception entry instead. This makes life for the exception blob easier
 224 // because making that same check and diverting is painful from assembly language.
 225 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, CompiledMethod*& cm))
 226   // Reset method handle flag.
 227   thread->set_is_method_handle_return(false);
 228 
 229   Handle exception(thread, ex);
 230   cm = CodeCache::find_compiled(pc);
 231   assert(cm != NULL, "this is not a compiled method");
 232   // Adjust the pc as needed/
 233   if (cm->is_deopt_pc(pc)) {
 234     RegisterMap map(thread, false);
 235     frame exception_frame = thread->last_frame().sender(&map);
 236     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 237     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 238     pc = exception_frame.pc();
 239   }
 240 #ifdef ASSERT
 241   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
 242   assert(exception->is_oop(), "just checking");
 243   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 244   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
 245     if (ExitVMOnVerifyError) vm_exit(-1);
 246     ShouldNotReachHere();
 247   }
 248 #endif
 249 
 250   // Check the stack guard pages and reenable them if necessary and there is
 251   // enough space on the stack to do so.  Use fast exceptions only if the guard
 252   // pages are enabled.
 253   bool guard_pages_enabled = thread->stack_guards_enabled();
 254   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
 255 
 256   if (JvmtiExport::can_post_on_exceptions()) {
 257     // To ensure correct notification of exception catches and throws
 258     // we have to deoptimize here.  If we attempted to notify the
 259     // catches and throws during this exception lookup it's possible
 260     // we could deoptimize on the way out of the VM and end back in
 261     // the interpreter at the throw site.  This would result in double
 262     // notifications since the interpreter would also notify about
 263     // these same catches and throws as it unwound the frame.
 264 
 265     RegisterMap reg_map(thread);
 266     frame stub_frame = thread->last_frame();
 267     frame caller_frame = stub_frame.sender(&reg_map);
 268 
 269     // We don't really want to deoptimize the nmethod itself since we
 270     // can actually continue in the exception handler ourselves but I
 271     // don't see an easy way to have the desired effect.
 272     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
 273     assert(caller_is_deopted(), "Must be deoptimized");
 274 
 275     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 276   }
 277 
 278   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
 279   if (guard_pages_enabled) {
 280     address fast_continuation = cm->handler_for_exception_and_pc(exception, pc);
 281     if (fast_continuation != NULL) {
 282       // Set flag if return address is a method handle call site.
 283       thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
 284       return fast_continuation;
 285     }
 286   }
 287 
 288   // If the stack guard pages are enabled, check whether there is a handler in
 289   // the current method.  Otherwise (guard pages disabled), force an unwind and
 290   // skip the exception cache update (i.e., just leave continuation==NULL).
 291   address continuation = NULL;
 292   if (guard_pages_enabled) {
 293 
 294     // New exception handling mechanism can support inlined methods
 295     // with exception handlers since the mappings are from PC to PC
 296 
 297     // debugging support
 298     // tracing
 299     if (log_is_enabled(Info, exceptions)) {
 300       ResourceMark rm;
 301       stringStream tempst;
 302       tempst.print("compiled method <%s>\n"
 303                    " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
 304                    cm->method()->print_value_string(), p2i(pc), p2i(thread));
 305       Exceptions::log_exception(exception, tempst);
 306     }
 307     // for AbortVMOnException flag
 308     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
 309 
 310     // Clear out the exception oop and pc since looking up an
 311     // exception handler can cause class loading, which might throw an
 312     // exception and those fields are expected to be clear during
 313     // normal bytecode execution.
 314     thread->clear_exception_oop_and_pc();
 315 
 316     continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false);
 317     // If an exception was thrown during exception dispatch, the exception oop may have changed
 318     thread->set_exception_oop(exception());
 319     thread->set_exception_pc(pc);
 320 
 321     // the exception cache is used only by non-implicit exceptions
 322     if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) {
 323       cm->add_handler_for_exception_and_pc(exception, pc, continuation);
 324     }
 325   }
 326 
 327   // Set flag if return address is a method handle call site.
 328   thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
 329 
 330   if (log_is_enabled(Info, exceptions)) {
 331     ResourceMark rm;
 332     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
 333                          " for exception thrown at PC " PTR_FORMAT,
 334                          p2i(thread), p2i(continuation), p2i(pc));
 335   }
 336 
 337   return continuation;
 338 JRT_END
 339 
 340 // Enter this method from compiled code only if there is a Java exception handler
 341 // in the method handling the exception.
 342 // We are entering here from exception stub. We don't do a normal VM transition here.
 343 // We do it in a helper. This is so we can check to see if the nmethod we have just
 344 // searched for an exception handler has been deoptimized in the meantime.
 345 address JVMCIRuntime::exception_handler_for_pc(JavaThread* thread) {
 346   oop exception = thread->exception_oop();
 347   address pc = thread->exception_pc();
 348   // Still in Java mode
 349   DEBUG_ONLY(ResetNoHandleMark rnhm);
 350   CompiledMethod* cm = NULL;
 351   address continuation = NULL;
 352   {
 353     // Enter VM mode by calling the helper
 354     ResetNoHandleMark rnhm;
 355     continuation = exception_handler_for_pc_helper(thread, exception, pc, cm);
 356   }
 357   // Back in JAVA, use no oops DON'T safepoint
 358 
 359   // Now check to see if the compiled method we were called from is now deoptimized.
 360   // If so we must return to the deopt blob and deoptimize the nmethod
 361   if (cm != NULL && caller_is_deopted()) {
 362     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 363   }
 364 
 365   assert(continuation != NULL, "no handler found");
 366   return continuation;
 367 }
 368 
 369 JRT_ENTRY_NO_ASYNC(void, JVMCIRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 370   IF_TRACE_jvmci_3 {
 371     char type[O_BUFLEN];
 372     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 373     markOop mark = obj->mark();
 374     TRACE_jvmci_3("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock));
 375     tty->flush();
 376   }
 377 #ifdef ASSERT
 378   if (PrintBiasedLockingStatistics) {
 379     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 380   }
 381 #endif
 382   Handle h_obj(thread, obj);
 383   assert(h_obj()->is_oop(), "must be NULL or an object");
 384   if (UseBiasedLocking) {
 385     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 386     ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
 387   } else {
 388     if (JVMCIUseFastLocking) {
 389       // When using fast locking, the compiled code has already tried the fast case
 390       ObjectSynchronizer::slow_enter(h_obj, lock, THREAD);
 391     } else {
 392       ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD);
 393     }
 394   }
 395   TRACE_jvmci_3("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj));
 396 JRT_END
 397 
 398 JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 399   assert(thread == JavaThread::current(), "threads must correspond");
 400   assert(thread->last_Java_sp(), "last_Java_sp must be set");
 401   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
 402   EXCEPTION_MARK;
 403 
 404 #ifdef DEBUG
 405   if (!obj->is_oop()) {
 406     ResetNoHandleMark rhm;
 407     nmethod* method = thread->last_frame().cb()->as_nmethod_or_null();
 408     if (method != NULL) {
 409       tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj));
 410     }
 411     thread->print_stack_on(tty);
 412     assert(false, "invalid lock object pointer dected");
 413   }
 414 #endif
 415 
 416   if (JVMCIUseFastLocking) {
 417     // When using fast locking, the compiled code has already tried the fast case
 418     ObjectSynchronizer::slow_exit(obj, lock, THREAD);
 419   } else {
 420     ObjectSynchronizer::fast_exit(obj, lock, THREAD);
 421   }
 422   IF_TRACE_jvmci_3 {
 423     char type[O_BUFLEN];
 424     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 425     TRACE_jvmci_3("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock));
 426     tty->flush();
 427   }
 428 JRT_END
 429 
 430 JRT_ENTRY(void, JVMCIRuntime::throw_and_post_jvmti_exception(JavaThread* thread, const char* exception, const char* message))
 431   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
 432   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
 433 JRT_END
 434 
 435 JRT_ENTRY(void, JVMCIRuntime::throw_klass_external_name_exception(JavaThread* thread, const char* exception, Klass* klass))
 436   ResourceMark rm(thread);
 437   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
 438   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, klass->external_name());
 439 JRT_END
 440 
 441 JRT_ENTRY(void, JVMCIRuntime::throw_class_cast_exception(JavaThread* thread, const char* exception, Klass* caster_klass, Klass* target_klass))
 442   ResourceMark rm(thread);
 443   const char* message = SharedRuntime::generate_class_cast_message(caster_klass, target_klass);
 444   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
 445   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
 446 JRT_END
 447 
 448 JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
 449   ttyLocker ttyl;
 450 
 451   if (obj == NULL) {
 452     tty->print("NULL");
 453   } else if (obj->is_oop_or_null(true) && (!as_string || !java_lang_String::is_instance(obj))) {
 454     if (obj->is_oop_or_null(true)) {
 455       char buf[O_BUFLEN];
 456       tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
 457     } else {
 458       tty->print(INTPTR_FORMAT, p2i(obj));
 459     }
 460   } else {
 461     ResourceMark rm;
 462     assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
 463     char *buf = java_lang_String::as_utf8_string(obj);
 464     tty->print_raw(buf);
 465   }
 466   if (newline) {
 467     tty->cr();
 468   }
 469 JRT_END
 470 
 471 JRT_LEAF(void, JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj))
 472   thread->satb_mark_queue().enqueue(obj);
 473 JRT_END
 474 
 475 JRT_LEAF(void, JVMCIRuntime::write_barrier_post(JavaThread* thread, void* card_addr))
 476   thread->dirty_card_queue().enqueue(card_addr);
 477 JRT_END
 478 
 479 JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
 480   bool ret = true;
 481   if(!Universe::heap()->is_in_closed_subset(parent)) {
 482     tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
 483     parent->print();
 484     ret=false;
 485   }
 486   if(!Universe::heap()->is_in_closed_subset(child)) {
 487     tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
 488     child->print();
 489     ret=false;
 490   }
 491   return (jint)ret;
 492 JRT_END
 493 
 494 JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value))
 495   ResourceMark rm;
 496   const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
 497   char *detail_msg = NULL;
 498   if (format != 0L) {
 499     const char* buf = (char*) (address) format;
 500     size_t detail_msg_length = strlen(buf) * 2;
 501     detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
 502     jio_snprintf(detail_msg, detail_msg_length, buf, value);
 503     report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
 504   } else {
 505     report_vm_error(__FILE__, __LINE__, error_msg);
 506   }
 507 JRT_END
 508 
 509 JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
 510   oop exception = thread->exception_oop();
 511   assert(exception != NULL, "npe");
 512   thread->set_exception_oop(NULL);
 513   thread->set_exception_pc(0);
 514   return exception;
 515 JRT_END
 516 
 517 PRAGMA_DIAG_PUSH
 518 PRAGMA_FORMAT_NONLITERAL_IGNORED
 519 JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3))
 520   ResourceMark rm;
 521   assert(format != NULL && java_lang_String::is_instance(format), "must be");
 522   char *buf = java_lang_String::as_utf8_string(format);
 523   tty->print((const char*)buf, v1, v2, v3);
 524 JRT_END
 525 PRAGMA_DIAG_POP
 526 
 527 static void decipher(jlong v, bool ignoreZero) {
 528   if (v != 0 || !ignoreZero) {
 529     void* p = (void *)(address) v;
 530     CodeBlob* cb = CodeCache::find_blob(p);
 531     if (cb) {
 532       if (cb->is_nmethod()) {
 533         char buf[O_BUFLEN];
 534         tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin()));
 535         return;
 536       }
 537       cb->print_value_on(tty);
 538       return;
 539     }
 540     if (Universe::heap()->is_in(p)) {
 541       oop obj = oop(p);
 542       obj->print_value_on(tty);
 543       return;
 544     }
 545     tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
 546   }
 547 }
 548 
 549 PRAGMA_DIAG_PUSH
 550 PRAGMA_FORMAT_NONLITERAL_IGNORED
 551 JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
 552   ResourceMark rm;
 553   const char *buf = (const char*) (address) format;
 554   if (vmError) {
 555     if (buf != NULL) {
 556       fatal(buf, v1, v2, v3);
 557     } else {
 558       fatal("<anonymous error>");
 559     }
 560   } else if (buf != NULL) {
 561     tty->print(buf, v1, v2, v3);
 562   } else {
 563     assert(v2 == 0, "v2 != 0");
 564     assert(v3 == 0, "v3 != 0");
 565     decipher(v1, false);
 566   }
 567 JRT_END
 568 PRAGMA_DIAG_POP
 569 
 570 JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
 571   union {
 572       jlong l;
 573       jdouble d;
 574       jfloat f;
 575   } uu;
 576   uu.l = value;
 577   switch (typeChar) {
 578     case 'Z': tty->print(value == 0 ? "false" : "true"); break;
 579     case 'B': tty->print("%d", (jbyte) value); break;
 580     case 'C': tty->print("%c", (jchar) value); break;
 581     case 'S': tty->print("%d", (jshort) value); break;
 582     case 'I': tty->print("%d", (jint) value); break;
 583     case 'F': tty->print("%f", uu.f); break;
 584     case 'J': tty->print(JLONG_FORMAT, value); break;
 585     case 'D': tty->print("%lf", uu.d); break;
 586     default: assert(false, "unknown typeChar"); break;
 587   }
 588   if (newline) {
 589     tty->cr();
 590   }
 591 JRT_END
 592 
 593 JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj))
 594   return (jint) obj->identity_hash();
 595 JRT_END
 596 
 597 JRT_ENTRY(jboolean, JVMCIRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted))
 598   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
 599   // This locking requires thread_in_vm which is why this method cannot be JRT_LEAF.
 600   Handle receiverHandle(thread, receiver);
 601   MutexLockerEx ml(thread->threadObj() == (void*)receiver ? NULL : Threads_lock);
 602   JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle());
 603   if (receiverThread == NULL) {
 604     // The other thread may exit during this process, which is ok so return false.
 605     return JNI_FALSE;
 606   } else {
 607     return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0);
 608   }
 609 JRT_END
 610 
 611 JRT_ENTRY(jint, JVMCIRuntime::test_deoptimize_call_int(JavaThread* thread, int value))
 612   deopt_caller();
 613   return value;
 614 JRT_END
 615 
 616 // private static JVMCIRuntime JVMCI.initializeRuntime()
 617 JVM_ENTRY(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
 618   if (!EnableJVMCI) {
 619     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled")
 620   }
 621   JVMCIRuntime::initialize_HotSpotJVMCIRuntime(CHECK_NULL);
 622   jobject ret = JVMCIRuntime::get_HotSpotJVMCIRuntime_jobject(CHECK_NULL);
 623   return ret;
 624 JVM_END
 625 
 626 Handle JVMCIRuntime::callStatic(const char* className, const char* methodName, const char* signature, JavaCallArguments* args, TRAPS) {
 627   guarantee(!_HotSpotJVMCIRuntime_initialized, "cannot reinitialize HotSpotJVMCIRuntime");
 628 
 629   TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_(Handle()));
 630   KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, CHECK_(Handle()));
 631   TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_(Handle()));
 632   TempNewSymbol sig = SymbolTable::new_symbol(signature, CHECK_(Handle()));
 633   JavaValue result(T_OBJECT);
 634   if (args == NULL) {
 635     JavaCalls::call_static(&result, klass, runtime, sig, CHECK_(Handle()));
 636   } else {
 637     JavaCalls::call_static(&result, klass, runtime, sig, args, CHECK_(Handle()));
 638   }
 639   return Handle((oop)result.get_jobject());
 640 }
 641 
 642 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(TRAPS) {
 643   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 644     ResourceMark rm;
 645 #ifdef ASSERT
 646     // This should only be called in the context of the JVMCI class being initialized
 647     TempNewSymbol name = SymbolTable::new_symbol("jdk/vm/ci/runtime/JVMCI", CHECK);
 648     Klass* k = SystemDictionary::resolve_or_null(name, CHECK);
 649     instanceKlassHandle klass = InstanceKlass::cast(k);
 650     assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD),
 651            "HotSpotJVMCIRuntime initialization should only be triggered through JVMCI initialization");
 652 #endif
 653 
 654     Handle result = callStatic("jdk/vm/ci/hotspot/HotSpotJVMCIRuntime",
 655                                "runtime",
 656                                "()Ljdk/vm/ci/hotspot/HotSpotJVMCIRuntime;", NULL, CHECK);
 657     objArrayOop trivial_prefixes = HotSpotJVMCIRuntime::trivialPrefixes(result);
 658     if (trivial_prefixes != NULL) {
 659       char** prefixes = NEW_C_HEAP_ARRAY(char*, trivial_prefixes->length(), mtCompiler);
 660       for (int i = 0; i < trivial_prefixes->length(); i++) {
 661         oop str = trivial_prefixes->obj_at(i);
 662         if (str == NULL) {
 663           THROW(vmSymbols::java_lang_NullPointerException());
 664         } else {
 665           prefixes[i] = strdup(java_lang_String::as_utf8_string(str));
 666         }
 667       }
 668       _trivial_prefixes = prefixes;
 669       _trivial_prefixes_count = trivial_prefixes->length();
 670     }
 671     int adjustment = HotSpotJVMCIRuntime::compilationLevelAdjustment(result);
 672     assert(adjustment >= JVMCIRuntime::none &&
 673            adjustment <= JVMCIRuntime::by_full_signature,
 674            "compilation level adjustment out of bounds");
 675     _comp_level_adjustment = (CompLevelAdjustment) adjustment;
 676     _HotSpotJVMCIRuntime_initialized = true;
 677     _HotSpotJVMCIRuntime_instance = JNIHandles::make_global(result());
 678   }
 679 }
 680 
 681 void JVMCIRuntime::initialize_JVMCI(TRAPS) {
 682   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 683     callStatic("jdk/vm/ci/runtime/JVMCI",
 684                "getRuntime",
 685                "()Ljdk/vm/ci/runtime/JVMCIRuntime;", NULL, CHECK);
 686   }
 687   assert(_HotSpotJVMCIRuntime_initialized == true, "what?");
 688 }
 689 
 690 void JVMCIRuntime::initialize_well_known_classes(TRAPS) {
 691   if (JVMCIRuntime::_well_known_classes_initialized == false) {
 692     SystemDictionary::WKID scan = SystemDictionary::FIRST_JVMCI_WKID;
 693     SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_JVMCI_WKID, scan, CHECK);
 694     JVMCIJavaClasses::compute_offsets(CHECK);
 695     JVMCIRuntime::_well_known_classes_initialized = true;
 696   }
 697 }
 698 
 699 void JVMCIRuntime::metadata_do(void f(Metadata*)) {
 700   // For simplicity, the existence of HotSpotJVMCIMetaAccessContext in
 701   // the SystemDictionary well known classes should ensure the other
 702   // classes have already been loaded, so make sure their order in the
 703   // table enforces that.
 704   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedJavaMethodImpl) <
 705          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 706   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotConstantPool) <
 707          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 708   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedObjectTypeImpl) <
 709          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 710 
 711   if (HotSpotJVMCIMetaAccessContext::klass() == NULL ||
 712       !HotSpotJVMCIMetaAccessContext::klass()->is_linked()) {
 713     // Nothing could be registered yet
 714     return;
 715   }
 716 
 717   // WeakReference<HotSpotJVMCIMetaAccessContext>[]
 718   objArrayOop allContexts = HotSpotJVMCIMetaAccessContext::allContexts();
 719   if (allContexts == NULL) {
 720     return;
 721   }
 722 
 723   // These must be loaded at this point but the linking state doesn't matter.
 724   assert(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass() != NULL, "must be loaded");
 725   assert(SystemDictionary::HotSpotConstantPool_klass() != NULL, "must be loaded");
 726   assert(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass() != NULL, "must be loaded");
 727 
 728   for (int i = 0; i < allContexts->length(); i++) {
 729     oop ref = allContexts->obj_at(i);
 730     if (ref != NULL) {
 731       oop referent = java_lang_ref_Reference::referent(ref);
 732       if (referent != NULL) {
 733         // Chunked Object[] with last element pointing to next chunk
 734         objArrayOop metadataRoots = HotSpotJVMCIMetaAccessContext::metadataRoots(referent);
 735         while (metadataRoots != NULL) {
 736           for (int typeIndex = 0; typeIndex < metadataRoots->length() - 1; typeIndex++) {
 737             oop reference = metadataRoots->obj_at(typeIndex);
 738             if (reference == NULL) {
 739               continue;
 740             }
 741             oop metadataRoot = java_lang_ref_Reference::referent(reference);
 742             if (metadataRoot == NULL) {
 743               continue;
 744             }
 745             if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 746               Method* method = CompilerToVM::asMethod(metadataRoot);
 747               f(method);
 748             } else if (metadataRoot->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 749               ConstantPool* constantPool = CompilerToVM::asConstantPool(metadataRoot);
 750               f(constantPool);
 751             } else if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 752               Klass* klass = CompilerToVM::asKlass(metadataRoot);
 753               f(klass);
 754             } else {
 755               metadataRoot->print();
 756               ShouldNotReachHere();
 757             }
 758           }
 759           metadataRoots = (objArrayOop)metadataRoots->obj_at(metadataRoots->length() - 1);
 760           assert(metadataRoots == NULL || metadataRoots->is_objArray(), "wrong type");
 761         }
 762       }
 763     }
 764   }
 765 }
 766 
 767 // private static void CompilerToVM.registerNatives()
 768 JVM_ENTRY(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
 769   if (!EnableJVMCI) {
 770     THROW_MSG(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled");
 771   }
 772 
 773 #ifdef _LP64
 774 #ifndef SPARC
 775   uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end();
 776   uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024;
 777   guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)");
 778 #endif // !SPARC
 779 #else
 780   fatal("check TLAB allocation code for address space conflicts");
 781 #endif // _LP64
 782 
 783   JVMCIRuntime::initialize_well_known_classes(CHECK);
 784 
 785   {
 786     ThreadToNativeFromVM trans(thread);
 787     env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count());
 788   }
 789 JVM_END
 790 
 791 #define CHECK_WARN_ABORT_(message) THREAD); \
 792   if (HAS_PENDING_EXCEPTION) { \
 793     warning(message); \
 794     char buf[512]; \
 795     jio_snprintf(buf, 512, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 796     JVMCIRuntime::abort_on_pending_exception(PENDING_EXCEPTION, buf); \
 797     return; \
 798   } \
 799   (void)(0
 800 
 801 void JVMCIRuntime::shutdown(TRAPS) {
 802   if (_HotSpotJVMCIRuntime_instance != NULL) {
 803     _shutdown_called = true;
 804     HandleMark hm(THREAD);
 805     Handle receiver = get_HotSpotJVMCIRuntime(CHECK);
 806     JavaValue result(T_VOID);
 807     JavaCallArguments args;
 808     args.push_oop(receiver);
 809     JavaCalls::call_special(&result, receiver->klass(), vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK);
 810   }
 811 }
 812 
 813 CompLevel JVMCIRuntime::adjust_comp_level_inner(methodHandle method, bool is_osr, CompLevel level, JavaThread* thread) {
 814   JVMCICompiler* compiler = JVMCICompiler::instance(thread);
 815   if (compiler != NULL && compiler->is_bootstrapping()) {
 816     return level;
 817   }
 818   if (!is_HotSpotJVMCIRuntime_initialized() || !_comp_level_adjustment) {
 819     // JVMCI cannot participate in compilation scheduling until
 820     // JVMCI is initialized and indicates it wants to participate.
 821     return level;
 822   }
 823 
 824 #define CHECK_RETURN THREAD); \
 825 if (HAS_PENDING_EXCEPTION) { \
 826   Handle exception(THREAD, PENDING_EXCEPTION); \
 827   CLEAR_PENDING_EXCEPTION; \
 828 \
 829   java_lang_Throwable::java_printStackTrace(exception, THREAD); \
 830   if (HAS_PENDING_EXCEPTION) { \
 831     CLEAR_PENDING_EXCEPTION; \
 832   } \
 833   return level; \
 834 } \
 835 (void)(0
 836 
 837 
 838   Thread* THREAD = thread;
 839   HandleMark hm;
 840   Handle receiver = JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK_RETURN);
 841   Handle name;
 842   Handle sig;
 843   if (_comp_level_adjustment == JVMCIRuntime::by_full_signature) {
 844     name = java_lang_String::create_from_symbol(method->name(), CHECK_RETURN);
 845     sig = java_lang_String::create_from_symbol(method->signature(), CHECK_RETURN);
 846   } else {
 847     name = Handle();
 848     sig = Handle();
 849   }
 850 
 851   JavaValue result(T_INT);
 852   JavaCallArguments args;
 853   args.push_oop(receiver);
 854   args.push_oop(method->method_holder()->java_mirror());
 855   args.push_oop(name());
 856   args.push_oop(sig());
 857   args.push_int(is_osr);
 858   args.push_int(level);
 859   JavaCalls::call_special(&result, receiver->klass(), vmSymbols::adjustCompilationLevel_name(),
 860                           vmSymbols::adjustCompilationLevel_signature(), &args, CHECK_RETURN);
 861 
 862   int comp_level = result.get_jint();
 863   if (comp_level < CompLevel_none || comp_level > CompLevel_full_optimization) {
 864     assert(false, "compilation level out of bounds");
 865     return level;
 866   }
 867   return (CompLevel) comp_level;
 868 #undef CHECK_RETURN
 869 }
 870 
 871 void JVMCIRuntime::bootstrap_finished(TRAPS) {
 872   HandleMark hm(THREAD);
 873   Handle receiver = get_HotSpotJVMCIRuntime(CHECK);
 874   JavaValue result(T_VOID);
 875   JavaCallArguments args;
 876   args.push_oop(receiver);
 877   JavaCalls::call_special(&result, receiver->klass(), vmSymbols::bootstrapFinished_method_name(), vmSymbols::void_method_signature(), &args, CHECK);
 878 }
 879 
 880 bool JVMCIRuntime::treat_as_trivial(Method* method) {
 881   if (_HotSpotJVMCIRuntime_initialized) {
 882     for (int i = 0; i < _trivial_prefixes_count; i++) {
 883       if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) {
 884         return true;
 885       }
 886     }
 887   }
 888   return false;
 889 }