1 /*
2  * Copyright (c) 1999, 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 
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "ci/ciConstant.hpp"
28 #include "ci/ciEnv.hpp"
29 #include "ci/ciField.hpp"
30 #include "ci/ciInstance.hpp"
31 #include "ci/ciInstanceKlass.hpp"
32 #include "ci/ciMethod.hpp"
33 #include "ci/ciNullObject.hpp"
34 #include "ci/ciReplay.hpp"
35 #include "ci/ciUtilities.inline.hpp"
36 #include "classfile/systemDictionary.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "code/codeCache.hpp"
39 #include "code/scopeDesc.hpp"
40 #include "compiler/compileBroker.hpp"
41 #include "compiler/compileLog.hpp"
42 #include "compiler/disassembler.hpp"
43 #include "gc/shared/collectedHeap.inline.hpp"
44 #include "interpreter/linkResolver.hpp"
45 #include "jfr/jfrEvents.hpp"
46 #include "memory/allocation.inline.hpp"
47 #include "memory/oopFactory.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/constantPool.inline.hpp"
51 #include "oops/cpCache.inline.hpp"
52 #include "oops/method.inline.hpp"
53 #include "oops/methodData.hpp"
54 #include "oops/objArrayKlass.hpp"
55 #include "oops/objArrayOop.inline.hpp"
56 #include "oops/oop.inline.hpp"
57 #include "prims/jvmtiExport.hpp"
58 #include "runtime/init.hpp"
59 #include "runtime/reflection.hpp"
60 #include "runtime/jniHandles.inline.hpp"
61 #include "runtime/safepointVerifiers.hpp"
62 #include "runtime/sharedRuntime.hpp"
63 #include "runtime/thread.inline.hpp"
64 #include "utilities/dtrace.hpp"
65 #include "utilities/macros.hpp"
66 #ifdef COMPILER1
67 #include "c1/c1_Runtime1.hpp"
68 #endif
69 #ifdef COMPILER2
70 #include "opto/runtime.hpp"
71 #endif
72 
73 // ciEnv
74 //
75 // This class is the top level broker for requests from the compiler
76 // to the VM.
77 
78 ciObject*              ciEnv::_null_object_instance;
79 
80 #define WK_KLASS_DEFN(name, ignore_s, ignore_o) ciInstanceKlass* ciEnv::_##name = NULL;
81 WK_KLASSES_DO(WK_KLASS_DEFN)
82 #undef WK_KLASS_DEFN
83 
84 ciSymbol*        ciEnv::_unloaded_cisymbol = NULL;
85 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;
86 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;
87 
88 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;
89 jobject ciEnv::_ArrayStoreException_handle = NULL;
90 jobject ciEnv::_ClassCastException_handle = NULL;
91 
92 #ifndef PRODUCT
93 static bool firstEnv = true;
94 #endif /* PRODUCT */
95 
96 // ------------------------------------------------------------------
97 // ciEnv::ciEnv
ciEnv(CompileTask * task,int system_dictionary_modification_counter)98 ciEnv::ciEnv(CompileTask* task, int system_dictionary_modification_counter)
99   : _ciEnv_arena(mtCompiler) {
100   VM_ENTRY_MARK;
101 
102   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
103   thread->set_env(this);
104   assert(ciEnv::current() == this, "sanity");
105 
106   _oop_recorder = NULL;
107   _debug_info = NULL;
108   _dependencies = NULL;
109   _failure_reason = NULL;
110   _inc_decompile_count_on_failure = true;
111   _compilable = MethodCompilable;
112   _break_at_compile = false;
113   _compiler_data = NULL;
114 #ifndef PRODUCT
115   assert(!firstEnv, "not initialized properly");
116 #endif /* !PRODUCT */
117 
118   _system_dictionary_modification_counter = system_dictionary_modification_counter;
119   _num_inlined_bytecodes = 0;
120   assert(task == NULL || thread->task() == task, "sanity");
121   if (task != NULL) {
122     task->mark_started(os::elapsed_counter());
123   }
124   _task = task;
125   _log = NULL;
126 
127   // Temporary buffer for creating symbols and such.
128   _name_buffer = NULL;
129   _name_buffer_len = 0;
130 
131   _arena   = &_ciEnv_arena;
132   _factory = new (_arena) ciObjectFactory(_arena, 128);
133 
134   // Preload commonly referenced system ciObjects.
135 
136   // During VM initialization, these instances have not yet been created.
137   // Assertions ensure that these instances are not accessed before
138   // their initialization.
139 
140   assert(Universe::is_fully_initialized(), "should be complete");
141 
142   oop o = Universe::null_ptr_exception_instance();
143   assert(o != NULL, "should have been initialized");
144   _NullPointerException_instance = get_object(o)->as_instance();
145   o = Universe::arithmetic_exception_instance();
146   assert(o != NULL, "should have been initialized");
147   _ArithmeticException_instance = get_object(o)->as_instance();
148 
149   _ArrayIndexOutOfBoundsException_instance = NULL;
150   _ArrayStoreException_instance = NULL;
151   _ClassCastException_instance = NULL;
152   _the_null_string = NULL;
153   _the_min_jint_string = NULL;
154 
155   _jvmti_can_hotswap_or_post_breakpoint = false;
156   _jvmti_can_access_local_variables = false;
157   _jvmti_can_post_on_exceptions = false;
158   _jvmti_can_pop_frame = false;
159 }
160 
ciEnv(Arena * arena)161 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) {
162   ASSERT_IN_VM;
163 
164   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
165   CompilerThread* current_thread = CompilerThread::current();
166   assert(current_thread->env() == NULL, "must be");
167   current_thread->set_env(this);
168   assert(ciEnv::current() == this, "sanity");
169 
170   _oop_recorder = NULL;
171   _debug_info = NULL;
172   _dependencies = NULL;
173   _failure_reason = NULL;
174   _inc_decompile_count_on_failure = true;
175   _compilable = MethodCompilable_never;
176   _break_at_compile = false;
177   _compiler_data = NULL;
178 #ifndef PRODUCT
179   assert(firstEnv, "must be first");
180   firstEnv = false;
181 #endif /* !PRODUCT */
182 
183   _system_dictionary_modification_counter = 0;
184   _num_inlined_bytecodes = 0;
185   _task = NULL;
186   _log = NULL;
187 
188   // Temporary buffer for creating symbols and such.
189   _name_buffer = NULL;
190   _name_buffer_len = 0;
191 
192   _arena   = arena;
193   _factory = new (_arena) ciObjectFactory(_arena, 128);
194 
195   // Preload commonly referenced system ciObjects.
196 
197   // During VM initialization, these instances have not yet been created.
198   // Assertions ensure that these instances are not accessed before
199   // their initialization.
200 
201   assert(Universe::is_fully_initialized(), "must be");
202 
203   _NullPointerException_instance = NULL;
204   _ArithmeticException_instance = NULL;
205   _ArrayIndexOutOfBoundsException_instance = NULL;
206   _ArrayStoreException_instance = NULL;
207   _ClassCastException_instance = NULL;
208   _the_null_string = NULL;
209   _the_min_jint_string = NULL;
210 
211   _jvmti_can_hotswap_or_post_breakpoint = false;
212   _jvmti_can_access_local_variables = false;
213   _jvmti_can_post_on_exceptions = false;
214   _jvmti_can_pop_frame = false;
215 }
216 
~ciEnv()217 ciEnv::~ciEnv() {
218   GUARDED_VM_ENTRY(
219       CompilerThread* current_thread = CompilerThread::current();
220       _factory->remove_symbols();
221       // Need safepoint to clear the env on the thread.  RedefineClasses might
222       // be reading it.
223       current_thread->set_env(NULL);
224   )
225 }
226 
227 // ------------------------------------------------------------------
228 // Cache Jvmti state
cache_jvmti_state()229 void ciEnv::cache_jvmti_state() {
230   VM_ENTRY_MARK;
231   // Get Jvmti capabilities under lock to get consistant values.
232   MutexLocker mu(JvmtiThreadState_lock);
233   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
234   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
235   _jvmti_can_post_on_exceptions         = JvmtiExport::can_post_on_exceptions();
236   _jvmti_can_pop_frame                  = JvmtiExport::can_pop_frame();
237   _jvmti_can_get_owned_monitor_info     = JvmtiExport::can_get_owned_monitor_info();
238 }
239 
jvmti_state_changed() const240 bool ciEnv::jvmti_state_changed() const {
241   if (!_jvmti_can_access_local_variables &&
242       JvmtiExport::can_access_local_variables()) {
243     return true;
244   }
245   if (!_jvmti_can_hotswap_or_post_breakpoint &&
246       JvmtiExport::can_hotswap_or_post_breakpoint()) {
247     return true;
248   }
249   if (!_jvmti_can_post_on_exceptions &&
250       JvmtiExport::can_post_on_exceptions()) {
251     return true;
252   }
253   if (!_jvmti_can_pop_frame &&
254       JvmtiExport::can_pop_frame()) {
255     return true;
256   }
257   return false;
258 }
259 
260 // ------------------------------------------------------------------
261 // Cache DTrace flags
cache_dtrace_flags()262 void ciEnv::cache_dtrace_flags() {
263   // Need lock?
264   _dtrace_extended_probes = ExtendedDTraceProbes;
265   if (_dtrace_extended_probes) {
266     _dtrace_monitor_probes  = true;
267     _dtrace_method_probes   = true;
268     _dtrace_alloc_probes    = true;
269   } else {
270     _dtrace_monitor_probes  = DTraceMonitorProbes;
271     _dtrace_method_probes   = DTraceMethodProbes;
272     _dtrace_alloc_probes    = DTraceAllocProbes;
273   }
274 }
275 
276 // ------------------------------------------------------------------
277 // helper for lazy exception creation
get_or_create_exception(jobject & handle,Symbol * name)278 ciInstance* ciEnv::get_or_create_exception(jobject& handle, Symbol* name) {
279   VM_ENTRY_MARK;
280   if (handle == NULL) {
281     // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.
282     Klass* k = SystemDictionary::find(name, Handle(), Handle(), THREAD);
283     jobject objh = NULL;
284     if (!HAS_PENDING_EXCEPTION && k != NULL) {
285       oop obj = InstanceKlass::cast(k)->allocate_instance(THREAD);
286       if (!HAS_PENDING_EXCEPTION)
287         objh = JNIHandles::make_global(Handle(THREAD, obj));
288     }
289     if (HAS_PENDING_EXCEPTION) {
290       CLEAR_PENDING_EXCEPTION;
291     } else {
292       handle = objh;
293     }
294   }
295   oop obj = JNIHandles::resolve(handle);
296   return obj == NULL? NULL: get_object(obj)->as_instance();
297 }
298 
ArrayIndexOutOfBoundsException_instance()299 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
300   if (_ArrayIndexOutOfBoundsException_instance == NULL) {
301     _ArrayIndexOutOfBoundsException_instance
302           = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,
303           vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
304   }
305   return _ArrayIndexOutOfBoundsException_instance;
306 }
ArrayStoreException_instance()307 ciInstance* ciEnv::ArrayStoreException_instance() {
308   if (_ArrayStoreException_instance == NULL) {
309     _ArrayStoreException_instance
310           = get_or_create_exception(_ArrayStoreException_handle,
311           vmSymbols::java_lang_ArrayStoreException());
312   }
313   return _ArrayStoreException_instance;
314 }
ClassCastException_instance()315 ciInstance* ciEnv::ClassCastException_instance() {
316   if (_ClassCastException_instance == NULL) {
317     _ClassCastException_instance
318           = get_or_create_exception(_ClassCastException_handle,
319           vmSymbols::java_lang_ClassCastException());
320   }
321   return _ClassCastException_instance;
322 }
323 
the_null_string()324 ciInstance* ciEnv::the_null_string() {
325   if (_the_null_string == NULL) {
326     VM_ENTRY_MARK;
327     _the_null_string = get_object(Universe::the_null_string())->as_instance();
328   }
329   return _the_null_string;
330 }
331 
the_min_jint_string()332 ciInstance* ciEnv::the_min_jint_string() {
333   if (_the_min_jint_string == NULL) {
334     VM_ENTRY_MARK;
335     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
336   }
337   return _the_min_jint_string;
338 }
339 
340 // ------------------------------------------------------------------
341 // ciEnv::get_method_from_handle
get_method_from_handle(Method * method)342 ciMethod* ciEnv::get_method_from_handle(Method* method) {
343   VM_ENTRY_MARK;
344   return get_metadata(method)->as_method();
345 }
346 
347 // ------------------------------------------------------------------
348 // ciEnv::array_element_offset_in_bytes
array_element_offset_in_bytes(ciArray * a_h,ciObject * o_h)349 int ciEnv::array_element_offset_in_bytes(ciArray* a_h, ciObject* o_h) {
350   VM_ENTRY_MARK;
351   objArrayOop a = (objArrayOop)a_h->get_oop();
352   assert(a->is_objArray(), "");
353   int length = a->length();
354   oop o = o_h->get_oop();
355   for (int i = 0; i < length; i++) {
356     if (a->obj_at(i) == o)  return i;
357   }
358   return -1;
359 }
360 
361 
362 // ------------------------------------------------------------------
363 // ciEnv::check_klass_accessiblity
364 //
365 // Note: the logic of this method should mirror the logic of
366 // ConstantPool::verify_constant_pool_resolve.
check_klass_accessibility(ciKlass * accessing_klass,Klass * resolved_klass)367 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
368                                       Klass* resolved_klass) {
369   if (accessing_klass == NULL || !accessing_klass->is_loaded()) {
370     return true;
371   }
372   if (accessing_klass->is_obj_array_klass()) {
373     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
374   }
375   if (!accessing_klass->is_instance_klass()) {
376     return true;
377   }
378   if (!_jvmti_can_get_owned_monitor_info &&
379       JvmtiExport::can_get_owned_monitor_info()) {
380     return true;
381   }
382 
383   if (resolved_klass->is_objArray_klass()) {
384     // Find the element klass, if this is an array.
385     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
386   }
387   if (resolved_klass->is_instance_klass()) {
388     return (Reflection::verify_class_access(accessing_klass->get_Klass(),
389                                             InstanceKlass::cast(resolved_klass),
390                                             true) == Reflection::ACCESS_OK);
391   }
392   return true;
393 }
394 
395 // ------------------------------------------------------------------
396 // ciEnv::get_klass_by_name_impl
get_klass_by_name_impl(ciKlass * accessing_klass,const constantPoolHandle & cpool,ciSymbol * name,bool require_local)397 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
398                                        const constantPoolHandle& cpool,
399                                        ciSymbol* name,
400                                        bool require_local) {
401   ASSERT_IN_VM;
402   EXCEPTION_CONTEXT;
403 
404   // Now we need to check the SystemDictionary
405   Symbol* sym = name->get_symbol();
406   if (sym->byte_at(0) == 'L' &&
407     sym->byte_at(sym->utf8_length()-1) == ';') {
408     // This is a name from a signature.  Strip off the trimmings.
409     // Call recursive to keep scope of strippedsym.
410     TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1,
411                     sym->utf8_length()-2,
412                     KILL_COMPILE_ON_FATAL_(_unloaded_ciinstance_klass));
413     ciSymbol* strippedname = get_symbol(strippedsym);
414     return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
415   }
416 
417   // Check for prior unloaded klass.  The SystemDictionary's answers
418   // can vary over time but the compiler needs consistency.
419   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
420   if (unloaded_klass != NULL) {
421     if (require_local)  return NULL;
422     return unloaded_klass;
423   }
424 
425   Handle loader(THREAD, (oop)NULL);
426   Handle domain(THREAD, (oop)NULL);
427   if (accessing_klass != NULL) {
428     loader = Handle(THREAD, accessing_klass->loader());
429     domain = Handle(THREAD, accessing_klass->protection_domain());
430   }
431 
432   // setup up the proper type to return on OOM
433   ciKlass* fail_type;
434   if (sym->byte_at(0) == '[') {
435     fail_type = _unloaded_ciobjarrayklass;
436   } else {
437     fail_type = _unloaded_ciinstance_klass;
438   }
439   Klass* found_klass;
440   {
441     ttyUnlocker ttyul;  // release tty lock to avoid ordering problems
442     MutexLocker ml(Compile_lock);
443     Klass* kls;
444     if (!require_local) {
445       kls = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
446                                                                        KILL_COMPILE_ON_FATAL_(fail_type));
447     } else {
448       kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
449                                                            KILL_COMPILE_ON_FATAL_(fail_type));
450     }
451     found_klass = kls;
452   }
453 
454   // If we fail to find an array klass, look again for its element type.
455   // The element type may be available either locally or via constraints.
456   // In either case, if we can find the element type in the system dictionary,
457   // we must build an array type around it.  The CI requires array klasses
458   // to be loaded if their element klasses are loaded, except when memory
459   // is exhausted.
460   if (sym->byte_at(0) == '[' &&
461       (sym->byte_at(1) == '[' || sym->byte_at(1) == 'L')) {
462     // We have an unloaded array.
463     // Build it on the fly if the element class exists.
464     TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1,
465                                                  sym->utf8_length()-1,
466                                                  KILL_COMPILE_ON_FATAL_(fail_type));
467 
468     // Get element ciKlass recursively.
469     ciKlass* elem_klass =
470       get_klass_by_name_impl(accessing_klass,
471                              cpool,
472                              get_symbol(elem_sym),
473                              require_local);
474     if (elem_klass != NULL && elem_klass->is_loaded()) {
475       // Now make an array for it
476       return ciObjArrayKlass::make_impl(elem_klass);
477     }
478   }
479 
480   if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {
481     // Look inside the constant pool for pre-resolved class entries.
482     for (int i = cpool->length() - 1; i >= 1; i--) {
483       if (cpool->tag_at(i).is_klass()) {
484         Klass* kls = cpool->resolved_klass_at(i);
485         if (kls->name() == sym) {
486           found_klass = kls;
487           break;
488         }
489       }
490     }
491   }
492 
493   if (found_klass != NULL) {
494     // Found it.  Build a CI handle.
495     return get_klass(found_klass);
496   }
497 
498   if (require_local)  return NULL;
499 
500   // Not yet loaded into the VM, or not governed by loader constraints.
501   // Make a CI representative for it.
502   return get_unloaded_klass(accessing_klass, name);
503 }
504 
505 // ------------------------------------------------------------------
506 // ciEnv::get_klass_by_name
get_klass_by_name(ciKlass * accessing_klass,ciSymbol * klass_name,bool require_local)507 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
508                                   ciSymbol* klass_name,
509                                   bool require_local) {
510   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
511                                                  constantPoolHandle(),
512                                                  klass_name,
513                                                  require_local);)
514 }
515 
516 // ------------------------------------------------------------------
517 // ciEnv::get_klass_by_index_impl
518 //
519 // Implementation of get_klass_by_index.
get_klass_by_index_impl(const constantPoolHandle & cpool,int index,bool & is_accessible,ciInstanceKlass * accessor)520 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
521                                         int index,
522                                         bool& is_accessible,
523                                         ciInstanceKlass* accessor) {
524   EXCEPTION_CONTEXT;
525   Klass* klass = NULL;
526   Symbol* klass_name = NULL;
527 
528   if (cpool->tag_at(index).is_symbol()) {
529     klass_name = cpool->symbol_at(index);
530   } else {
531     // Check if it's resolved if it's not a symbol constant pool entry.
532     klass =  ConstantPool::klass_at_if_loaded(cpool, index);
533     // Try to look it up by name.
534     if (klass == NULL) {
535       klass_name = cpool->klass_name_at(index);
536     }
537   }
538 
539   if (klass == NULL) {
540     // Not found in constant pool.  Use the name to do the lookup.
541     ciKlass* k = get_klass_by_name_impl(accessor,
542                                         cpool,
543                                         get_symbol(klass_name),
544                                         false);
545     // Calculate accessibility the hard way.
546     if (!k->is_loaded()) {
547       is_accessible = false;
548     } else if (k->loader() != accessor->loader() &&
549                get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {
550       // Loaded only remotely.  Not linked yet.
551       is_accessible = false;
552     } else {
553       // Linked locally, and we must also check public/private, etc.
554       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
555     }
556     return k;
557   }
558 
559   // Check for prior unloaded klass.  The SystemDictionary's answers
560   // can vary over time but the compiler needs consistency.
561   ciSymbol* name = get_symbol(klass->name());
562   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
563   if (unloaded_klass != NULL) {
564     is_accessible = false;
565     return unloaded_klass;
566   }
567 
568   // It is known to be accessible, since it was found in the constant pool.
569   is_accessible = true;
570   return get_klass(klass);
571 }
572 
573 // ------------------------------------------------------------------
574 // ciEnv::get_klass_by_index
575 //
576 // Get a klass from the constant pool.
get_klass_by_index(const constantPoolHandle & cpool,int index,bool & is_accessible,ciInstanceKlass * accessor)577 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
578                                    int index,
579                                    bool& is_accessible,
580                                    ciInstanceKlass* accessor) {
581   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
582 }
583 
584 // ------------------------------------------------------------------
585 // ciEnv::get_constant_by_index_impl
586 //
587 // Implementation of get_constant_by_index().
get_constant_by_index_impl(const constantPoolHandle & cpool,int pool_index,int cache_index,ciInstanceKlass * accessor)588 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
589                                              int pool_index, int cache_index,
590                                              ciInstanceKlass* accessor) {
591   bool ignore_will_link;
592   EXCEPTION_CONTEXT;
593   int index = pool_index;
594   if (cache_index >= 0) {
595     assert(index < 0, "only one kind of index at a time");
596     index = cpool->object_to_cp_index(cache_index);
597     oop obj = cpool->resolved_references()->obj_at(cache_index);
598     if (obj != NULL) {
599       if (obj == Universe::the_null_sentinel()) {
600         return ciConstant(T_OBJECT, get_object(NULL));
601       }
602       BasicType bt = T_OBJECT;
603       if (cpool->tag_at(index).is_dynamic_constant())
604         bt = FieldType::basic_type(cpool->uncached_signature_ref_at(index));
605       if (is_reference_type(bt)) {
606       } else {
607         // we have to unbox the primitive value
608         if (!is_java_primitive(bt))  return ciConstant();
609         jvalue value;
610         BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);
611         assert(bt2 == bt, "");
612         switch (bt2) {
613         case T_DOUBLE:  return ciConstant(value.d);
614         case T_FLOAT:   return ciConstant(value.f);
615         case T_LONG:    return ciConstant(value.j);
616         case T_INT:     return ciConstant(bt2, value.i);
617         case T_SHORT:   return ciConstant(bt2, value.s);
618         case T_BYTE:    return ciConstant(bt2, value.b);
619         case T_CHAR:    return ciConstant(bt2, value.c);
620         case T_BOOLEAN: return ciConstant(bt2, value.z);
621         default:  return ciConstant();
622         }
623       }
624       ciObject* ciobj = get_object(obj);
625       if (ciobj->is_array()) {
626         return ciConstant(T_ARRAY, ciobj);
627       } else {
628         assert(ciobj->is_instance(), "should be an instance");
629         return ciConstant(T_OBJECT, ciobj);
630       }
631     }
632   }
633   constantTag tag = cpool->tag_at(index);
634   if (tag.is_int()) {
635     return ciConstant(T_INT, (jint)cpool->int_at(index));
636   } else if (tag.is_long()) {
637     return ciConstant((jlong)cpool->long_at(index));
638   } else if (tag.is_float()) {
639     return ciConstant((jfloat)cpool->float_at(index));
640   } else if (tag.is_double()) {
641     return ciConstant((jdouble)cpool->double_at(index));
642   } else if (tag.is_string()) {
643     oop string = NULL;
644     assert(cache_index >= 0, "should have a cache index");
645     if (cpool->is_pseudo_string_at(index)) {
646       string = cpool->pseudo_string_at(index, cache_index);
647     } else {
648       string = cpool->string_at(index, cache_index, THREAD);
649       if (HAS_PENDING_EXCEPTION) {
650         CLEAR_PENDING_EXCEPTION;
651         record_out_of_memory_failure();
652         return ciConstant();
653       }
654     }
655     ciObject* constant = get_object(string);
656     if (constant->is_array()) {
657       return ciConstant(T_ARRAY, constant);
658     } else {
659       assert (constant->is_instance(), "must be an instance, or not? ");
660       return ciConstant(T_OBJECT, constant);
661     }
662   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
663     // 4881222: allow ldc to take a class type
664     ciKlass* klass = get_klass_by_index_impl(cpool, index, ignore_will_link, accessor);
665     if (HAS_PENDING_EXCEPTION) {
666       CLEAR_PENDING_EXCEPTION;
667       record_out_of_memory_failure();
668       return ciConstant();
669     }
670     assert (klass->is_instance_klass() || klass->is_array_klass(),
671             "must be an instance or array klass ");
672     return ciConstant(T_OBJECT, klass->java_mirror());
673   } else if (tag.is_method_type()) {
674     // must execute Java code to link this CP entry into cache[i].f1
675     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
676     ciObject* ciobj = get_unloaded_method_type_constant(signature);
677     return ciConstant(T_OBJECT, ciobj);
678   } else if (tag.is_method_handle()) {
679     // must execute Java code to link this CP entry into cache[i].f1
680     int ref_kind        = cpool->method_handle_ref_kind_at(index);
681     int callee_index    = cpool->method_handle_klass_index_at(index);
682     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
683     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
684     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
685     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
686     return ciConstant(T_OBJECT, ciobj);
687   } else if (tag.is_dynamic_constant()) {
688     return ciConstant();
689   } else {
690     ShouldNotReachHere();
691     return ciConstant();
692   }
693 }
694 
695 // ------------------------------------------------------------------
696 // ciEnv::get_constant_by_index
697 //
698 // Pull a constant out of the constant pool.  How appropriate.
699 //
700 // Implementation note: this query is currently in no way cached.
get_constant_by_index(const constantPoolHandle & cpool,int pool_index,int cache_index,ciInstanceKlass * accessor)701 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
702                                         int pool_index, int cache_index,
703                                         ciInstanceKlass* accessor) {
704   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
705 }
706 
707 // ------------------------------------------------------------------
708 // ciEnv::get_field_by_index_impl
709 //
710 // Implementation of get_field_by_index.
711 //
712 // Implementation note: the results of field lookups are cached
713 // in the accessor klass.
get_field_by_index_impl(ciInstanceKlass * accessor,int index)714 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
715                                         int index) {
716   ciConstantPoolCache* cache = accessor->field_cache();
717   if (cache == NULL) {
718     ciField* field = new (arena()) ciField(accessor, index);
719     return field;
720   } else {
721     ciField* field = (ciField*)cache->get(index);
722     if (field == NULL) {
723       field = new (arena()) ciField(accessor, index);
724       cache->insert(index, field);
725     }
726     return field;
727   }
728 }
729 
730 // ------------------------------------------------------------------
731 // ciEnv::get_field_by_index
732 //
733 // Get a field by index from a klass's constant pool.
get_field_by_index(ciInstanceKlass * accessor,int index)734 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
735                                    int index) {
736   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)
737 }
738 
739 // ------------------------------------------------------------------
740 // ciEnv::lookup_method
741 //
742 // Perform an appropriate method lookup based on accessor, holder,
743 // name, signature, and bytecode.
lookup_method(ciInstanceKlass * accessor,ciKlass * holder,Symbol * name,Symbol * sig,Bytecodes::Code bc,constantTag tag)744 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
745                              ciKlass*         holder,
746                              Symbol*          name,
747                              Symbol*          sig,
748                              Bytecodes::Code  bc,
749                              constantTag      tag) {
750   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
751   assert(check_klass_accessibility(accessor, holder->get_Klass()), "holder not accessible");
752 
753   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
754   Klass* holder_klass = holder->get_Klass();
755   methodHandle dest_method;
756   LinkInfo link_info(holder_klass, name, sig, accessor_klass, LinkInfo::needs_access_check, tag);
757   switch (bc) {
758   case Bytecodes::_invokestatic:
759     dest_method =
760       LinkResolver::resolve_static_call_or_null(link_info);
761     break;
762   case Bytecodes::_invokespecial:
763     dest_method =
764       LinkResolver::resolve_special_call_or_null(link_info);
765     break;
766   case Bytecodes::_invokeinterface:
767     dest_method =
768       LinkResolver::linktime_resolve_interface_method_or_null(link_info);
769     break;
770   case Bytecodes::_invokevirtual:
771     dest_method =
772       LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
773     break;
774   default: ShouldNotReachHere();
775   }
776 
777   return dest_method();
778 }
779 
780 
781 // ------------------------------------------------------------------
782 // ciEnv::get_method_by_index_impl
get_method_by_index_impl(const constantPoolHandle & cpool,int index,Bytecodes::Code bc,ciInstanceKlass * accessor)783 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
784                                           int index, Bytecodes::Code bc,
785                                           ciInstanceKlass* accessor) {
786   if (bc == Bytecodes::_invokedynamic) {
787     ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);
788     bool is_resolved = !cpce->is_f1_null();
789     // FIXME: code generation could allow for null (unlinked) call site
790     // The call site could be made patchable as follows:
791     // Load the appendix argument from the constant pool.
792     // Test the appendix argument and jump to a known deopt routine if it is null.
793     // Jump through a patchable call site, which is initially a deopt routine.
794     // Patch the call site to the nmethod entry point of the static compiled lambda form.
795     // As with other two-component call sites, both values must be independently verified.
796 
797     if (is_resolved) {
798       // Get the invoker Method* from the constant pool.
799       // (The appendix argument, if any, will be noted in the method's signature.)
800       Method* adapter = cpce->f1_as_method();
801       return get_method(adapter);
802     }
803 
804     // Fake a method that is equivalent to a declared method.
805     ciInstanceKlass* holder    = get_instance_klass(SystemDictionary::MethodHandle_klass());
806     ciSymbol*        name      = ciSymbol::invokeBasic_name();
807     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index));
808     return get_unloaded_method(holder, name, signature, accessor);
809   } else {
810     const int holder_index = cpool->klass_ref_index_at(index);
811     bool holder_is_accessible;
812     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
813 
814     // Get the method's name and signature.
815     Symbol* name_sym = cpool->name_ref_at(index);
816     Symbol* sig_sym  = cpool->signature_ref_at(index);
817 
818     if (cpool->has_preresolution()
819         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
820             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
821       // Short-circuit lookups for JSR 292-related call sites.
822       // That is, do not rely only on name-based lookups, because they may fail
823       // if the names are not resolvable in the boot class loader (7056328).
824       switch (bc) {
825       case Bytecodes::_invokevirtual:
826       case Bytecodes::_invokeinterface:
827       case Bytecodes::_invokespecial:
828       case Bytecodes::_invokestatic:
829         {
830           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
831           if (m != NULL) {
832             return get_method(m);
833           }
834         }
835         break;
836       default:
837         break;
838       }
839     }
840 
841     if (holder_is_accessible) {  // Our declared holder is loaded.
842       constantTag tag = cpool->tag_ref_at(index);
843       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
844       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
845       if (m != NULL &&
846           (bc == Bytecodes::_invokestatic
847            ?  m->method_holder()->is_not_initialized()
848            : !m->method_holder()->is_loaded())) {
849         m = NULL;
850       }
851 #ifdef ASSERT
852       if (m != NULL && ReplayCompiles && !ciReplay::is_loaded(m)) {
853         m = NULL;
854       }
855 #endif
856       if (m != NULL) {
857         // We found the method.
858         return get_method(m);
859       }
860     }
861 
862     // Either the declared holder was not loaded, or the method could
863     // not be found.  Create a dummy ciMethod to represent the failed
864     // lookup.
865     ciSymbol* name      = get_symbol(name_sym);
866     ciSymbol* signature = get_symbol(sig_sym);
867     return get_unloaded_method(holder, name, signature, accessor);
868   }
869 }
870 
871 
872 // ------------------------------------------------------------------
873 // ciEnv::get_instance_klass_for_declared_method_holder
get_instance_klass_for_declared_method_holder(ciKlass * method_holder)874 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
875   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
876   // instead of a ciInstanceKlass.  For that case simply pretend that the
877   // declared holder is Object.clone since that's where the call will bottom out.
878   // A more correct fix would trickle out through many interfaces in CI,
879   // requiring ciInstanceKlass* to become ciKlass* and many more places would
880   // require checks to make sure the expected type was found.  Given that this
881   // only occurs for clone() the more extensive fix seems like overkill so
882   // instead we simply smear the array type into Object.
883   guarantee(method_holder != NULL, "no method holder");
884   if (method_holder->is_instance_klass()) {
885     return method_holder->as_instance_klass();
886   } else if (method_holder->is_array_klass()) {
887     return current()->Object_klass();
888   } else {
889     ShouldNotReachHere();
890   }
891   return NULL;
892 }
893 
894 
895 // ------------------------------------------------------------------
896 // ciEnv::get_method_by_index
get_method_by_index(const constantPoolHandle & cpool,int index,Bytecodes::Code bc,ciInstanceKlass * accessor)897 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
898                                      int index, Bytecodes::Code bc,
899                                      ciInstanceKlass* accessor) {
900   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
901 }
902 
903 
904 // ------------------------------------------------------------------
905 // ciEnv::name_buffer
name_buffer(int req_len)906 char *ciEnv::name_buffer(int req_len) {
907   if (_name_buffer_len < req_len) {
908     if (_name_buffer == NULL) {
909       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
910       _name_buffer_len = req_len;
911     } else {
912       _name_buffer =
913         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
914       _name_buffer_len = req_len;
915     }
916   }
917   return _name_buffer;
918 }
919 
920 // ------------------------------------------------------------------
921 // ciEnv::is_in_vm
is_in_vm()922 bool ciEnv::is_in_vm() {
923   return JavaThread::current()->thread_state() == _thread_in_vm;
924 }
925 
system_dictionary_modification_counter_changed()926 bool ciEnv::system_dictionary_modification_counter_changed() {
927   return _system_dictionary_modification_counter != SystemDictionary::number_of_modifications();
928 }
929 
930 // ------------------------------------------------------------------
931 // ciEnv::validate_compile_task_dependencies
932 //
933 // Check for changes during compilation (e.g. class loads, evolution,
934 // breakpoints, call site invalidation).
validate_compile_task_dependencies(ciMethod * target)935 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
936   if (failing())  return;  // no need for further checks
937 
938   bool counter_changed = system_dictionary_modification_counter_changed();
939   Dependencies::DepType result = dependencies()->validate_dependencies(_task, counter_changed);
940   if (result != Dependencies::end_marker) {
941     if (result == Dependencies::call_site_target_value) {
942       _inc_decompile_count_on_failure = false;
943       record_failure("call site target change");
944     } else if (Dependencies::is_klass_type(result)) {
945       record_failure("concurrent class loading");
946     } else {
947       record_failure("invalid non-klass dependency");
948     }
949   }
950 }
951 
952 // ------------------------------------------------------------------
953 // ciEnv::register_method
register_method(ciMethod * target,int entry_bci,CodeOffsets * offsets,int orig_pc_offset,CodeBuffer * code_buffer,int frame_words,OopMapSet * oop_map_set,ExceptionHandlerTable * handler_table,ImplicitExceptionTable * inc_table,AbstractCompiler * compiler,bool has_unsafe_access,bool has_wide_vectors,RTMState rtm_state)954 void ciEnv::register_method(ciMethod* target,
955                             int entry_bci,
956                             CodeOffsets* offsets,
957                             int orig_pc_offset,
958                             CodeBuffer* code_buffer,
959                             int frame_words,
960                             OopMapSet* oop_map_set,
961                             ExceptionHandlerTable* handler_table,
962                             ImplicitExceptionTable* inc_table,
963                             AbstractCompiler* compiler,
964                             bool has_unsafe_access,
965                             bool has_wide_vectors,
966                             RTMState  rtm_state) {
967   VM_ENTRY_MARK;
968   nmethod* nm = NULL;
969   {
970     methodHandle method(THREAD, target->get_Method());
971 
972     // We require method counters to store some method state (max compilation levels) required by the compilation policy.
973     if (method->get_method_counters(THREAD) == NULL) {
974       record_failure("can't create method counters");
975       // All buffers in the CodeBuffer are allocated in the CodeCache.
976       // If the code buffer is created on each compile attempt
977       // as in C2, then it must be freed.
978       code_buffer->free_blob();
979       return;
980     }
981 
982     // To prevent compile queue updates.
983     MutexLocker locker(MethodCompileQueue_lock, THREAD);
984 
985     // Prevent SystemDictionary::add_to_hierarchy from running
986     // and invalidating our dependencies until we install this method.
987     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
988     MutexLocker ml(Compile_lock);
989     NoSafepointVerifier nsv;
990 
991     // Change in Jvmti state may invalidate compilation.
992     if (!failing() && jvmti_state_changed()) {
993       record_failure("Jvmti state change invalidated dependencies");
994     }
995 
996     // Change in DTrace flags may invalidate compilation.
997     if (!failing() &&
998         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
999           (!dtrace_method_probes() && DTraceMethodProbes) ||
1000           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
1001       record_failure("DTrace flags change invalidated dependencies");
1002     }
1003 
1004     if (!failing()) {
1005       if (log() != NULL) {
1006         // Log the dependencies which this compilation declares.
1007         dependencies()->log_all_dependencies();
1008       }
1009 
1010       // Encode the dependencies now, so we can check them right away.
1011       dependencies()->encode_content_bytes();
1012 
1013       // Check for {class loads, evolution, breakpoints, ...} during compilation
1014       validate_compile_task_dependencies(target);
1015     }
1016 #if INCLUDE_RTM_OPT
1017     if (!failing() && (rtm_state != NoRTM) &&
1018         (method()->method_data() != NULL) &&
1019         (method()->method_data()->rtm_state() != rtm_state)) {
1020       // Preemptive decompile if rtm state was changed.
1021       record_failure("RTM state change invalidated rtm code");
1022     }
1023 #endif
1024 
1025     if (failing()) {
1026       // While not a true deoptimization, it is a preemptive decompile.
1027       MethodData* mdo = method()->method_data();
1028       if (mdo != NULL && _inc_decompile_count_on_failure) {
1029         mdo->inc_decompile_count();
1030       }
1031 
1032       // All buffers in the CodeBuffer are allocated in the CodeCache.
1033       // If the code buffer is created on each compile attempt
1034       // as in C2, then it must be freed.
1035       code_buffer->free_blob();
1036       return;
1037     }
1038 
1039     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1040     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1041 
1042     nm =  nmethod::new_nmethod(method,
1043                                compile_id(),
1044                                entry_bci,
1045                                offsets,
1046                                orig_pc_offset,
1047                                debug_info(), dependencies(), code_buffer,
1048                                frame_words, oop_map_set,
1049                                handler_table, inc_table,
1050                                compiler, task()->comp_level());
1051 
1052     // Free codeBlobs
1053     code_buffer->free_blob();
1054 
1055     if (nm != NULL) {
1056       nm->set_has_unsafe_access(has_unsafe_access);
1057       nm->set_has_wide_vectors(has_wide_vectors);
1058 #if INCLUDE_RTM_OPT
1059       nm->set_rtm_state(rtm_state);
1060 #endif
1061 
1062       // Record successful registration.
1063       // (Put nm into the task handle *before* publishing to the Java heap.)
1064       if (task() != NULL) {
1065         task()->set_code(nm);
1066       }
1067 
1068       if (entry_bci == InvocationEntryBci) {
1069         if (TieredCompilation) {
1070           // If there is an old version we're done with it
1071           CompiledMethod* old = method->code();
1072           if (TraceMethodReplacement && old != NULL) {
1073             ResourceMark rm;
1074             char *method_name = method->name_and_sig_as_C_string();
1075             tty->print_cr("Replacing method %s", method_name);
1076           }
1077           if (old != NULL) {
1078             old->make_not_used();
1079           }
1080         }
1081         if (TraceNMethodInstalls) {
1082           ResourceMark rm;
1083           char *method_name = method->name_and_sig_as_C_string();
1084           ttyLocker ttyl;
1085           tty->print_cr("Installing method (%d) %s ",
1086                         task()->comp_level(),
1087                         method_name);
1088         }
1089         // Allow the code to be executed
1090         method->set_code(method, nm);
1091       } else {
1092         if (TraceNMethodInstalls) {
1093           ResourceMark rm;
1094           char *method_name = method->name_and_sig_as_C_string();
1095           ttyLocker ttyl;
1096           tty->print_cr("Installing osr method (%d) %s @ %d",
1097                         task()->comp_level(),
1098                         method_name,
1099                         entry_bci);
1100         }
1101         method->method_holder()->add_osr_nmethod(nm);
1102       }
1103       nm->make_in_use();
1104     }
1105   }  // safepoints are allowed again
1106 
1107   if (nm != NULL) {
1108     // JVMTI -- compiled method notification (must be done outside lock)
1109     nm->post_compiled_method_load_event();
1110   } else {
1111     // The CodeCache is full.
1112     record_failure("code cache is full");
1113   }
1114 }
1115 
1116 
1117 // ------------------------------------------------------------------
1118 // ciEnv::find_system_klass
find_system_klass(ciSymbol * klass_name)1119 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1120   VM_ENTRY_MARK;
1121   return get_klass_by_name_impl(NULL, constantPoolHandle(), klass_name, false);
1122 }
1123 
1124 // ------------------------------------------------------------------
1125 // ciEnv::comp_level
comp_level()1126 int ciEnv::comp_level() {
1127   if (task() == NULL)  return CompLevel_highest_tier;
1128   return task()->comp_level();
1129 }
1130 
1131 // ------------------------------------------------------------------
1132 // ciEnv::compile_id
compile_id()1133 uint ciEnv::compile_id() {
1134   if (task() == NULL)  return 0;
1135   return task()->compile_id();
1136 }
1137 
1138 // ------------------------------------------------------------------
1139 // ciEnv::notice_inlined_method()
notice_inlined_method(ciMethod * method)1140 void ciEnv::notice_inlined_method(ciMethod* method) {
1141   _num_inlined_bytecodes += method->code_size_for_inlining();
1142 }
1143 
1144 // ------------------------------------------------------------------
1145 // ciEnv::num_inlined_bytecodes()
num_inlined_bytecodes() const1146 int ciEnv::num_inlined_bytecodes() const {
1147   return _num_inlined_bytecodes;
1148 }
1149 
1150 // ------------------------------------------------------------------
1151 // ciEnv::record_failure()
record_failure(const char * reason)1152 void ciEnv::record_failure(const char* reason) {
1153   if (_failure_reason == NULL) {
1154     // Record the first failure reason.
1155     _failure_reason = reason;
1156   }
1157 }
1158 
report_failure(const char * reason)1159 void ciEnv::report_failure(const char* reason) {
1160   EventCompilationFailure event;
1161   if (event.should_commit()) {
1162     event.set_compileId(compile_id());
1163     event.set_failureMessage(reason);
1164     event.commit();
1165   }
1166 }
1167 
1168 // ------------------------------------------------------------------
1169 // ciEnv::record_method_not_compilable()
record_method_not_compilable(const char * reason,bool all_tiers)1170 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1171   int new_compilable =
1172     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1173 
1174   // Only note transitions to a worse state
1175   if (new_compilable > _compilable) {
1176     if (log() != NULL) {
1177       if (all_tiers) {
1178         log()->elem("method_not_compilable");
1179       } else {
1180         log()->elem("method_not_compilable_at_tier level='%d'",
1181                     current()->task()->comp_level());
1182       }
1183     }
1184     _compilable = new_compilable;
1185 
1186     // Reset failure reason; this one is more important.
1187     _failure_reason = NULL;
1188     record_failure(reason);
1189   }
1190 }
1191 
1192 // ------------------------------------------------------------------
1193 // ciEnv::record_out_of_memory_failure()
record_out_of_memory_failure()1194 void ciEnv::record_out_of_memory_failure() {
1195   // If memory is low, we stop compiling methods.
1196   record_method_not_compilable("out of memory");
1197 }
1198 
unloaded_ciinstance()1199 ciInstance* ciEnv::unloaded_ciinstance() {
1200   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1201 }
1202 
1203 // ------------------------------------------------------------------
1204 // ciEnv::dump_replay_data*
1205 
1206 // Don't change thread state and acquire any locks.
1207 // Safe to call from VM error reporter.
1208 
dump_compile_data(outputStream * out)1209 void ciEnv::dump_compile_data(outputStream* out) {
1210   CompileTask* task = this->task();
1211   if (task) {
1212     Method* method = task->method();
1213     int entry_bci = task->osr_bci();
1214     int comp_level = task->comp_level();
1215     out->print("compile %s %s %s %d %d",
1216                method->klass_name()->as_quoted_ascii(),
1217                method->name()->as_quoted_ascii(),
1218                method->signature()->as_quoted_ascii(),
1219                entry_bci, comp_level);
1220     if (compiler_data() != NULL) {
1221       if (is_c2_compile(comp_level)) {
1222 #ifdef COMPILER2
1223         // Dump C2 inlining data.
1224         ((Compile*)compiler_data())->dump_inline_data(out);
1225 #endif
1226       } else if (is_c1_compile(comp_level)) {
1227 #ifdef COMPILER1
1228         // Dump C1 inlining data.
1229         ((Compilation*)compiler_data())->dump_inline_data(out);
1230 #endif
1231       }
1232     }
1233     out->cr();
1234   }
1235 }
1236 
dump_replay_data_unsafe(outputStream * out)1237 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1238   ResourceMark rm;
1239 #if INCLUDE_JVMTI
1240   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1241   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1242   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1243 #endif // INCLUDE_JVMTI
1244 
1245   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1246   out->print_cr("# %d ciObject found", objects->length());
1247   for (int i = 0; i < objects->length(); i++) {
1248     objects->at(i)->dump_replay_data(out);
1249   }
1250   dump_compile_data(out);
1251   out->flush();
1252 }
1253 
dump_replay_data(outputStream * out)1254 void ciEnv::dump_replay_data(outputStream* out) {
1255   GUARDED_VM_ENTRY(
1256     MutexLocker ml(Compile_lock);
1257     dump_replay_data_unsafe(out);
1258   )
1259 }
1260 
dump_replay_data(int compile_id)1261 void ciEnv::dump_replay_data(int compile_id) {
1262   static char buffer[O_BUFLEN];
1263   int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);
1264   if (ret > 0) {
1265     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1266     if (fd != -1) {
1267       FILE* replay_data_file = os::open(fd, "w");
1268       if (replay_data_file != NULL) {
1269         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1270         dump_replay_data(&replay_data_stream);
1271         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1272       } else {
1273         tty->print_cr("# Can't open file to dump replay data.");
1274       }
1275     }
1276   }
1277 }
1278 
dump_inline_data(int compile_id)1279 void ciEnv::dump_inline_data(int compile_id) {
1280   static char buffer[O_BUFLEN];
1281   int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);
1282   if (ret > 0) {
1283     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1284     if (fd != -1) {
1285       FILE* inline_data_file = os::open(fd, "w");
1286       if (inline_data_file != NULL) {
1287         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1288         GUARDED_VM_ENTRY(
1289           MutexLocker ml(Compile_lock);
1290           dump_compile_data(&replay_data_stream);
1291         )
1292         replay_data_stream.flush();
1293         tty->print("# Compiler inline data is saved as: ");
1294         tty->print_cr("%s", buffer);
1295       } else {
1296         tty->print_cr("# Can't open file to dump inline data.");
1297       }
1298     }
1299   }
1300 }
1301