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 #ifndef SHARE_JVMCI_JVMCIRUNTIME_HPP
  25 #define SHARE_JVMCI_JVMCIRUNTIME_HPP
  26 
  27 #include "interpreter/interpreter.hpp"
  28 #include "jvmci/jvmci.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/deoptimization.hpp"
  32 
  33 class JVMCIObject;
  34 class JVMCIEnv;
  35 class JVMCICompileState;
  36 
  37 // Encapsulates the JVMCI metadata for an nmethod.
  38 // JVMCINMethodData objects are inlined into nmethods
  39 // at nmethod::_jvmci_data_offset.
  40 class JVMCINMethodData {
  41   // Index for the HotSpotNmethod mirror in the nmethod's oops table.
  42   // This is -1 if there is no mirror in the oops table.
  43   int _nmethod_mirror_index;
  44 
  45   // Is HotSpotNmethod.name non-null? If so, the value is
  46   // embedded in the end of this object.
  47   bool _has_name;
  48 
  49   // Address of the failed speculations list to which a speculation
  50   // is appended when it causes a deoptimization.
  51   FailedSpeculation** _failed_speculations;
  52 
  53 public:
  54   // Computes the size of a JVMCINMethodData object
  55   static int compute_size(const char* nmethod_mirror_name) {
  56     int size = sizeof(JVMCINMethodData);
  57     if (nmethod_mirror_name != NULL) {
  58       size += (int) strlen(nmethod_mirror_name) + 1;
  59     }
  60     return size;
  61   }
  62 
  63   void initialize(int nmethod_mirror_index,
  64              const char* name,
  65              FailedSpeculation** failed_speculations);
  66 
  67   // Adds `speculation` to the failed speculations list.
  68   void add_failed_speculation(nmethod* nm, jlong speculation);
  69 
  70   // Gets the JVMCI name of the nmethod (which may be NULL).
  71   const char* name() { return _has_name ? (char*)(((address) this) + sizeof(JVMCINMethodData)) : NULL; }
  72 
  73   // Clears the HotSpotNmethod.address field in the  mirror. If nm
  74   // is dead, the HotSpotNmethod.entryPoint field is also cleared.
  75   void invalidate_nmethod_mirror(nmethod* nm);
  76 
  77   // Gets the mirror from nm's oops table.
  78   oop get_nmethod_mirror(nmethod* nm);
  79 
  80   // Sets the mirror in nm's oops table.
  81   void set_nmethod_mirror(nmethod* nm, oop mirror);
  82 
  83   // Clears the mirror in nm's oops table.
  84   void clear_nmethod_mirror(nmethod* nm);
  85 };
  86 
  87 // A top level class that represents an initialized JVMCI runtime.
  88 // There is one instance of this class per HotSpotJVMCIRuntime object.
  89 class JVMCIRuntime: public CHeapObj<mtCompiler> {
  90  public:
  91   // Constants describing whether JVMCI wants to be able to adjust the compilation
  92   // level selected for a method by the VM compilation policy and if so, based on
  93   // what information about the method being schedule for compilation.
  94   enum CompLevelAdjustment {
  95      none = 0,             // no adjustment
  96      by_holder = 1,        // adjust based on declaring class of method
  97      by_full_signature = 2 // adjust based on declaring class, name and signature of method
  98   };
  99 
 100  private:
 101   volatile bool _being_initialized;
 102   volatile bool _initialized;
 103 
 104   JVMCIObject _HotSpotJVMCIRuntime_instance;
 105 
 106   CompLevelAdjustment _comp_level_adjustment;
 107 
 108   bool _shutdown_called;
 109 
 110   CompLevel adjust_comp_level_inner(methodHandle method, bool is_osr, CompLevel level, JavaThread* thread);
 111 
 112   JVMCIObject create_jvmci_primitive_type(BasicType type, JVMCI_TRAPS);
 113 
 114   // Implementation methods for loading and constant pool access.
 115   static Klass* get_klass_by_name_impl(Klass*& accessing_klass,
 116                                        const constantPoolHandle& cpool,
 117                                        Symbol* klass_name,
 118                                        bool require_local);
 119   static Klass*   get_klass_by_index_impl(const constantPoolHandle& cpool,
 120                                           int klass_index,
 121                                           bool& is_accessible,
 122                                           Klass* loading_klass);
 123   static void   get_field_by_index_impl(InstanceKlass* loading_klass, fieldDescriptor& fd,
 124                                         int field_index);
 125   static methodHandle  get_method_by_index_impl(const constantPoolHandle& cpool,
 126                                                 int method_index, Bytecodes::Code bc,
 127                                                 InstanceKlass* loading_klass);
 128 
 129   // Helper methods
 130   static bool       check_klass_accessibility(Klass* accessing_klass, Klass* resolved_klass);
 131   static methodHandle  lookup_method(InstanceKlass*  accessor,
 132                                      Klass*  holder,
 133                                      Symbol*         name,
 134                                      Symbol*         sig,
 135                                      Bytecodes::Code bc,
 136                                      constantTag     tag);
 137 
 138  public:
 139   JVMCIRuntime() {
 140     _comp_level_adjustment = JVMCIRuntime::none;
 141     _initialized = false;
 142     _being_initialized = false;
 143     _shutdown_called = false;
 144   }
 145 
 146   /**
 147    * Compute offsets and construct any state required before executing JVMCI code.
 148    */
 149   void initialize(JVMCIEnv* jvmciEnv);
 150 
 151   /**
 152    * Gets the singleton HotSpotJVMCIRuntime instance, initializing it if necessary
 153    */
 154   JVMCIObject get_HotSpotJVMCIRuntime(JVMCI_TRAPS);
 155 
 156   bool is_HotSpotJVMCIRuntime_initialized() {
 157     return _HotSpotJVMCIRuntime_instance.is_non_null();
 158   }
 159 
 160   /**
 161    * Trigger initialization of HotSpotJVMCIRuntime through JVMCI.getRuntime()
 162    */
 163   void initialize_JVMCI(JVMCI_TRAPS);
 164 
 165   /**
 166    * Explicitly initialize HotSpotJVMCIRuntime itself
 167    */
 168   void initialize_HotSpotJVMCIRuntime(JVMCI_TRAPS);
 169 
 170   void call_getCompiler(TRAPS);
 171 
 172   /**
 173    * Lets JVMCI modify the compilation level currently selected for a method by
 174    * the VM compilation policy.
 175    *
 176    * @param method the method being scheduled for compilation
 177    * @param is_osr specifies if the compilation is an OSR compilation
 178    * @param level the compilation level currently selected by the VM compilation policy
 179    * @param thread the current thread
 180    * @return the compilation level to use for the compilation
 181    */
 182   CompLevel adjust_comp_level(methodHandle method, bool is_osr, CompLevel level, JavaThread* thread);
 183 
 184   void shutdown();
 185 
 186   bool shutdown_called() {
 187     return _shutdown_called;
 188   }
 189 
 190   void bootstrap_finished(TRAPS);
 191 
 192   // Look up a klass by name from a particular class loader (the accessor's).
 193   // If require_local, result must be defined in that class loader, or NULL.
 194   // If !require_local, a result from remote class loader may be reported,
 195   // if sufficient class loader constraints exist such that initiating
 196   // a class loading request from the given loader is bound to return
 197   // the class defined in the remote loader (or throw an error).
 198   //
 199   // Return an unloaded klass if !require_local and no class at all is found.
 200   //
 201   // The CI treats a klass as loaded if it is consistently defined in
 202   // another loader, even if it hasn't yet been loaded in all loaders
 203   // that could potentially see it via delegation.
 204   static Klass* get_klass_by_name(Klass* accessing_klass,
 205                                   Symbol* klass_name,
 206                                   bool require_local);
 207 
 208   // Constant pool access.
 209   static Klass*   get_klass_by_index(const constantPoolHandle& cpool,
 210                                      int klass_index,
 211                                      bool& is_accessible,
 212                                      Klass* loading_klass);
 213   static void   get_field_by_index(InstanceKlass* loading_klass, fieldDescriptor& fd,
 214                                    int field_index);
 215   static methodHandle  get_method_by_index(const constantPoolHandle& cpool,
 216                                            int method_index, Bytecodes::Code bc,
 217                                            InstanceKlass* loading_klass);
 218 
 219   // converts the Klass* representing the holder of a method into a
 220   // InstanceKlass*.  This is needed since the holder of a method in
 221   // the bytecodes could be an array type.  Basically this converts
 222   // array types into java/lang/Object and other types stay as they are.
 223   static InstanceKlass* get_instance_klass_for_declared_method_holder(Klass* klass);
 224 
 225   // Helper routine for determining the validity of a compilation
 226   // with respect to concurrent class loading.
 227   static JVMCI::CodeInstallResult validate_compile_task_dependencies(Dependencies* target, JVMCICompileState* task, char** failure_detail);
 228 
 229   // Compiles `target` with the JVMCI compiler.
 230   void compile_method(JVMCIEnv* JVMCIENV, JVMCICompiler* compiler, const methodHandle& target, int entry_bci);
 231 
 232   // Register the result of a compilation.
 233   JVMCI::CodeInstallResult register_method(JVMCIEnv* JVMCIENV,
 234                        const methodHandle&       target,
 235                        nmethod*&                 nm,
 236                        int                       entry_bci,
 237                        CodeOffsets*              offsets,
 238                        int                       orig_pc_offset,
 239                        CodeBuffer*               code_buffer,
 240                        int                       frame_words,
 241                        OopMapSet*                oop_map_set,
 242                        ExceptionHandlerTable*    handler_table,
 243                        AbstractCompiler*         compiler,
 244                        DebugInformationRecorder* debug_info,
 245                        Dependencies*             dependencies,
 246                        int                       compile_id,
 247                        bool                      has_unsafe_access,
 248                        bool                      has_wide_vector,
 249                        JVMCIObject               compiled_code,
 250                        JVMCIObject               nmethod_mirror,
 251                        FailedSpeculation**       failed_speculations,
 252                        char*                     speculations,
 253                        int                       speculations_len);
 254 
 255   /**
 256    * Exits the VM due to an unexpected exception.
 257    */
 258   static void exit_on_pending_exception(JVMCIEnv* JVMCIENV, const char* message);
 259 
 260   static void describe_pending_hotspot_exception(JavaThread* THREAD, bool clear);
 261 
 262 #define CHECK_EXIT THREAD); \
 263   if (HAS_PENDING_EXCEPTION) { \
 264     char buf[256]; \
 265     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 266     JVMCIRuntime::exit_on_pending_exception(NULL, buf); \
 267     return; \
 268   } \
 269   (void)(0
 270 
 271 #define CHECK_EXIT_(v) THREAD);                 \
 272   if (HAS_PENDING_EXCEPTION) { \
 273     char buf[256]; \
 274     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 275     JVMCIRuntime::exit_on_pending_exception(NULL, buf); \
 276     return v; \
 277   } \
 278   (void)(0
 279 
 280 #define JVMCI_CHECK_EXIT JVMCIENV); \
 281   if (JVMCIENV->has_pending_exception()) {      \
 282     char buf[256]; \
 283     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 284     JVMCIRuntime::exit_on_pending_exception(JVMCIENV, buf); \
 285     return; \
 286   } \
 287   (void)(0
 288 
 289 #define JVMCI_CHECK_EXIT_(result) JVMCIENV); \
 290   if (JVMCIENV->has_pending_exception()) {      \
 291     char buf[256]; \
 292     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 293     JVMCIRuntime::exit_on_pending_exception(JVMCIENV, buf); \
 294     return result; \
 295   } \
 296   (void)(0
 297 
 298   static BasicType kindToBasicType(Handle kind, TRAPS);
 299 
 300   static void new_instance_common(JavaThread* thread, Klass* klass, bool null_on_fail);
 301   static void new_array_common(JavaThread* thread, Klass* klass, jint length, bool null_on_fail);
 302   static void new_multi_array_common(JavaThread* thread, Klass* klass, int rank, jint* dims, bool null_on_fail);
 303   static void dynamic_new_array_common(JavaThread* thread, oopDesc* element_mirror, jint length, bool null_on_fail);
 304   static void dynamic_new_instance_common(JavaThread* thread, oopDesc* type_mirror, bool null_on_fail);
 305 
 306   // The following routines are called from compiled JVMCI code
 307 
 308   // When allocation fails, these stubs:
 309   // 1. Exercise -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError handling and also
 310   //    post a JVMTI_EVENT_RESOURCE_EXHAUSTED event if the failure is an OutOfMemroyError
 311   // 2. Return NULL with a pending exception.
 312   // Compiled code must ensure these stubs are not called twice for the same allocation
 313   // site due to the non-repeatable side effects in the case of OOME.
 314   static void new_instance(JavaThread* thread, Klass* klass) { new_instance_common(thread, klass, false); }
 315   static void new_array(JavaThread* thread, Klass* klass, jint length) { new_array_common(thread, klass, length, false); }
 316   static void new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims) { new_multi_array_common(thread, klass, rank, dims, false); }
 317   static void dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length) { dynamic_new_array_common(thread, element_mirror, length, false); }
 318   static void dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror) { dynamic_new_instance_common(thread, type_mirror, false); }
 319 
 320   // When allocation fails, these stubs return NULL and have no pending exception. Compiled code
 321   // can use these stubs if a failed allocation will be retried (e.g., by deoptimizing and
 322   // re-executing in the interpreter).
 323   static void new_instance_or_null(JavaThread* thread, Klass* klass) { new_instance_common(thread, klass, true); }
 324   static void new_array_or_null(JavaThread* thread, Klass* klass, jint length) { new_array_common(thread, klass, length, true); }
 325   static void new_multi_array_or_null(JavaThread* thread, Klass* klass, int rank, jint* dims) { new_multi_array_common(thread, klass, rank, dims, true); }
 326   static void dynamic_new_array_or_null(JavaThread* thread, oopDesc* element_mirror, jint length) { dynamic_new_array_common(thread, element_mirror, length, true); }
 327   static void dynamic_new_instance_or_null(JavaThread* thread, oopDesc* type_mirror) { dynamic_new_instance_common(thread, type_mirror, true); }
 328 
 329   static jboolean thread_is_interrupted(JavaThread* thread, oopDesc* obj, jboolean clear_interrupted);
 330   static void vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3);
 331   static jint identity_hash_code(JavaThread* thread, oopDesc* obj);
 332   static address exception_handler_for_pc(JavaThread* thread);
 333   static void monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock);
 334   static void monitorexit (JavaThread* thread, oopDesc* obj, BasicLock* lock);
 335   static jboolean object_notify(JavaThread* thread, oopDesc* obj);
 336   static jboolean object_notifyAll(JavaThread* thread, oopDesc* obj);
 337   static void vm_error(JavaThread* thread, jlong where, jlong format, jlong value);
 338   static oopDesc* load_and_clear_exception(JavaThread* thread);
 339   static void log_printf(JavaThread* thread, const char* format, jlong v1, jlong v2, jlong v3);
 340   static void log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline);
 341   // Print the passed in object, optionally followed by a newline.  If
 342   // as_string is true and the object is a java.lang.String then it
 343   // printed as a string, otherwise the type of the object is printed
 344   // followed by its address.
 345   static void log_object(JavaThread* thread, oopDesc* object, bool as_string, bool newline);
 346 #if INCLUDE_G1GC
 347   static void write_barrier_pre(JavaThread* thread, oopDesc* obj);
 348   static void write_barrier_post(JavaThread* thread, void* card);
 349 #endif
 350   static jboolean validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child);
 351 
 352   // used to throw exceptions from compiled JVMCI code
 353   static void throw_and_post_jvmti_exception(JavaThread* thread, const char* exception, const char* message);
 354   // helper methods to throw exception with complex messages
 355   static void throw_klass_external_name_exception(JavaThread* thread, const char* exception, Klass* klass);
 356   static void throw_class_cast_exception(JavaThread* thread, const char* exception, Klass* caster_klass, Klass* target_klass);
 357 
 358   // Test only function
 359   static jint test_deoptimize_call_int(JavaThread* thread, int value);
 360 };
 361 
 362 // Tracing macros.
 363 
 364 #define IF_TRACE_jvmci_1 if (!(JVMCITraceLevel >= 1)) ; else
 365 #define IF_TRACE_jvmci_2 if (!(JVMCITraceLevel >= 2)) ; else
 366 #define IF_TRACE_jvmci_3 if (!(JVMCITraceLevel >= 3)) ; else
 367 #define IF_TRACE_jvmci_4 if (!(JVMCITraceLevel >= 4)) ; else
 368 #define IF_TRACE_jvmci_5 if (!(JVMCITraceLevel >= 5)) ; else
 369 
 370 #define TRACE_jvmci_1 if (!(JVMCITraceLevel >= 1 && (tty->print(PTR_FORMAT " JVMCITrace-1: ", p2i(JavaThread::current())), true))) ; else tty->print_cr
 371 #define TRACE_jvmci_2 if (!(JVMCITraceLevel >= 2 && (tty->print(PTR_FORMAT "    JVMCITrace-2: ", p2i(JavaThread::current())), true))) ; else tty->print_cr
 372 #define TRACE_jvmci_3 if (!(JVMCITraceLevel >= 3 && (tty->print(PTR_FORMAT "       JVMCITrace-3: ", p2i(JavaThread::current())), true))) ; else tty->print_cr
 373 #define TRACE_jvmci_4 if (!(JVMCITraceLevel >= 4 && (tty->print(PTR_FORMAT "          JVMCITrace-4: ", p2i(JavaThread::current())), true))) ; else tty->print_cr
 374 #define TRACE_jvmci_5 if (!(JVMCITraceLevel >= 5 && (tty->print(PTR_FORMAT "             JVMCITrace-5: ", p2i(JavaThread::current())), true))) ; else tty->print_cr
 375 
 376 #endif // SHARE_JVMCI_JVMCIRUNTIME_HPP