1 /*
   2  * Copyright 1999-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_ciEnv.cpp.incl"
  27 
  28 // ciEnv
  29 //
  30 // This class is the top level broker for requests from the compiler
  31 // to the VM.
  32 
  33 ciObject*              ciEnv::_null_object_instance;
  34 ciMethodKlass*         ciEnv::_method_klass_instance;
  35 ciSymbolKlass*         ciEnv::_symbol_klass_instance;
  36 ciKlassKlass*          ciEnv::_klass_klass_instance;
  37 ciInstanceKlassKlass*  ciEnv::_instance_klass_klass_instance;
  38 ciTypeArrayKlassKlass* ciEnv::_type_array_klass_klass_instance;
  39 ciObjArrayKlassKlass*  ciEnv::_obj_array_klass_klass_instance;
  40 
  41 ciInstanceKlass* ciEnv::_ArrayStoreException;
  42 ciInstanceKlass* ciEnv::_Class;
  43 ciInstanceKlass* ciEnv::_ClassCastException;
  44 ciInstanceKlass* ciEnv::_InvokeDynamic;
  45 ciInstanceKlass* ciEnv::_Object;
  46 ciInstanceKlass* ciEnv::_Throwable;
  47 ciInstanceKlass* ciEnv::_Thread;
  48 ciInstanceKlass* ciEnv::_OutOfMemoryError;
  49 ciInstanceKlass* ciEnv::_String;
  50 ciInstanceKlass* ciEnv::_StringBuffer;
  51 ciInstanceKlass* ciEnv::_StringBuilder;
  52 ciInstanceKlass* ciEnv::_Integer;
  53 
  54 ciSymbol*        ciEnv::_unloaded_cisymbol = NULL;
  55 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;
  56 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;
  57 
  58 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;
  59 jobject ciEnv::_ArrayStoreException_handle = NULL;
  60 jobject ciEnv::_ClassCastException_handle = NULL;
  61 
  62 #ifndef PRODUCT
  63 static bool firstEnv = true;
  64 #endif /* PRODUCT */
  65 
  66 // ------------------------------------------------------------------
  67 // ciEnv::ciEnv
  68 ciEnv::ciEnv(CompileTask* task, int system_dictionary_modification_counter) {
  69   VM_ENTRY_MARK;
  70 
  71   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
  72   thread->set_env(this);
  73   assert(ciEnv::current() == this, "sanity");
  74 
  75   _oop_recorder = NULL;
  76   _debug_info = NULL;
  77   _dependencies = NULL;
  78   _failure_reason = NULL;
  79   _compilable = MethodCompilable;
  80   _break_at_compile = false;
  81   _compiler_data = NULL;
  82 #ifndef PRODUCT
  83   assert(!firstEnv, "not initialized properly");
  84 #endif /* !PRODUCT */
  85 
  86   _system_dictionary_modification_counter = system_dictionary_modification_counter;
  87   _num_inlined_bytecodes = 0;
  88   assert(task == NULL || thread->task() == task, "sanity");
  89   _task = task;
  90   _log = NULL;
  91 
  92   // Temporary buffer for creating symbols and such.
  93   _name_buffer = NULL;
  94   _name_buffer_len = 0;
  95 
  96   _arena   = &_ciEnv_arena;
  97   _factory = new (_arena) ciObjectFactory(_arena, 128);
  98 
  99   // Preload commonly referenced system ciObjects.
 100 
 101   // During VM initialization, these instances have not yet been created.
 102   // Assertions ensure that these instances are not accessed before
 103   // their initialization.
 104 
 105   assert(Universe::is_fully_initialized(), "should be complete");
 106 
 107   oop o = Universe::null_ptr_exception_instance();
 108   assert(o != NULL, "should have been initialized");
 109   _NullPointerException_instance = get_object(o)->as_instance();
 110   o = Universe::arithmetic_exception_instance();
 111   assert(o != NULL, "should have been initialized");
 112   _ArithmeticException_instance = get_object(o)->as_instance();
 113 
 114   _ArrayIndexOutOfBoundsException_instance = NULL;
 115   _ArrayStoreException_instance = NULL;
 116   _ClassCastException_instance = NULL;
 117   _the_null_string = NULL;
 118   _the_min_jint_string = NULL;
 119 }
 120 
 121 ciEnv::ciEnv(Arena* arena) {
 122   ASSERT_IN_VM;
 123 
 124   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 125   CompilerThread* current_thread = CompilerThread::current();
 126   assert(current_thread->env() == NULL, "must be");
 127   current_thread->set_env(this);
 128   assert(ciEnv::current() == this, "sanity");
 129 
 130   _oop_recorder = NULL;
 131   _debug_info = NULL;
 132   _dependencies = NULL;
 133   _failure_reason = NULL;
 134   _compilable = MethodCompilable_never;
 135   _break_at_compile = false;
 136   _compiler_data = NULL;
 137 #ifndef PRODUCT
 138   assert(firstEnv, "must be first");
 139   firstEnv = false;
 140 #endif /* !PRODUCT */
 141 
 142   _system_dictionary_modification_counter = 0;
 143   _num_inlined_bytecodes = 0;
 144   _task = NULL;
 145   _log = NULL;
 146 
 147   // Temporary buffer for creating symbols and such.
 148   _name_buffer = NULL;
 149   _name_buffer_len = 0;
 150 
 151   _arena   = arena;
 152   _factory = new (_arena) ciObjectFactory(_arena, 128);
 153 
 154   // Preload commonly referenced system ciObjects.
 155 
 156   // During VM initialization, these instances have not yet been created.
 157   // Assertions ensure that these instances are not accessed before
 158   // their initialization.
 159 
 160   assert(Universe::is_fully_initialized(), "must be");
 161 
 162   oop o = Universe::null_ptr_exception_instance();
 163   assert(o != NULL, "should have been initialized");
 164   _NullPointerException_instance = get_object(o)->as_instance();
 165   o = Universe::arithmetic_exception_instance();
 166   assert(o != NULL, "should have been initialized");
 167   _ArithmeticException_instance = get_object(o)->as_instance();
 168 
 169   _ArrayIndexOutOfBoundsException_instance = NULL;
 170   _ArrayStoreException_instance = NULL;
 171   _ClassCastException_instance = NULL;
 172   _the_null_string = NULL;
 173   _the_min_jint_string = NULL;
 174 }
 175 
 176 ciEnv::~ciEnv() {
 177   CompilerThread* current_thread = CompilerThread::current();
 178   current_thread->set_env(NULL);
 179 }
 180 
 181 // ------------------------------------------------------------------
 182 // Cache Jvmti state
 183 void ciEnv::cache_jvmti_state() {
 184   VM_ENTRY_MARK;
 185   // Get Jvmti capabilities under lock to get consistant values.
 186   MutexLocker mu(JvmtiThreadState_lock);
 187   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 188   _jvmti_can_examine_or_deopt_anywhere  = JvmtiExport::can_examine_or_deopt_anywhere();
 189   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 190   _jvmti_can_post_exceptions            = JvmtiExport::can_post_exceptions();
 191 }
 192 
 193 // ------------------------------------------------------------------
 194 // Cache DTrace flags
 195 void ciEnv::cache_dtrace_flags() {
 196   // Need lock?
 197   _dtrace_extended_probes = ExtendedDTraceProbes;
 198   if (_dtrace_extended_probes) {
 199     _dtrace_monitor_probes  = true;
 200     _dtrace_method_probes   = true;
 201     _dtrace_alloc_probes    = true;
 202   } else {
 203     _dtrace_monitor_probes  = DTraceMonitorProbes;
 204     _dtrace_method_probes   = DTraceMethodProbes;
 205     _dtrace_alloc_probes    = DTraceAllocProbes;
 206   }
 207 }
 208 
 209 // ------------------------------------------------------------------
 210 // helper for lazy exception creation
 211 ciInstance* ciEnv::get_or_create_exception(jobject& handle, symbolHandle name) {
 212   VM_ENTRY_MARK;
 213   if (handle == NULL) {
 214     // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.
 215     klassOop k = SystemDictionary::find(name, Handle(), Handle(), THREAD);
 216     jobject objh = NULL;
 217     if (!HAS_PENDING_EXCEPTION && k != NULL) {
 218       oop obj = instanceKlass::cast(k)->allocate_permanent_instance(THREAD);
 219       if (!HAS_PENDING_EXCEPTION)
 220         objh = JNIHandles::make_global(obj);
 221     }
 222     if (HAS_PENDING_EXCEPTION) {
 223       CLEAR_PENDING_EXCEPTION;
 224     } else {
 225       handle = objh;
 226     }
 227   }
 228   oop obj = JNIHandles::resolve(handle);
 229   return obj == NULL? NULL: get_object(obj)->as_instance();
 230 }
 231 
 232 // ------------------------------------------------------------------
 233 // ciEnv::ArrayIndexOutOfBoundsException_instance, etc.
 234 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
 235   if (_ArrayIndexOutOfBoundsException_instance == NULL) {
 236     _ArrayIndexOutOfBoundsException_instance
 237           = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,
 238           vmSymbolHandles::java_lang_ArrayIndexOutOfBoundsException());
 239   }
 240   return _ArrayIndexOutOfBoundsException_instance;
 241 }
 242 ciInstance* ciEnv::ArrayStoreException_instance() {
 243   if (_ArrayStoreException_instance == NULL) {
 244     _ArrayStoreException_instance
 245           = get_or_create_exception(_ArrayStoreException_handle,
 246           vmSymbolHandles::java_lang_ArrayStoreException());
 247   }
 248   return _ArrayStoreException_instance;
 249 }
 250 ciInstance* ciEnv::ClassCastException_instance() {
 251   if (_ClassCastException_instance == NULL) {
 252     _ClassCastException_instance
 253           = get_or_create_exception(_ClassCastException_handle,
 254           vmSymbolHandles::java_lang_ClassCastException());
 255   }
 256   return _ClassCastException_instance;
 257 }
 258 
 259 ciInstance* ciEnv::the_null_string() {
 260   if (_the_null_string == NULL) {
 261     VM_ENTRY_MARK;
 262     _the_null_string = get_object(Universe::the_null_string())->as_instance();
 263   }
 264   return _the_null_string;
 265 }
 266 
 267 ciInstance* ciEnv::the_min_jint_string() {
 268   if (_the_min_jint_string == NULL) {
 269     VM_ENTRY_MARK;
 270     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
 271   }
 272   return _the_min_jint_string;
 273 }
 274 
 275 // ------------------------------------------------------------------
 276 // ciEnv::get_method_from_handle
 277 ciMethod* ciEnv::get_method_from_handle(jobject method) {
 278   VM_ENTRY_MARK;
 279   return get_object(JNIHandles::resolve(method))->as_method();
 280 }
 281 
 282 // ------------------------------------------------------------------
 283 // ciEnv::make_array
 284 ciArray* ciEnv::make_system_array(GrowableArray<ciObject*>* objects) {
 285   VM_ENTRY_MARK;
 286   int length = objects->length();
 287   objArrayOop a = oopFactory::new_system_objArray(length, THREAD);
 288   if (HAS_PENDING_EXCEPTION) {
 289     CLEAR_PENDING_EXCEPTION;
 290     record_out_of_memory_failure();
 291     return NULL;
 292   }
 293   for (int i = 0; i < length; i++) {
 294     a->obj_at_put(i, objects->at(i)->get_oop());
 295   }
 296   assert(a->is_perm(), "");
 297   return get_object(a)->as_array();
 298 }
 299 
 300 
 301 // ------------------------------------------------------------------
 302 // ciEnv::array_element_offset_in_bytes
 303 int ciEnv::array_element_offset_in_bytes(ciArray* a_h, ciObject* o_h) {
 304   VM_ENTRY_MARK;
 305   objArrayOop a = (objArrayOop)a_h->get_oop();
 306   assert(a->is_objArray(), "");
 307   int length = a->length();
 308   oop o = o_h->get_oop();
 309   for (int i = 0; i < length; i++) {
 310     if (a->obj_at(i) == o)  return i;
 311   }
 312   return -1;
 313 }
 314 
 315 
 316 // ------------------------------------------------------------------
 317 // ciEnv::check_klass_accessiblity
 318 //
 319 // Note: the logic of this method should mirror the logic of
 320 // constantPoolOopDesc::verify_constant_pool_resolve.
 321 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 322                                       klassOop resolved_klass) {
 323   if (accessing_klass == NULL || !accessing_klass->is_loaded()) {
 324     return true;
 325   }
 326   if (accessing_klass->is_obj_array()) {
 327     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 328   }
 329   if (!accessing_klass->is_instance_klass()) {
 330     return true;
 331   }
 332 
 333   if (resolved_klass->klass_part()->oop_is_objArray()) {
 334     // Find the element klass, if this is an array.
 335     resolved_klass = objArrayKlass::cast(resolved_klass)->bottom_klass();
 336   }
 337   if (resolved_klass->klass_part()->oop_is_instance()) {
 338     return Reflection::verify_class_access(accessing_klass->get_klassOop(),
 339                                            resolved_klass,
 340                                            true);
 341   }
 342   return true;
 343 }
 344 
 345 // ------------------------------------------------------------------
 346 // ciEnv::get_klass_by_name_impl
 347 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 348                                        ciSymbol* name,
 349                                        bool require_local) {
 350   ASSERT_IN_VM;
 351   EXCEPTION_CONTEXT;
 352 
 353   // Now we need to check the SystemDictionary
 354   symbolHandle sym(THREAD, name->get_symbolOop());
 355   if (sym->byte_at(0) == 'L' &&
 356     sym->byte_at(sym->utf8_length()-1) == ';') {
 357     // This is a name from a signature.  Strip off the trimmings.
 358     sym = oopFactory::new_symbol_handle(sym->as_utf8()+1,
 359                                         sym->utf8_length()-2,
 360                                         KILL_COMPILE_ON_FATAL_(_unloaded_ciinstance_klass));
 361     name = get_object(sym())->as_symbol();
 362   }
 363 
 364   // Check for prior unloaded klass.  The SystemDictionary's answers
 365   // can vary over time but the compiler needs consistency.
 366   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 367   if (unloaded_klass != NULL) {
 368     if (require_local)  return NULL;
 369     return unloaded_klass;
 370   }
 371 
 372   Handle loader(THREAD, (oop)NULL);
 373   Handle domain(THREAD, (oop)NULL);
 374   if (accessing_klass != NULL) {
 375     loader = Handle(THREAD, accessing_klass->loader());
 376     domain = Handle(THREAD, accessing_klass->protection_domain());
 377   }
 378 
 379   // setup up the proper type to return on OOM
 380   ciKlass* fail_type;
 381   if (sym->byte_at(0) == '[') {
 382     fail_type = _unloaded_ciobjarrayklass;
 383   } else {
 384     fail_type = _unloaded_ciinstance_klass;
 385   }
 386   klassOop found_klass;
 387   if (!require_local) {
 388     found_klass =
 389       SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
 390                                                                  KILL_COMPILE_ON_FATAL_(fail_type));
 391   } else {
 392     found_klass =
 393       SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
 394                                                      KILL_COMPILE_ON_FATAL_(fail_type));
 395   }
 396 
 397   if (found_klass != NULL) {
 398     // Found it.  Build a CI handle.
 399     return get_object(found_klass)->as_klass();
 400   }
 401 
 402   // If we fail to find an array klass, look again for its element type.
 403   // The element type may be available either locally or via constraints.
 404   // In either case, if we can find the element type in the system dictionary,
 405   // we must build an array type around it.  The CI requires array klasses
 406   // to be loaded if their element klasses are loaded, except when memory
 407   // is exhausted.
 408   if (sym->byte_at(0) == '[' &&
 409       (sym->byte_at(1) == '[' || sym->byte_at(1) == 'L')) {
 410     // We have an unloaded array.
 411     // Build it on the fly if the element class exists.
 412     symbolOop elem_sym = oopFactory::new_symbol(sym->as_utf8()+1,
 413                                                 sym->utf8_length()-1,
 414                                                 KILL_COMPILE_ON_FATAL_(fail_type));
 415     // Get element ciKlass recursively.
 416     ciKlass* elem_klass =
 417       get_klass_by_name_impl(accessing_klass,
 418                              get_object(elem_sym)->as_symbol(),
 419                              require_local);
 420     if (elem_klass != NULL && elem_klass->is_loaded()) {
 421       // Now make an array for it
 422       return ciObjArrayKlass::make_impl(elem_klass);
 423     }
 424   }
 425 
 426   if (require_local)  return NULL;
 427   // Not yet loaded into the VM, or not governed by loader constraints.
 428   // Make a CI representative for it.
 429   return get_unloaded_klass(accessing_klass, name);
 430 }
 431 
 432 // ------------------------------------------------------------------
 433 // ciEnv::get_klass_by_name
 434 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 435                                   ciSymbol* klass_name,
 436                                   bool require_local) {
 437   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 438                                                  klass_name,
 439                                                  require_local);)
 440 }
 441 
 442 // ------------------------------------------------------------------
 443 // ciEnv::get_klass_by_index_impl
 444 //
 445 // Implementation of get_klass_by_index.
 446 ciKlass* ciEnv::get_klass_by_index_impl(ciInstanceKlass* accessor,
 447                                         int index,
 448                                         bool& is_accessible) {
 449   assert(accessor->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool");
 450   EXCEPTION_CONTEXT;
 451   constantPoolHandle cpool(THREAD, accessor->get_instanceKlass()->constants());
 452   KlassHandle klass (THREAD, constantPoolOopDesc::klass_at_if_loaded(cpool, index));
 453   symbolHandle klass_name;
 454   if (klass.is_null()) {
 455     // The klass has not been inserted into the constant pool.
 456     // Try to look it up by name.
 457     {
 458       // We have to lock the cpool to keep the oop from being resolved
 459       // while we are accessing it.
 460       ObjectLocker ol(cpool, THREAD);
 461 
 462       constantTag tag = cpool->tag_at(index);
 463       if (tag.is_klass()) {
 464         // The klass has been inserted into the constant pool
 465         // very recently.
 466         klass = KlassHandle(THREAD, cpool->resolved_klass_at(index));
 467       } else if (tag.is_symbol()) {
 468         klass_name = symbolHandle(THREAD, cpool->symbol_at(index));
 469       } else {
 470         assert(cpool->tag_at(index).is_unresolved_klass(), "wrong tag");
 471         klass_name = symbolHandle(THREAD, cpool->unresolved_klass_at(index));
 472       }
 473     }
 474   }
 475 
 476   if (klass.is_null()) {
 477     // Not found in constant pool.  Use the name to do the lookup.
 478     ciKlass* k = get_klass_by_name_impl(accessor,
 479                                         get_object(klass_name())->as_symbol(),
 480                                         false);
 481     // Calculate accessibility the hard way.
 482     if (!k->is_loaded()) {
 483       is_accessible = false;
 484     } else if (k->loader() != accessor->loader() &&
 485                get_klass_by_name_impl(accessor, k->name(), true) == NULL) {
 486       // Loaded only remotely.  Not linked yet.
 487       is_accessible = false;
 488     } else {
 489       // Linked locally, and we must also check public/private, etc.
 490       is_accessible = check_klass_accessibility(accessor, k->get_klassOop());
 491     }
 492     return k;
 493   }
 494 
 495   // Check for prior unloaded klass.  The SystemDictionary's answers
 496   // can vary over time but the compiler needs consistency.
 497   ciSymbol* name = get_object(klass()->klass_part()->name())->as_symbol();
 498   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 499   if (unloaded_klass != NULL) {
 500     is_accessible = false;
 501     return unloaded_klass;
 502   }
 503 
 504   // It is known to be accessible, since it was found in the constant pool.
 505   is_accessible = true;
 506   return get_object(klass())->as_klass();
 507 }
 508 
 509 // ------------------------------------------------------------------
 510 // ciEnv::get_klass_by_index
 511 //
 512 // Get a klass from the constant pool.
 513 ciKlass* ciEnv::get_klass_by_index(ciInstanceKlass* accessor,
 514                                    int index,
 515                                    bool& is_accessible) {
 516   GUARDED_VM_ENTRY(return get_klass_by_index_impl(accessor, index, is_accessible);)
 517 }
 518 
 519 // ------------------------------------------------------------------
 520 // ciEnv::get_constant_by_index_impl
 521 //
 522 // Implementation of get_constant_by_index().
 523 ciConstant ciEnv::get_constant_by_index_impl(ciInstanceKlass* accessor,
 524                                              int index) {
 525   EXCEPTION_CONTEXT;
 526   instanceKlass* ik_accessor = accessor->get_instanceKlass();
 527   assert(ik_accessor->is_linked(), "must be linked before accessing constant pool");
 528   constantPoolOop cpool = ik_accessor->constants();
 529   constantTag tag = cpool->tag_at(index);
 530   if (tag.is_int()) {
 531     return ciConstant(T_INT, (jint)cpool->int_at(index));
 532   } else if (tag.is_long()) {
 533     return ciConstant((jlong)cpool->long_at(index));
 534   } else if (tag.is_float()) {
 535     return ciConstant((jfloat)cpool->float_at(index));
 536   } else if (tag.is_double()) {
 537     return ciConstant((jdouble)cpool->double_at(index));
 538   } else if (tag.is_string() || tag.is_unresolved_string()) {
 539     oop string = NULL;
 540     if (cpool->is_pseudo_string_at(index)) {
 541       string = cpool->pseudo_string_at(index);
 542     } else {
 543       string = cpool->string_at(index, THREAD);
 544       if (HAS_PENDING_EXCEPTION) {
 545         CLEAR_PENDING_EXCEPTION;
 546         record_out_of_memory_failure();
 547         return ciConstant();
 548       }
 549     }
 550     ciObject* constant = get_object(string);
 551     assert (constant->is_instance(), "must be an instance, or not? ");
 552     return ciConstant(T_OBJECT, constant);
 553   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 554     // 4881222: allow ldc to take a class type
 555     bool ignore;
 556     ciKlass* klass = get_klass_by_index_impl(accessor, index, ignore);
 557     if (HAS_PENDING_EXCEPTION) {
 558       CLEAR_PENDING_EXCEPTION;
 559       record_out_of_memory_failure();
 560       return ciConstant();
 561     }
 562     assert (klass->is_instance_klass() || klass->is_array_klass(),
 563             "must be an instance or array klass ");
 564     return ciConstant(T_OBJECT, klass);
 565   } else {
 566     ShouldNotReachHere();
 567     return ciConstant();
 568   }
 569 }
 570 
 571 // ------------------------------------------------------------------
 572 // ciEnv::is_unresolved_string_impl
 573 //
 574 // Implementation of is_unresolved_string().
 575 bool ciEnv::is_unresolved_string_impl(instanceKlass* accessor, int index) const {
 576   EXCEPTION_CONTEXT;
 577   assert(accessor->is_linked(), "must be linked before accessing constant pool");
 578   constantPoolOop cpool = accessor->constants();
 579   constantTag tag = cpool->tag_at(index);
 580   return tag.is_unresolved_string();
 581 }
 582 
 583 // ------------------------------------------------------------------
 584 // ciEnv::is_unresolved_klass_impl
 585 //
 586 // Implementation of is_unresolved_klass().
 587 bool ciEnv::is_unresolved_klass_impl(instanceKlass* accessor, int index) const {
 588   EXCEPTION_CONTEXT;
 589   assert(accessor->is_linked(), "must be linked before accessing constant pool");
 590   constantPoolOop cpool = accessor->constants();
 591   constantTag tag = cpool->tag_at(index);
 592   return tag.is_unresolved_klass();
 593 }
 594 
 595 // ------------------------------------------------------------------
 596 // ciEnv::get_constant_by_index
 597 //
 598 // Pull a constant out of the constant pool.  How appropriate.
 599 //
 600 // Implementation note: this query is currently in no way cached.
 601 ciConstant ciEnv::get_constant_by_index(ciInstanceKlass* accessor,
 602                                         int index) {
 603   GUARDED_VM_ENTRY(return get_constant_by_index_impl(accessor, index); )
 604 }
 605 
 606 // ------------------------------------------------------------------
 607 // ciEnv::is_unresolved_string
 608 //
 609 // Check constant pool
 610 //
 611 // Implementation note: this query is currently in no way cached.
 612 bool ciEnv::is_unresolved_string(ciInstanceKlass* accessor,
 613                                         int index) const {
 614   GUARDED_VM_ENTRY(return is_unresolved_string_impl(accessor->get_instanceKlass(), index); )
 615 }
 616 
 617 // ------------------------------------------------------------------
 618 // ciEnv::is_unresolved_klass
 619 //
 620 // Check constant pool
 621 //
 622 // Implementation note: this query is currently in no way cached.
 623 bool ciEnv::is_unresolved_klass(ciInstanceKlass* accessor,
 624                                         int index) const {
 625   GUARDED_VM_ENTRY(return is_unresolved_klass_impl(accessor->get_instanceKlass(), index); )
 626 }
 627 
 628 // ------------------------------------------------------------------
 629 // ciEnv::get_field_by_index_impl
 630 //
 631 // Implementation of get_field_by_index.
 632 //
 633 // Implementation note: the results of field lookups are cached
 634 // in the accessor klass.
 635 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 636                                         int index) {
 637   ciConstantPoolCache* cache = accessor->field_cache();
 638   if (cache == NULL) {
 639     ciField* field = new (arena()) ciField(accessor, index);
 640     return field;
 641   } else {
 642     ciField* field = (ciField*)cache->get(index);
 643     if (field == NULL) {
 644       field = new (arena()) ciField(accessor, index);
 645       cache->insert(index, field);
 646     }
 647     return field;
 648   }
 649 }
 650 
 651 // ------------------------------------------------------------------
 652 // ciEnv::get_field_by_index
 653 //
 654 // Get a field by index from a klass's constant pool.
 655 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 656                                    int index) {
 657   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)
 658 }
 659 
 660 // ------------------------------------------------------------------
 661 // ciEnv::lookup_method
 662 //
 663 // Perform an appropriate method lookup based on accessor, holder,
 664 // name, signature, and bytecode.
 665 methodOop ciEnv::lookup_method(instanceKlass*  accessor,
 666                                instanceKlass*  holder,
 667                                symbolOop       name,
 668                                symbolOop       sig,
 669                                Bytecodes::Code bc) {
 670   EXCEPTION_CONTEXT;
 671   KlassHandle h_accessor(THREAD, accessor);
 672   KlassHandle h_holder(THREAD, holder);
 673   symbolHandle h_name(THREAD, name);
 674   symbolHandle h_sig(THREAD, sig);
 675   LinkResolver::check_klass_accessability(h_accessor, h_holder, KILL_COMPILE_ON_FATAL_(NULL));
 676   methodHandle dest_method;
 677   switch (bc) {
 678   case Bytecodes::_invokestatic:
 679     dest_method =
 680       LinkResolver::resolve_static_call_or_null(h_holder, h_name, h_sig, h_accessor);
 681     break;
 682   case Bytecodes::_invokespecial:
 683     dest_method =
 684       LinkResolver::resolve_special_call_or_null(h_holder, h_name, h_sig, h_accessor);
 685     break;
 686   case Bytecodes::_invokeinterface:
 687     dest_method =
 688       LinkResolver::linktime_resolve_interface_method_or_null(h_holder, h_name, h_sig,
 689                                                               h_accessor, true);
 690     break;
 691   case Bytecodes::_invokevirtual:
 692     dest_method =
 693       LinkResolver::linktime_resolve_virtual_method_or_null(h_holder, h_name, h_sig,
 694                                                             h_accessor, true);
 695     break;
 696   default: ShouldNotReachHere();
 697   }
 698 
 699   return dest_method();
 700 }
 701 
 702 
 703 // ------------------------------------------------------------------
 704 // ciEnv::get_method_by_index_impl
 705 ciMethod* ciEnv::get_method_by_index_impl(ciInstanceKlass* accessor,
 706                                      int index, Bytecodes::Code bc) {
 707   // Get the method's declared holder.
 708 
 709   assert(accessor->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool");
 710   constantPoolHandle cpool = accessor->get_instanceKlass()->constants();
 711   int holder_index = cpool->klass_ref_index_at(index);
 712   bool holder_is_accessible;
 713   ciKlass* holder = get_klass_by_index_impl(accessor, holder_index, holder_is_accessible);
 714   ciInstanceKlass* declared_holder = get_instance_klass_for_declared_method_holder(holder);
 715 
 716   // Get the method's name and signature.
 717   symbolOop name_sym = cpool->name_ref_at(index);
 718   symbolOop sig_sym  = cpool->signature_ref_at(index);
 719 
 720   if (holder_is_accessible) { // Our declared holder is loaded.
 721     instanceKlass* lookup = declared_holder->get_instanceKlass();
 722     methodOop m = lookup_method(accessor->get_instanceKlass(), lookup, name_sym, sig_sym, bc);
 723     if (m != NULL) {
 724       // We found the method.
 725       return get_object(m)->as_method();
 726     }
 727   }
 728 
 729   // Either the declared holder was not loaded, or the method could
 730   // not be found.  Create a dummy ciMethod to represent the failed
 731   // lookup.
 732 
 733   return get_unloaded_method(declared_holder,
 734                              get_object(name_sym)->as_symbol(),
 735                              get_object(sig_sym)->as_symbol());
 736 }
 737 
 738 
 739 // ------------------------------------------------------------------
 740 // ciEnv::get_fake_invokedynamic_method_impl
 741 ciMethod* ciEnv::get_fake_invokedynamic_method_impl(ciInstanceKlass* accessor,
 742                                                     int index, Bytecodes::Code bc) {
 743   assert(bc == Bytecodes::_invokedynamic, "must be invokedynamic");
 744   assert(accessor->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool");
 745   constantPoolHandle cpool = accessor->get_instanceKlass()->constants();
 746 
 747   // Get the CallSite from the constant pool cache.
 748   ConstantPoolCacheEntry* cpc_entry = cpool->cache()->secondary_entry_at(index);
 749   assert(cpc_entry != NULL && cpc_entry->is_secondary_entry(), "sanity");
 750   Handle call_site = cpc_entry->f1();
 751 
 752   // Call site might not be linked yet.
 753   if (call_site.is_null()) {
 754     ciInstanceKlass* mh_klass = get_object(SystemDictionary::MethodHandle_klass())->as_instance_klass();
 755     ciSymbol*       sig_sym   = get_object(cpool->signature_ref_at(index))->as_symbol();
 756     return get_unloaded_method(mh_klass, ciSymbol::invoke_name(), sig_sym);
 757   }
 758 
 759   // Get the methodOop from the CallSite.
 760   methodOop method_oop = (methodOop) java_dyn_CallSite::vmmethod(call_site());
 761   assert(method_oop != NULL, "sanity");
 762   assert(method_oop->is_method_handle_invoke(), "consistent");
 763 
 764   return get_object(method_oop)->as_method();
 765 }
 766 
 767 
 768 // ------------------------------------------------------------------
 769 // ciEnv::get_instance_klass_for_declared_method_holder
 770 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 771   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 772   // instead of a ciInstanceKlass.  For that case simply pretend that the
 773   // declared holder is Object.clone since that's where the call will bottom out.
 774   // A more correct fix would trickle out through many interfaces in CI,
 775   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 776   // require checks to make sure the expected type was found.  Given that this
 777   // only occurs for clone() the more extensive fix seems like overkill so
 778   // instead we simply smear the array type into Object.
 779   if (method_holder->is_instance_klass()) {
 780     return method_holder->as_instance_klass();
 781   } else if (method_holder->is_array_klass()) {
 782     return current()->Object_klass();
 783   } else {
 784     ShouldNotReachHere();
 785   }
 786   return NULL;
 787 }
 788 
 789 
 790 // ------------------------------------------------------------------
 791 // ciEnv::get_method_by_index
 792 ciMethod* ciEnv::get_method_by_index(ciInstanceKlass* accessor,
 793                                      int index, Bytecodes::Code bc) {
 794   if (bc == Bytecodes::_invokedynamic) {
 795     GUARDED_VM_ENTRY(return get_fake_invokedynamic_method_impl(accessor, index, bc);)
 796   } else {
 797     GUARDED_VM_ENTRY(return get_method_by_index_impl(accessor, index, bc);)
 798   }
 799 }
 800 
 801 
 802 // ------------------------------------------------------------------
 803 // ciEnv::name_buffer
 804 char *ciEnv::name_buffer(int req_len) {
 805   if (_name_buffer_len < req_len) {
 806     if (_name_buffer == NULL) {
 807       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 808       _name_buffer_len = req_len;
 809     } else {
 810       _name_buffer =
 811         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 812       _name_buffer_len = req_len;
 813     }
 814   }
 815   return _name_buffer;
 816 }
 817 
 818 // ------------------------------------------------------------------
 819 // ciEnv::is_in_vm
 820 bool ciEnv::is_in_vm() {
 821   return JavaThread::current()->thread_state() == _thread_in_vm;
 822 }
 823 
 824 bool ciEnv::system_dictionary_modification_counter_changed() {
 825   return _system_dictionary_modification_counter != SystemDictionary::number_of_modifications();
 826 }
 827 
 828 // ------------------------------------------------------------------
 829 // ciEnv::check_for_system_dictionary_modification
 830 // Check for changes to the system dictionary during compilation
 831 // class loads, evolution, breakpoints
 832 void ciEnv::check_for_system_dictionary_modification(ciMethod* target) {
 833   if (failing())  return;  // no need for further checks
 834 
 835   // Dependencies must be checked when the system dictionary changes.
 836   // If logging is enabled all violated dependences will be recorded in
 837   // the log.  In debug mode check dependencies even if the system
 838   // dictionary hasn't changed to verify that no invalid dependencies
 839   // were inserted.  Any violated dependences in this case are dumped to
 840   // the tty.
 841 
 842   bool counter_changed = system_dictionary_modification_counter_changed();
 843   bool test_deps = counter_changed;
 844   DEBUG_ONLY(test_deps = true);
 845   if (!test_deps)  return;
 846 
 847   bool print_failures = false;
 848   DEBUG_ONLY(print_failures = !counter_changed);
 849 
 850   bool keep_going = (print_failures || xtty != NULL);
 851 
 852   int violated = 0;
 853 
 854   for (Dependencies::DepStream deps(dependencies()); deps.next(); ) {
 855     klassOop witness = deps.check_dependency();
 856     if (witness != NULL) {
 857       ++violated;
 858       if (print_failures)  deps.print_dependency(witness, /*verbose=*/ true);
 859       // If there's no log and we're not sanity-checking, we're done.
 860       if (!keep_going)     break;
 861     }
 862   }
 863 
 864   if (violated != 0) {
 865     assert(counter_changed, "failed dependencies, but counter didn't change");
 866     record_failure("concurrent class loading");
 867   }
 868 }
 869 
 870 // ------------------------------------------------------------------
 871 // ciEnv::register_method
 872 void ciEnv::register_method(ciMethod* target,
 873                             int entry_bci,
 874                             CodeOffsets* offsets,
 875                             int orig_pc_offset,
 876                             CodeBuffer* code_buffer,
 877                             int frame_words,
 878                             OopMapSet* oop_map_set,
 879                             ExceptionHandlerTable* handler_table,
 880                             ImplicitExceptionTable* inc_table,
 881                             AbstractCompiler* compiler,
 882                             int comp_level,
 883                             bool has_debug_info,
 884                             bool has_unsafe_access) {
 885   VM_ENTRY_MARK;
 886   nmethod* nm = NULL;
 887   {
 888     // To prevent compile queue updates.
 889     MutexLocker locker(MethodCompileQueue_lock, THREAD);
 890 
 891     // Prevent SystemDictionary::add_to_hierarchy from running
 892     // and invalidating our dependencies until we install this method.
 893     MutexLocker ml(Compile_lock);
 894 
 895     // Change in Jvmti state may invalidate compilation.
 896     if (!failing() &&
 897         ( (!jvmti_can_hotswap_or_post_breakpoint() &&
 898            JvmtiExport::can_hotswap_or_post_breakpoint()) ||
 899           (!jvmti_can_examine_or_deopt_anywhere() &&
 900            JvmtiExport::can_examine_or_deopt_anywhere()) ||
 901           (!jvmti_can_access_local_variables() &&
 902            JvmtiExport::can_access_local_variables()) ||
 903           (!jvmti_can_post_exceptions() &&
 904            JvmtiExport::can_post_exceptions()) )) {
 905       record_failure("Jvmti state change invalidated dependencies");
 906     }
 907 
 908     // Change in DTrace flags may invalidate compilation.
 909     if (!failing() &&
 910         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
 911           (!dtrace_method_probes() && DTraceMethodProbes) ||
 912           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
 913       record_failure("DTrace flags change invalidated dependencies");
 914     }
 915 
 916     if (!failing()) {
 917       if (log() != NULL) {
 918         // Log the dependencies which this compilation declares.
 919         dependencies()->log_all_dependencies();
 920       }
 921 
 922       // Encode the dependencies now, so we can check them right away.
 923       dependencies()->encode_content_bytes();
 924 
 925       // Check for {class loads, evolution, breakpoints} during compilation
 926       check_for_system_dictionary_modification(target);
 927     }
 928 
 929     methodHandle method(THREAD, target->get_methodOop());
 930 
 931     if (failing()) {
 932       // While not a true deoptimization, it is a preemptive decompile.
 933       methodDataOop mdo = method()->method_data();
 934       if (mdo != NULL) {
 935         mdo->inc_decompile_count();
 936       }
 937 
 938       // All buffers in the CodeBuffer are allocated in the CodeCache.
 939       // If the code buffer is created on each compile attempt
 940       // as in C2, then it must be freed.
 941       code_buffer->free_blob();
 942       return;
 943     }
 944 
 945     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
 946     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
 947 
 948     nm =  nmethod::new_nmethod(method,
 949                                compile_id(),
 950                                entry_bci,
 951                                offsets,
 952                                orig_pc_offset,
 953                                debug_info(), dependencies(), code_buffer,
 954                                frame_words, oop_map_set,
 955                                handler_table, inc_table,
 956                                compiler, comp_level);
 957 
 958     // Free codeBlobs
 959     code_buffer->free_blob();
 960 
 961     // stress test 6243940 by immediately making the method
 962     // non-entrant behind the system's back. This has serious
 963     // side effects on the code cache and is not meant for
 964     // general stress testing
 965     if (nm != NULL && StressNonEntrant) {
 966       MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 967       NativeJump::patch_verified_entry(nm->entry_point(), nm->verified_entry_point(),
 968                   SharedRuntime::get_handle_wrong_method_stub());
 969     }
 970 
 971     if (nm == NULL) {
 972       // The CodeCache is full.  Print out warning and disable compilation.
 973       record_failure("code cache is full");
 974       UseInterpreter = true;
 975       if (UseCompiler || AlwaysCompileLoopMethods ) {
 976 #ifndef PRODUCT
 977         warning("CodeCache is full. Compiler has been disabled");
 978         if (CompileTheWorld || ExitOnFullCodeCache) {
 979           before_exit(JavaThread::current());
 980           exit_globals(); // will delete tty
 981           vm_direct_exit(CompileTheWorld ? 0 : 1);
 982         }
 983 #endif
 984         UseCompiler               = false;
 985         AlwaysCompileLoopMethods  = false;
 986       }
 987     } else {
 988       NOT_PRODUCT(nm->set_has_debug_info(has_debug_info); )
 989       nm->set_has_unsafe_access(has_unsafe_access);
 990 
 991       // Record successful registration.
 992       // (Put nm into the task handle *before* publishing to the Java heap.)
 993       if (task() != NULL)  task()->set_code(nm);
 994 
 995       if (entry_bci == InvocationEntryBci) {
 996 #ifdef TIERED
 997         // If there is an old version we're done with it
 998         nmethod* old = method->code();
 999         if (TraceMethodReplacement && old != NULL) {
1000           ResourceMark rm;
1001           char *method_name = method->name_and_sig_as_C_string();
1002           tty->print_cr("Replacing method %s", method_name);
1003         }
1004         if (old != NULL ) {
1005           old->make_not_entrant();
1006         }
1007 #endif // TIERED
1008         if (TraceNMethodInstalls ) {
1009           ResourceMark rm;
1010           char *method_name = method->name_and_sig_as_C_string();
1011           ttyLocker ttyl;
1012           tty->print_cr("Installing method (%d) %s ",
1013                         comp_level,
1014                         method_name);
1015         }
1016         // Allow the code to be executed
1017         method->set_code(method, nm);
1018       } else {
1019         if (TraceNMethodInstalls ) {
1020           ResourceMark rm;
1021           char *method_name = method->name_and_sig_as_C_string();
1022           ttyLocker ttyl;
1023           tty->print_cr("Installing osr method (%d) %s @ %d",
1024                         comp_level,
1025                         method_name,
1026                         entry_bci);
1027         }
1028         instanceKlass::cast(method->method_holder())->add_osr_nmethod(nm);
1029 
1030       }
1031     }
1032   }
1033   // JVMTI -- compiled method notification (must be done outside lock)
1034   if (nm != NULL) {
1035     nm->post_compiled_method_load_event();
1036   }
1037 
1038 }
1039 
1040 
1041 // ------------------------------------------------------------------
1042 // ciEnv::find_system_klass
1043 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1044   VM_ENTRY_MARK;
1045   return get_klass_by_name_impl(NULL, klass_name, false);
1046 }
1047 
1048 // ------------------------------------------------------------------
1049 // ciEnv::comp_level
1050 int ciEnv::comp_level() {
1051   if (task() == NULL)  return CompLevel_full_optimization;
1052   return task()->comp_level();
1053 }
1054 
1055 // ------------------------------------------------------------------
1056 // ciEnv::compile_id
1057 uint ciEnv::compile_id() {
1058   if (task() == NULL)  return 0;
1059   return task()->compile_id();
1060 }
1061 
1062 // ------------------------------------------------------------------
1063 // ciEnv::notice_inlined_method()
1064 void ciEnv::notice_inlined_method(ciMethod* method) {
1065   _num_inlined_bytecodes += method->code_size();
1066 }
1067 
1068 // ------------------------------------------------------------------
1069 // ciEnv::num_inlined_bytecodes()
1070 int ciEnv::num_inlined_bytecodes() const {
1071   return _num_inlined_bytecodes;
1072 }
1073 
1074 // ------------------------------------------------------------------
1075 // ciEnv::record_failure()
1076 void ciEnv::record_failure(const char* reason) {
1077   if (log() != NULL) {
1078     log()->elem("failure reason='%s'", reason);
1079   }
1080   if (_failure_reason == NULL) {
1081     // Record the first failure reason.
1082     _failure_reason = reason;
1083   }
1084 }
1085 
1086 // ------------------------------------------------------------------
1087 // ciEnv::record_method_not_compilable()
1088 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1089   int new_compilable =
1090     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1091 
1092   // Only note transitions to a worse state
1093   if (new_compilable > _compilable) {
1094     if (log() != NULL) {
1095       if (all_tiers) {
1096         log()->elem("method_not_compilable");
1097       } else {
1098         log()->elem("method_not_compilable_at_tier");
1099       }
1100     }
1101     _compilable = new_compilable;
1102 
1103     // Reset failure reason; this one is more important.
1104     _failure_reason = NULL;
1105     record_failure(reason);
1106   }
1107 }
1108 
1109 // ------------------------------------------------------------------
1110 // ciEnv::record_out_of_memory_failure()
1111 void ciEnv::record_out_of_memory_failure() {
1112   // If memory is low, we stop compiling methods.
1113   record_method_not_compilable("out of memory");
1114 }