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