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