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