1 /*
  2  * Copyright (c) 1999, 2024, 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 
 25 #ifndef SHARE_CI_CIENV_HPP
 26 #define SHARE_CI_CIENV_HPP
 27 
 28 #include "ci/ciClassList.hpp"
 29 #include "ci/ciObjectFactory.hpp"
 30 #include "classfile/vmClassMacros.hpp"
 31 #include "code/debugInfoRec.hpp"
 32 #include "code/dependencies.hpp"
 33 #include "code/exceptionHandlerTable.hpp"
 34 #include "compiler/compiler_globals.hpp"
 35 #include "compiler/compilerThread.hpp"
 36 #include "compiler/cHeapStringHolder.hpp"
 37 #include "oops/methodData.hpp"
 38 #include "runtime/javaThread.hpp"
 39 
 40 class CompileTask;
 41 class OopMapSet;
 42 class SCCEntry;
 43 
 44 // ciEnv
 45 //
 46 // This class is the top level broker for requests from the compiler
 47 // to the VM.
 48 class ciEnv : StackObj {
 49   CI_PACKAGE_ACCESS_TO
 50   friend class CompileBroker;
 51   friend class Dependencies;  // for get_object, during logging
 52   friend class RecordLocation;
 53   friend class PrepareExtraDataClosure;
 54 
 55 private:
 56   Arena*           _arena;       // Alias for _ciEnv_arena except in init_shared_objects()
 57   Arena            _ciEnv_arena;
 58   ciObjectFactory* _factory;
 59   OopRecorder*     _oop_recorder;
 60   DebugInformationRecorder* _debug_info;
 61   Dependencies*    _dependencies;
 62   CHeapStringHolder _failure_reason;
 63   bool             _inc_decompile_count_on_failure;
 64   int              _compilable;
 65   bool             _break_at_compile;
 66   int              _num_inlined_bytecodes;
 67   CompileTask*     _task;           // faster access to CompilerThread::task
 68   CompileLog*      _log;            // faster access to CompilerThread::log
 69   void*            _compiler_data;  // compiler-specific stuff, if any
 70 
 71   char* _name_buffer;
 72   int   _name_buffer_len;
 73 
 74   // Cache Jvmti state
 75   uint64_t _jvmti_redefinition_count;
 76   bool  _jvmti_can_hotswap_or_post_breakpoint;
 77   bool  _jvmti_can_access_local_variables;
 78   bool  _jvmti_can_post_on_exceptions;
 79   bool  _jvmti_can_pop_frame;
 80   bool  _jvmti_can_get_owned_monitor_info; // includes can_get_owned_monitor_stack_depth_info
 81   bool  _jvmti_can_walk_any_space;
 82 
 83   // Cache DTrace flags
 84   bool  _dtrace_method_probes;
 85   bool  _dtrace_alloc_probes;
 86 
 87   // Distinguished instances of certain ciObjects..
 88   static ciObject*              _null_object_instance;
 89 
 90 #define VM_CLASS_DECL(name, ignore_s) static ciInstanceKlass* _##name;
 91   VM_CLASSES_DO(VM_CLASS_DECL)
 92 #undef VM_CLASS_DECL
 93 
 94   static ciSymbol*        _unloaded_cisymbol;
 95   static ciInstanceKlass* _unloaded_ciinstance_klass;
 96   static ciObjArrayKlass* _unloaded_ciobjarrayklass;
 97 
 98   ciInstance* _NullPointerException_instance;
 99   ciInstance* _ArithmeticException_instance;
100   ciInstance* _ArrayIndexOutOfBoundsException_instance;
101   ciInstance* _ArrayStoreException_instance;
102   ciInstance* _ClassCastException_instance;
103 
104   ciInstance* _the_null_string;      // The Java string "null"
105   ciInstance* _the_min_jint_string; // The Java string "-2147483648"
106 
107   // Look up a klass by name from a particular class loader (the accessor's).
108   // If require_local, result must be defined in that class loader, or null.
109   // If !require_local, a result from remote class loader may be reported,
110   // if sufficient class loader constraints exist such that initiating
111   // a class loading request from the given loader is bound to return
112   // the class defined in the remote loader (or throw an error).
113   //
114   // Return an unloaded klass if !require_local and no class at all is found.
115   //
116   // The CI treats a klass as loaded if it is consistently defined in
117   // another loader, even if it hasn't yet been loaded in all loaders
118   // that could potentially see it via delegation.
119   ciKlass* get_klass_by_name(ciKlass* accessing_klass,
120                              ciSymbol* klass_name,
121                              bool require_local);
122 
123   // Constant pool access.
124   ciKlass*   get_klass_by_index(const constantPoolHandle& cpool,
125                                 int klass_index,
126                                 bool& is_accessible,
127                                 ciInstanceKlass* loading_klass);
128   ciConstant get_constant_by_index(const constantPoolHandle& cpool,
129                                    int pool_index, int cache_index,
130                                    ciInstanceKlass* accessor);
131   ciField*   get_field_by_index(ciInstanceKlass* loading_klass,
132                                 int field_index, Bytecodes::Code bc);
133   ciMethod*  get_method_by_index(const constantPoolHandle& cpool,
134                                  int method_index, Bytecodes::Code bc,
135                                  ciInstanceKlass* loading_klass);
136 
137   // Implementation methods for loading and constant pool access.
138   ciKlass* get_klass_by_name_impl(ciKlass* accessing_klass,
139                                   const constantPoolHandle& cpool,
140                                   ciSymbol* klass_name,
141                                   bool require_local);
142   ciKlass*   get_klass_by_index_impl(const constantPoolHandle& cpool,
143                                      int klass_index,
144                                      bool& is_accessible,
145                                      ciInstanceKlass* loading_klass);
146   ciConstant get_constant_by_index_impl(const constantPoolHandle& cpool,
147                                         int pool_index, int cache_index,
148                                         ciInstanceKlass* loading_klass);
149   ciField*   get_field_by_index_impl(ciInstanceKlass* loading_klass,
150                                      int field_index, Bytecodes::Code bc);
151   ciMethod*  get_method_by_index_impl(const constantPoolHandle& cpool,
152                                       int method_index, Bytecodes::Code bc,
153                                       ciInstanceKlass* loading_klass);
154 
155   // Helper methods
156   bool       check_klass_accessibility(ciKlass* accessing_klass,
157                                       Klass* resolved_klass);
158   Method*    lookup_method(ciInstanceKlass* accessor,
159                            ciKlass*         holder,
160                            Symbol*          name,
161                            Symbol*          sig,
162                            Bytecodes::Code  bc,
163                            constantTag      tag);
164 
165   ciConstant unbox_primitive_value(ciObject* cibox, BasicType expected_bt = T_ILLEGAL);
166   ciConstant get_resolved_constant(const constantPoolHandle& cpool, int obj_index);
167 
168   // Get a ciObject from the object factory.  Ensures uniqueness
169   // of ciObjects.
170   ciObject* get_object(oop o) {
171     if (o == nullptr) {
172       return _null_object_instance;
173     } else {
174       return _factory->get(o);
175     }
176   }
177 
178   ciSymbol* get_symbol(Symbol* o) {
179     if (o == nullptr) {
180       ShouldNotReachHere();
181       return nullptr;
182     } else {
183       return _factory->get_symbol(o);
184     }
185   }
186 
187   ciMetadata* get_metadata(Metadata* o) {
188     if (o == nullptr) {
189       return nullptr;
190     } else {
191       return _factory->get_metadata(o);
192     }
193   }
194 
195   ciMetadata* cached_metadata(Metadata* o) {
196     return _factory->cached_metadata(o);
197   }
198 
199   ciInstance* get_instance(oop o) {
200     if (o == nullptr) return nullptr;
201     return get_object(o)->as_instance();
202   }
203   ciObjArrayKlass* get_obj_array_klass(Klass* o) {
204     if (o == nullptr) return nullptr;
205     return get_metadata(o)->as_obj_array_klass();
206   }
207   ciTypeArrayKlass* get_type_array_klass(Klass* o) {
208     if (o == nullptr) return nullptr;
209     return get_metadata(o)->as_type_array_klass();
210   }
211   ciKlass* get_klass(Klass* o) {
212     if (o == nullptr) return nullptr;
213     return get_metadata(o)->as_klass();
214   }
215   ciInstanceKlass* get_instance_klass(Klass* o) {
216     if (o == nullptr) return nullptr;
217     return get_metadata(o)->as_instance_klass();
218   }
219   ciMethod* get_method(Method* o) {
220     if (o == nullptr) return nullptr;
221     return get_metadata(o)->as_method();
222   }
223   ciMethodData* get_method_data(MethodData* o) {
224     if (o == nullptr) return nullptr;
225     return get_metadata(o)->as_method_data();
226   }
227 
228   ciMethod* get_method_from_handle(Method* method);
229 
230   // Get a ciMethod representing either an unfound method or
231   // a method with an unloaded holder.  Ensures uniqueness of
232   // the result.
233   ciMethod* get_unloaded_method(ciKlass*         holder,
234                                 ciSymbol*        name,
235                                 ciSymbol*        signature,
236                                 ciInstanceKlass* accessor) {
237     ciInstanceKlass* declared_holder = get_instance_klass_for_declared_method_holder(holder);
238     return _factory->get_unloaded_method(declared_holder, name, signature, accessor);
239   }
240 
241   // Get a ciKlass representing an unloaded klass.
242   // Ensures uniqueness of the result.
243   ciKlass* get_unloaded_klass(ciKlass*  accessing_klass,
244                               ciSymbol* name) {
245     return _factory->get_unloaded_klass(accessing_klass, name, true);
246   }
247 
248   // Get a ciKlass representing an unloaded klass mirror.
249   // Result is not necessarily unique, but will be unloaded.
250   ciInstance* get_unloaded_klass_mirror(ciKlass* type) {
251     return _factory->get_unloaded_klass_mirror(type);
252   }
253 
254   // Get a ciInstance representing an unresolved method handle constant.
255   ciInstance* get_unloaded_method_handle_constant(ciKlass*  holder,
256                                                   ciSymbol* name,
257                                                   ciSymbol* signature,
258                                                   int       ref_kind) {
259     return _factory->get_unloaded_method_handle_constant(holder, name, signature, ref_kind);
260   }
261 
262   // Get a ciInstance representing an unresolved method type constant.
263   ciInstance* get_unloaded_method_type_constant(ciSymbol* signature) {
264     return _factory->get_unloaded_method_type_constant(signature);
265   }
266 
267   // See if we already have an unloaded klass for the given name
268   // or return null if not.
269   ciKlass *check_get_unloaded_klass(ciKlass*  accessing_klass, ciSymbol* name) {
270     return _factory->get_unloaded_klass(accessing_klass, name, false);
271   }
272 
273   // Get a ciReturnAddress corresponding to the given bci.
274   // Ensures uniqueness of the result.
275   ciReturnAddress* get_return_address(int bci) {
276     return _factory->get_return_address(bci);
277   }
278 
279   // Get a ciMethodData representing the methodData for a method
280   // with none.
281   ciMethodData* get_empty_methodData() {
282     return _factory->get_empty_methodData();
283   }
284 
285   // General utility : get a buffer of some required length.
286   // Used in symbol creation.
287   char* name_buffer(int req_len);
288 
289   // Is this thread currently in the VM state?
290   static bool is_in_vm();
291 
292   // Helper routine for determining the validity of a compilation with
293   // respect to method dependencies (e.g. concurrent class loading).
294   void validate_compile_task_dependencies(ciMethod* target);
295 public:
296   enum {
297     MethodCompilable,
298     MethodCompilable_not_at_tier,
299     MethodCompilable_never
300   };
301 
302   ciEnv(CompileTask* task);
303   // Used only during initialization of the ci
304   ciEnv(Arena* arena);
305   ~ciEnv();
306 
307   OopRecorder* oop_recorder() { return _oop_recorder; }
308   void set_oop_recorder(OopRecorder* r) { _oop_recorder = r; }
309 
310   DebugInformationRecorder* debug_info() { return _debug_info; }
311   void set_debug_info(DebugInformationRecorder* i) { _debug_info = i; }
312 
313   Dependencies* dependencies() { return _dependencies; }
314   void set_dependencies(Dependencies* d) { _dependencies = d; }
315 
316   // This is true if the compilation is not going to produce code.
317   // (It is reasonable to retry failed compilations.)
318   bool failing() const { return _failure_reason.get() != nullptr; }
319 
320   // Reason this compilation is failing, such as "too many basic blocks".
321   const char* failure_reason() const { return _failure_reason.get(); }
322 
323   // Return state of appropriate compatibility
324   int compilable() { return _compilable; }
325 
326   const char* retry_message() const {
327     switch (_compilable) {
328       case ciEnv::MethodCompilable_not_at_tier:
329         return "retry at different tier";
330       case ciEnv::MethodCompilable_never:
331         return "not retryable";
332       case ciEnv::MethodCompilable:
333         return nullptr;
334       default:
335         ShouldNotReachHere();
336         return nullptr;
337     }
338   }
339 
340   bool break_at_compile() { return _break_at_compile; }
341   void set_break_at_compile(bool z) { _break_at_compile = z; }
342 
343   // Cache Jvmti state
344   bool  cache_jvmti_state();
345   bool  jvmti_state_changed() const;
346   bool  should_retain_local_variables() const {
347     return _jvmti_can_access_local_variables || _jvmti_can_pop_frame;
348   }
349   bool  jvmti_can_hotswap_or_post_breakpoint() const { return _jvmti_can_hotswap_or_post_breakpoint; }
350   bool  jvmti_can_post_on_exceptions()         const { return _jvmti_can_post_on_exceptions; }
351   bool  jvmti_can_get_owned_monitor_info()     const { return _jvmti_can_get_owned_monitor_info; }
352   bool  jvmti_can_walk_any_space()             const { return _jvmti_can_walk_any_space; }
353 
354   // Cache DTrace flags
355   void  cache_dtrace_flags();
356   bool  dtrace_method_probes()   const { return _dtrace_method_probes; }
357   bool  dtrace_alloc_probes()    const { return _dtrace_alloc_probes; }
358 
359   // The compiler task which has created this env.
360   // May be useful to find out compile_id, comp_level, etc.
361   CompileTask* task() const { return _task; }
362 
363   // Handy forwards to the task:
364   int comp_level();   // task()->comp_level()
365   int compile_id();  // task()->compile_id()
366 
367   // Register the result of a compilation.
368   void register_method(ciMethod*                 target,
369                        int                       entry_bci,
370                        CodeOffsets*              offsets,
371                        int                       orig_pc_offset,
372                        CodeBuffer*               code_buffer,
373                        int                       frame_words,
374                        OopMapSet*                oop_map_set,
375                        ExceptionHandlerTable*    handler_table,
376                        ImplicitExceptionTable*   inc_table,
377                        AbstractCompiler*         compiler,
378                        bool                      has_clinit_barriers,
379                        bool                      for_preload,
380                        bool                      has_unsafe_access,
381                        bool                      has_wide_vectors,
382                        bool                      has_monitors,
383                        bool                      has_scoped_access,
384                        int                       immediate_oops_patched,
385                        bool                      install_code,
386                        SCCEntry*                 entry = nullptr);
387 
388   // Access to certain well known ciObjects.
389 #define VM_CLASS_FUNC(name, ignore_s) \
390   ciInstanceKlass* name() { \
391     return _##name;\
392   }
393   VM_CLASSES_DO(VM_CLASS_FUNC)
394 #undef VM_CLASS_FUNC
395 
396   ciInstance* NullPointerException_instance() {
397     assert(_NullPointerException_instance != nullptr, "initialization problem");
398     return _NullPointerException_instance;
399   }
400   ciInstance* ArithmeticException_instance() {
401     assert(_ArithmeticException_instance != nullptr, "initialization problem");
402     return _ArithmeticException_instance;
403   }
404   ciInstance* ArrayIndexOutOfBoundsException_instance() {
405     assert(_ArrayIndexOutOfBoundsException_instance != nullptr, "initialization problem");
406     return _ArrayIndexOutOfBoundsException_instance;
407   }
408   ciInstance* ArrayStoreException_instance() {
409     assert(_ArrayStoreException_instance != nullptr, "initialization problem");
410     return _ArrayStoreException_instance;
411   }
412   ciInstance* ClassCastException_instance() {
413     assert(_ClassCastException_instance != nullptr, "initialization problem");
414     return _ClassCastException_instance;
415   }
416 
417   ciInstance* the_null_string();
418   ciInstance* the_min_jint_string();
419 
420   static ciSymbol* unloaded_cisymbol() {
421     return _unloaded_cisymbol;
422   }
423   static ciObjArrayKlass* unloaded_ciobjarrayklass() {
424     return _unloaded_ciobjarrayklass;
425   }
426   static ciInstanceKlass* unloaded_ciinstance_klass() {
427     return _unloaded_ciinstance_klass;
428   }
429   ciInstance* unloaded_ciinstance();
430 
431   ciInstanceKlass* get_box_klass_for_primitive_type(BasicType type);
432 
433   ciKlass*  find_system_klass(ciSymbol* klass_name);
434 
435   // Note:  To find a class from its name string, use ciSymbol::make,
436   // but consider adding to vmSymbols.hpp instead.
437 
438   // converts the ciKlass* representing the holder of a method into a
439   // ciInstanceKlass*.  This is needed since the holder of a method in
440   // the bytecodes could be an array type.  Basically this converts
441   // array types into java/lang/Object and other types stay as they are.
442   static ciInstanceKlass* get_instance_klass_for_declared_method_holder(ciKlass* klass);
443 
444   // Access to the compile-lifetime allocation arena.
445   Arena*    arena() { return _arena; }
446 
447   // What is the current compilation environment?
448   static ciEnv* current() { return CompilerThread::current()->env(); }
449 
450   // Overload with current thread argument
451   static ciEnv* current(CompilerThread *thread) { return thread->env(); }
452 
453   // Per-compiler data.  (Used by C2 to publish the Compile* pointer.)
454   void* compiler_data() const { return _compiler_data; }
455   void set_compiler_data(void* x) { _compiler_data = x; }
456 
457   // Notice that a method has been inlined in the current compile;
458   // used only for statistics.
459   void notice_inlined_method(ciMethod* method);
460 
461   // Total number of bytecodes in inlined methods in this compile
462   int num_inlined_bytecodes() const;
463 
464   // Output stream for logging compilation info.
465   CompileLog* log() { return _log; }
466   void set_log(CompileLog* log) { _log = log; }
467 
468   void record_failure(const char* reason);      // Record failure and report later
469   void report_failure(const char* reason);      // Report failure immediately
470   void record_method_not_compilable(const char* reason, bool all_tiers = false);
471   void record_out_of_memory_failure();
472 
473   // RedefineClasses support
474   void metadata_do(MetadataClosure* f) { _factory->metadata_do(f); }
475 
476 private:
477   SCCEntry* _scc_clinit_barriers_entry;
478 
479 public:
480   void  set_scc_clinit_barriers_entry(SCCEntry* entry) { _scc_clinit_barriers_entry = entry; }
481   SCCEntry* scc_clinit_barriers_entry()          const { return _scc_clinit_barriers_entry; }
482 
483   // Replay support
484 private:
485   static int klass_compare(const InstanceKlass* const &ik1, const InstanceKlass* const &ik2) {
486     if (ik1 > ik2) {
487       return 1;
488     } else if (ik1 < ik2) {
489       return -1;
490     } else {
491       return 0;
492     }
493   }
494   bool dyno_loc(const InstanceKlass* ik, const char *&loc) const;
495   void set_dyno_loc(const InstanceKlass* ik);
496   void record_best_dyno_loc(const InstanceKlass* ik);
497   bool print_dyno_loc(outputStream* out, const InstanceKlass* ik) const;
498 
499   GrowableArray<const InstanceKlass*>* _dyno_klasses;
500   GrowableArray<const char *>*         _dyno_locs;
501 
502 #define MAX_DYNO_NAME_LENGTH 1024
503   char _dyno_name[MAX_DYNO_NAME_LENGTH+1];
504 
505 public:
506   // Dump the compilation replay data for the ciEnv to the stream.
507   void dump_replay_data(int compile_id);
508   void dump_inline_data(int compile_id);
509   void dump_replay_data(outputStream* out);
510   void dump_replay_data_unsafe(outputStream* out);
511   void dump_replay_data_helper(outputStream* out);
512   void dump_compile_data(outputStream* out);
513   void dump_replay_data_version(outputStream* out);
514 
515   const char *dyno_name(const InstanceKlass* ik) const;
516   const char *replay_name(const InstanceKlass* ik) const;
517   const char *replay_name(ciKlass* i) const;
518 
519   void record_lambdaform(Thread* thread, oop obj);
520   void record_member(Thread* thread, oop obj);
521   void record_mh(Thread* thread, oop obj);
522   void record_call_site_obj(Thread* thread, oop obj);
523   void record_call_site_method(Thread* thread, Method* adapter);
524   void process_invokedynamic(const constantPoolHandle &cp, int index, JavaThread* thread);
525   void process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread);
526   void find_dynamic_call_sites();
527 
528   bool is_precompiled();
529   bool is_fully_initialized(InstanceKlass* ik);
530   InstanceKlass::ClassState compute_init_state_for_precompiled(InstanceKlass* ik);
531 };
532 
533 #endif // SHARE_CI_CIENV_HPP