1 /*
   2  * Copyright (c) 1997, 2010, 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 "classfile/javaClasses.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/verifier.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "gc_implementation/shared/markSweep.inline.hpp"
  32 #include "gc_interface/collectedHeap.inline.hpp"
  33 #include "interpreter/oopMapCache.hpp"
  34 #include "interpreter/rewriter.hpp"
  35 #include "jvmtifiles/jvmti.h"
  36 #include "memory/genOopClosures.inline.hpp"
  37 #include "memory/oopFactory.hpp"
  38 #include "memory/permGen.hpp"
  39 #include "oops/instanceKlass.hpp"
  40 #include "oops/instanceOop.hpp"
  41 #include "oops/methodOop.hpp"
  42 #include "oops/objArrayKlassKlass.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/symbolOop.hpp"
  45 #include "prims/jvmtiExport.hpp"
  46 #include "prims/jvmtiRedefineClassesTrace.hpp"
  47 #include "runtime/fieldDescriptor.hpp"
  48 #include "runtime/handles.inline.hpp"
  49 #include "runtime/javaCalls.hpp"
  50 #include "runtime/mutexLocker.hpp"
  51 #include "services/threadService.hpp"
  52 #include "utilities/dtrace.hpp"
  53 #ifdef TARGET_OS_FAMILY_linux
  54 # include "thread_linux.inline.hpp"
  55 #endif
  56 #ifdef TARGET_OS_FAMILY_solaris
  57 # include "thread_solaris.inline.hpp"
  58 #endif
  59 #ifdef TARGET_OS_FAMILY_windows
  60 # include "thread_windows.inline.hpp"
  61 #endif
  62 #ifndef SERIALGC
  63 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  64 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
  65 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
  66 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
  67 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
  68 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
  69 #include "oops/oop.pcgc.inline.hpp"
  70 #endif
  71 #ifdef COMPILER1
  72 #include "c1/c1_Compiler.hpp"
  73 #endif
  74 
  75 #ifdef DTRACE_ENABLED
  76 
  77 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
  78   char*, intptr_t, oop, intptr_t);
  79 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
  80   char*, intptr_t, oop, intptr_t, int);
  81 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
  82   char*, intptr_t, oop, intptr_t, int);
  83 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
  84   char*, intptr_t, oop, intptr_t, int);
  85 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
  86   char*, intptr_t, oop, intptr_t, int);
  87 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
  88   char*, intptr_t, oop, intptr_t, int);
  89 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
  90   char*, intptr_t, oop, intptr_t, int);
  91 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
  92   char*, intptr_t, oop, intptr_t, int);
  93 
  94 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
  95   {                                                              \
  96     char* data = NULL;                                           \
  97     int len = 0;                                                 \
  98     symbolOop name = (clss)->name();                             \
  99     if (name != NULL) {                                          \
 100       data = (char*)name->bytes();                               \
 101       len = name->utf8_length();                                 \
 102     }                                                            \
 103     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
 104       data, len, (clss)->class_loader(), thread_type);           \
 105   }
 106 
 107 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
 108   {                                                              \
 109     char* data = NULL;                                           \
 110     int len = 0;                                                 \
 111     symbolOop name = (clss)->name();                             \
 112     if (name != NULL) {                                          \
 113       data = (char*)name->bytes();                               \
 114       len = name->utf8_length();                                 \
 115     }                                                            \
 116     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
 117       data, len, (clss)->class_loader(), thread_type, wait);     \
 118   }
 119 
 120 #else //  ndef DTRACE_ENABLED
 121 
 122 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
 123 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
 124 
 125 #endif //  ndef DTRACE_ENABLED
 126 
 127 bool instanceKlass::should_be_initialized() const {
 128   return !is_initialized();
 129 }
 130 
 131 klassVtable* instanceKlass::vtable() const {
 132   return new klassVtable(as_klassOop(), start_of_vtable(), vtable_length() / vtableEntry::size());
 133 }
 134 
 135 klassItable* instanceKlass::itable() const {
 136   return new klassItable(as_klassOop());
 137 }
 138 
 139 void instanceKlass::eager_initialize(Thread *thread) {
 140   if (!EagerInitialization) return;
 141 
 142   if (this->is_not_initialized()) {
 143     // abort if the the class has a class initializer
 144     if (this->class_initializer() != NULL) return;
 145 
 146     // abort if it is java.lang.Object (initialization is handled in genesis)
 147     klassOop super = this->super();
 148     if (super == NULL) return;
 149 
 150     // abort if the super class should be initialized
 151     if (!instanceKlass::cast(super)->is_initialized()) return;
 152 
 153     // call body to expose the this pointer
 154     instanceKlassHandle this_oop(thread, this->as_klassOop());
 155     eager_initialize_impl(this_oop);
 156   }
 157 }
 158 
 159 
 160 void instanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
 161   EXCEPTION_MARK;
 162   ObjectLocker ol(this_oop, THREAD);
 163 
 164   // abort if someone beat us to the initialization
 165   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
 166 
 167   ClassState old_state = this_oop->_init_state;
 168   link_class_impl(this_oop, true, THREAD);
 169   if (HAS_PENDING_EXCEPTION) {
 170     CLEAR_PENDING_EXCEPTION;
 171     // Abort if linking the class throws an exception.
 172 
 173     // Use a test to avoid redundantly resetting the state if there's
 174     // no change.  Set_init_state() asserts that state changes make
 175     // progress, whereas here we might just be spinning in place.
 176     if( old_state != this_oop->_init_state )
 177       this_oop->set_init_state (old_state);
 178   } else {
 179     // linking successfull, mark class as initialized
 180     this_oop->set_init_state (fully_initialized);
 181     // trace
 182     if (TraceClassInitialization) {
 183       ResourceMark rm(THREAD);
 184       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
 185     }
 186   }
 187 }
 188 
 189 
 190 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 191 // process. The step comments refers to the procedure described in that section.
 192 // Note: implementation moved to static method to expose the this pointer.
 193 void instanceKlass::initialize(TRAPS) {
 194   if (this->should_be_initialized()) {
 195     HandleMark hm(THREAD);
 196     instanceKlassHandle this_oop(THREAD, this->as_klassOop());
 197     initialize_impl(this_oop, CHECK);
 198     // Note: at this point the class may be initialized
 199     //       OR it may be in the state of being initialized
 200     //       in case of recursive initialization!
 201   } else {
 202     assert(is_initialized(), "sanity check");
 203   }
 204 }
 205 
 206 
 207 bool instanceKlass::verify_code(
 208     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
 209   // 1) Verify the bytecodes
 210   Verifier::Mode mode =
 211     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
 212   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
 213 }
 214 
 215 
 216 // Used exclusively by the shared spaces dump mechanism to prevent
 217 // classes mapped into the shared regions in new VMs from appearing linked.
 218 
 219 void instanceKlass::unlink_class() {
 220   assert(is_linked(), "must be linked");
 221   _init_state = loaded;
 222 }
 223 
 224 void instanceKlass::link_class(TRAPS) {
 225   assert(is_loaded(), "must be loaded");
 226   if (!is_linked()) {
 227     instanceKlassHandle this_oop(THREAD, this->as_klassOop());
 228     link_class_impl(this_oop, true, CHECK);
 229   }
 230 }
 231 
 232 // Called to verify that a class can link during initialization, without
 233 // throwing a VerifyError.
 234 bool instanceKlass::link_class_or_fail(TRAPS) {
 235   assert(is_loaded(), "must be loaded");
 236   if (!is_linked()) {
 237     instanceKlassHandle this_oop(THREAD, this->as_klassOop());
 238     link_class_impl(this_oop, false, CHECK_false);
 239   }
 240   return is_linked();
 241 }
 242 
 243 bool instanceKlass::link_class_impl(
 244     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
 245   // check for error state
 246   if (this_oop->is_in_error_state()) {
 247     ResourceMark rm(THREAD);
 248     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
 249                this_oop->external_name(), false);
 250   }
 251   // return if already verified
 252   if (this_oop->is_linked()) {
 253     return true;
 254   }
 255 
 256   // Timing
 257   // timer handles recursion
 258   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 259   JavaThread* jt = (JavaThread*)THREAD;
 260 
 261   // link super class before linking this class
 262   instanceKlassHandle super(THREAD, this_oop->super());
 263   if (super.not_null()) {
 264     if (super->is_interface()) {  // check if super class is an interface
 265       ResourceMark rm(THREAD);
 266       Exceptions::fthrow(
 267         THREAD_AND_LOCATION,
 268         vmSymbolHandles::java_lang_IncompatibleClassChangeError(),
 269         "class %s has interface %s as super class",
 270         this_oop->external_name(),
 271         super->external_name()
 272       );
 273       return false;
 274     }
 275 
 276     link_class_impl(super, throw_verifyerror, CHECK_false);
 277   }
 278 
 279   // link all interfaces implemented by this class before linking this class
 280   objArrayHandle interfaces (THREAD, this_oop->local_interfaces());
 281   int num_interfaces = interfaces->length();
 282   for (int index = 0; index < num_interfaces; index++) {
 283     HandleMark hm(THREAD);
 284     instanceKlassHandle ih(THREAD, klassOop(interfaces->obj_at(index)));
 285     link_class_impl(ih, throw_verifyerror, CHECK_false);
 286   }
 287 
 288   // in case the class is linked in the process of linking its superclasses
 289   if (this_oop->is_linked()) {
 290     return true;
 291   }
 292 
 293   // trace only the link time for this klass that includes
 294   // the verification time
 295   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 296                              ClassLoader::perf_class_link_selftime(),
 297                              ClassLoader::perf_classes_linked(),
 298                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 299                              jt->get_thread_stat()->perf_timers_addr(),
 300                              PerfClassTraceTime::CLASS_LINK);
 301 
 302   // verification & rewriting
 303   {
 304     ObjectLocker ol(this_oop, THREAD);
 305     // rewritten will have been set if loader constraint error found
 306     // on an earlier link attempt
 307     // don't verify or rewrite if already rewritten
 308     if (!this_oop->is_linked()) {
 309       if (!this_oop->is_rewritten()) {
 310         {
 311           // Timer includes any side effects of class verification (resolution,
 312           // etc), but not recursive entry into verify_code().
 313           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
 314                                    ClassLoader::perf_class_verify_selftime(),
 315                                    ClassLoader::perf_classes_verified(),
 316                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
 317                                    jt->get_thread_stat()->perf_timers_addr(),
 318                                    PerfClassTraceTime::CLASS_VERIFY);
 319           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
 320           if (!verify_ok) {
 321             return false;
 322           }
 323         }
 324 
 325         // Just in case a side-effect of verify linked this class already
 326         // (which can sometimes happen since the verifier loads classes
 327         // using custom class loaders, which are free to initialize things)
 328         if (this_oop->is_linked()) {
 329           return true;
 330         }
 331 
 332         // also sets rewritten
 333         this_oop->rewrite_class(CHECK_false);
 334       }
 335 
 336       // Initialize the vtable and interface table after
 337       // methods have been rewritten since rewrite may
 338       // fabricate new methodOops.
 339       // also does loader constraint checking
 340       if (!this_oop()->is_shared()) {
 341         ResourceMark rm(THREAD);
 342         this_oop->vtable()->initialize_vtable(true, CHECK_false);
 343         this_oop->itable()->initialize_itable(true, CHECK_false);
 344       }
 345 #ifdef ASSERT
 346       else {
 347         ResourceMark rm(THREAD);
 348         this_oop->vtable()->verify(tty, true);
 349         // In case itable verification is ever added.
 350         // this_oop->itable()->verify(tty, true);
 351       }
 352 #endif
 353       this_oop->set_init_state(linked);
 354       if (JvmtiExport::should_post_class_prepare()) {
 355         Thread *thread = THREAD;
 356         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 357         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
 358       }
 359     }
 360   }
 361   return true;
 362 }
 363 
 364 
 365 // Rewrite the byte codes of all of the methods of a class.
 366 // Three cases:
 367 //    During the link of a newly loaded class.
 368 //    During the preloading of classes to be written to the shared spaces.
 369 //      - Rewrite the methods and update the method entry points.
 370 //
 371 //    During the link of a class in the shared spaces.
 372 //      - The methods were already rewritten, update the metho entry points.
 373 //
 374 // The rewriter must be called exactly once. Rewriting must happen after
 375 // verification but before the first method of the class is executed.
 376 
 377 void instanceKlass::rewrite_class(TRAPS) {
 378   assert(is_loaded(), "must be loaded");
 379   instanceKlassHandle this_oop(THREAD, this->as_klassOop());
 380   if (this_oop->is_rewritten()) {
 381     assert(this_oop()->is_shared(), "rewriting an unshared class?");
 382     return;
 383   }
 384   Rewriter::rewrite(this_oop, CHECK); // No exception can happen here
 385   this_oop->set_rewritten();
 386 }
 387 
 388 
 389 void instanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
 390   // Make sure klass is linked (verified) before initialization
 391   // A class could already be verified, since it has been reflected upon.
 392   this_oop->link_class(CHECK);
 393 
 394   DTRACE_CLASSINIT_PROBE(required, instanceKlass::cast(this_oop()), -1);
 395 
 396   bool wait = false;
 397 
 398   // refer to the JVM book page 47 for description of steps
 399   // Step 1
 400   { ObjectLocker ol(this_oop, THREAD);
 401 
 402     Thread *self = THREAD; // it's passed the current thread
 403 
 404     // Step 2
 405     // If we were to use wait() instead of waitInterruptibly() then
 406     // we might end up throwing IE from link/symbol resolution sites
 407     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
 408     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
 409         wait = true;
 410       ol.waitUninterruptibly(CHECK);
 411     }
 412 
 413     // Step 3
 414     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
 415       DTRACE_CLASSINIT_PROBE_WAIT(recursive, instanceKlass::cast(this_oop()), -1,wait);
 416       return;
 417     }
 418 
 419     // Step 4
 420     if (this_oop->is_initialized()) {
 421       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, instanceKlass::cast(this_oop()), -1,wait);
 422       return;
 423     }
 424 
 425     // Step 5
 426     if (this_oop->is_in_error_state()) {
 427       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, instanceKlass::cast(this_oop()), -1,wait);
 428       ResourceMark rm(THREAD);
 429       const char* desc = "Could not initialize class ";
 430       const char* className = this_oop->external_name();
 431       size_t msglen = strlen(desc) + strlen(className) + 1;
 432       char* message = NEW_RESOURCE_ARRAY(char, msglen);
 433       if (NULL == message) {
 434         // Out of memory: can't create detailed error message
 435         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 436       } else {
 437         jio_snprintf(message, msglen, "%s%s", desc, className);
 438         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 439       }
 440     }
 441 
 442     // Step 6
 443     this_oop->set_init_state(being_initialized);
 444     this_oop->set_init_thread(self);
 445   }
 446 
 447   // Step 7
 448   klassOop super_klass = this_oop->super();
 449   if (super_klass != NULL && !this_oop->is_interface() && Klass::cast(super_klass)->should_be_initialized()) {
 450     Klass::cast(super_klass)->initialize(THREAD);
 451 
 452     if (HAS_PENDING_EXCEPTION) {
 453       Handle e(THREAD, PENDING_EXCEPTION);
 454       CLEAR_PENDING_EXCEPTION;
 455       {
 456         EXCEPTION_MARK;
 457         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
 458         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
 459       }
 460       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, instanceKlass::cast(this_oop()), -1,wait);
 461       THROW_OOP(e());
 462     }
 463   }
 464 
 465   // Step 8
 466   {
 467     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
 468     JavaThread* jt = (JavaThread*)THREAD;
 469     DTRACE_CLASSINIT_PROBE_WAIT(clinit, instanceKlass::cast(this_oop()), -1,wait);
 470     // Timer includes any side effects of class initialization (resolution,
 471     // etc), but not recursive entry into call_class_initializer().
 472     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
 473                              ClassLoader::perf_class_init_selftime(),
 474                              ClassLoader::perf_classes_inited(),
 475                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 476                              jt->get_thread_stat()->perf_timers_addr(),
 477                              PerfClassTraceTime::CLASS_CLINIT);
 478     this_oop->call_class_initializer(THREAD);
 479   }
 480 
 481   // Step 9
 482   if (!HAS_PENDING_EXCEPTION) {
 483     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
 484     { ResourceMark rm(THREAD);
 485       debug_only(this_oop->vtable()->verify(tty, true);)
 486     }
 487   }
 488   else {
 489     // Step 10 and 11
 490     Handle e(THREAD, PENDING_EXCEPTION);
 491     CLEAR_PENDING_EXCEPTION;
 492     {
 493       EXCEPTION_MARK;
 494       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
 495       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
 496     }
 497     DTRACE_CLASSINIT_PROBE_WAIT(error, instanceKlass::cast(this_oop()), -1,wait);
 498     if (e->is_a(SystemDictionary::Error_klass())) {
 499       THROW_OOP(e());
 500     } else {
 501       JavaCallArguments args(e);
 502       THROW_ARG(vmSymbolHandles::java_lang_ExceptionInInitializerError(),
 503                 vmSymbolHandles::throwable_void_signature(),
 504                 &args);
 505     }
 506   }
 507   DTRACE_CLASSINIT_PROBE_WAIT(end, instanceKlass::cast(this_oop()), -1,wait);
 508 }
 509 
 510 
 511 // Note: implementation moved to static method to expose the this pointer.
 512 void instanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
 513   instanceKlassHandle kh(THREAD, this->as_klassOop());
 514   set_initialization_state_and_notify_impl(kh, state, CHECK);
 515 }
 516 
 517 void instanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
 518   ObjectLocker ol(this_oop, THREAD);
 519   this_oop->set_init_state(state);
 520   ol.notify_all(CHECK);
 521 }
 522 
 523 void instanceKlass::add_implementor(klassOop k) {
 524   assert(Compile_lock->owned_by_self(), "");
 525   // Filter out my subinterfaces.
 526   // (Note: Interfaces are never on the subklass list.)
 527   if (instanceKlass::cast(k)->is_interface()) return;
 528 
 529   // Filter out subclasses whose supers already implement me.
 530   // (Note: CHA must walk subclasses of direct implementors
 531   // in order to locate indirect implementors.)
 532   klassOop sk = instanceKlass::cast(k)->super();
 533   if (sk != NULL && instanceKlass::cast(sk)->implements_interface(as_klassOop()))
 534     // We only need to check one immediate superclass, since the
 535     // implements_interface query looks at transitive_interfaces.
 536     // Any supers of the super have the same (or fewer) transitive_interfaces.
 537     return;
 538 
 539   // Update number of implementors
 540   int i = _nof_implementors++;
 541 
 542   // Record this implementor, if there are not too many already
 543   if (i < implementors_limit) {
 544     assert(_implementors[i] == NULL, "should be exactly one implementor");
 545     oop_store_without_check((oop*)&_implementors[i], k);
 546   } else if (i == implementors_limit) {
 547     // clear out the list on first overflow
 548     for (int i2 = 0; i2 < implementors_limit; i2++)
 549       oop_store_without_check((oop*)&_implementors[i2], NULL);
 550   }
 551 
 552   // The implementor also implements the transitive_interfaces
 553   for (int index = 0; index < local_interfaces()->length(); index++) {
 554     instanceKlass::cast(klassOop(local_interfaces()->obj_at(index)))->add_implementor(k);
 555   }
 556 }
 557 
 558 void instanceKlass::init_implementor() {
 559   for (int i = 0; i < implementors_limit; i++)
 560     oop_store_without_check((oop*)&_implementors[i], NULL);
 561   _nof_implementors = 0;
 562 }
 563 
 564 
 565 void instanceKlass::process_interfaces(Thread *thread) {
 566   // link this class into the implementors list of every interface it implements
 567   KlassHandle this_as_oop (thread, this->as_klassOop());
 568   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
 569     assert(local_interfaces()->obj_at(i)->is_klass(), "must be a klass");
 570     instanceKlass* interf = instanceKlass::cast(klassOop(local_interfaces()->obj_at(i)));
 571     assert(interf->is_interface(), "expected interface");
 572     interf->add_implementor(this_as_oop());
 573   }
 574 }
 575 
 576 bool instanceKlass::can_be_primary_super_slow() const {
 577   if (is_interface())
 578     return false;
 579   else
 580     return Klass::can_be_primary_super_slow();
 581 }
 582 
 583 objArrayOop instanceKlass::compute_secondary_supers(int num_extra_slots, TRAPS) {
 584   // The secondaries are the implemented interfaces.
 585   instanceKlass* ik = instanceKlass::cast(as_klassOop());
 586   objArrayHandle interfaces (THREAD, ik->transitive_interfaces());
 587   int num_secondaries = num_extra_slots + interfaces->length();
 588   if (num_secondaries == 0) {
 589     return Universe::the_empty_system_obj_array();
 590   } else if (num_extra_slots == 0) {
 591     return interfaces();
 592   } else {
 593     // a mix of both
 594     objArrayOop secondaries = oopFactory::new_system_objArray(num_secondaries, CHECK_NULL);
 595     for (int i = 0; i < interfaces->length(); i++) {
 596       secondaries->obj_at_put(num_extra_slots+i, interfaces->obj_at(i));
 597     }
 598     return secondaries;
 599   }
 600 }
 601 
 602 bool instanceKlass::compute_is_subtype_of(klassOop k) {
 603   if (Klass::cast(k)->is_interface()) {
 604     return implements_interface(k);
 605   } else {
 606     return Klass::compute_is_subtype_of(k);
 607   }
 608 }
 609 
 610 bool instanceKlass::implements_interface(klassOop k) const {
 611   if (as_klassOop() == k) return true;
 612   assert(Klass::cast(k)->is_interface(), "should be an interface class");
 613   for (int i = 0; i < transitive_interfaces()->length(); i++) {
 614     if (transitive_interfaces()->obj_at(i) == k) {
 615       return true;
 616     }
 617   }
 618   return false;
 619 }
 620 
 621 objArrayOop instanceKlass::allocate_objArray(int n, int length, TRAPS) {
 622   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
 623   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
 624     report_java_out_of_memory("Requested array size exceeds VM limit");
 625     THROW_OOP_0(Universe::out_of_memory_error_array_size());
 626   }
 627   int size = objArrayOopDesc::object_size(length);
 628   klassOop ak = array_klass(n, CHECK_NULL);
 629   KlassHandle h_ak (THREAD, ak);
 630   objArrayOop o =
 631     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
 632   return o;
 633 }
 634 
 635 instanceOop instanceKlass::register_finalizer(instanceOop i, TRAPS) {
 636   if (TraceFinalizerRegistration) {
 637     tty->print("Registered ");
 638     i->print_value_on(tty);
 639     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
 640   }
 641   instanceHandle h_i(THREAD, i);
 642   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
 643   JavaValue result(T_VOID);
 644   JavaCallArguments args(h_i);
 645   methodHandle mh (THREAD, Universe::finalizer_register_method());
 646   JavaCalls::call(&result, mh, &args, CHECK_NULL);
 647   return h_i();
 648 }
 649 
 650 instanceOop instanceKlass::allocate_instance(TRAPS) {
 651   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
 652   int size = size_helper();  // Query before forming handle.
 653 
 654   KlassHandle h_k(THREAD, as_klassOop());
 655 
 656   instanceOop i;
 657 
 658   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
 659   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
 660     i = register_finalizer(i, CHECK_NULL);
 661   }
 662   return i;
 663 }
 664 
 665 instanceOop instanceKlass::allocate_permanent_instance(TRAPS) {
 666   // Finalizer registration occurs in the Object.<init> constructor
 667   // and constructors normally aren't run when allocating perm
 668   // instances so simply disallow finalizable perm objects.  This can
 669   // be relaxed if a need for it is found.
 670   assert(!has_finalizer(), "perm objects not allowed to have finalizers");
 671   int size = size_helper();  // Query before forming handle.
 672   KlassHandle h_k(THREAD, as_klassOop());
 673   instanceOop i = (instanceOop)
 674     CollectedHeap::permanent_obj_allocate(h_k, size, CHECK_NULL);
 675   return i;
 676 }
 677 
 678 void instanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
 679   if (is_interface() || is_abstract()) {
 680     ResourceMark rm(THREAD);
 681     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
 682               : vmSymbols::java_lang_InstantiationException(), external_name());
 683   }
 684   if (as_klassOop() == SystemDictionary::Class_klass()) {
 685     ResourceMark rm(THREAD);
 686     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
 687               : vmSymbols::java_lang_IllegalAccessException(), external_name());
 688   }
 689 }
 690 
 691 klassOop instanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
 692   instanceKlassHandle this_oop(THREAD, as_klassOop());
 693   return array_klass_impl(this_oop, or_null, n, THREAD);
 694 }
 695 
 696 klassOop instanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
 697   if (this_oop->array_klasses() == NULL) {
 698     if (or_null) return NULL;
 699 
 700     ResourceMark rm;
 701     JavaThread *jt = (JavaThread *)THREAD;
 702     {
 703       // Atomic creation of array_klasses
 704       MutexLocker mc(Compile_lock, THREAD);   // for vtables
 705       MutexLocker ma(MultiArray_lock, THREAD);
 706 
 707       // Check if update has already taken place
 708       if (this_oop->array_klasses() == NULL) {
 709         objArrayKlassKlass* oakk =
 710           (objArrayKlassKlass*)Universe::objArrayKlassKlassObj()->klass_part();
 711 
 712         klassOop  k = oakk->allocate_objArray_klass(1, this_oop, CHECK_NULL);
 713         this_oop->set_array_klasses(k);
 714       }
 715     }
 716   }
 717   // _this will always be set at this point
 718   objArrayKlass* oak = (objArrayKlass*)this_oop->array_klasses()->klass_part();
 719   if (or_null) {
 720     return oak->array_klass_or_null(n);
 721   }
 722   return oak->array_klass(n, CHECK_NULL);
 723 }
 724 
 725 klassOop instanceKlass::array_klass_impl(bool or_null, TRAPS) {
 726   return array_klass_impl(or_null, 1, THREAD);
 727 }
 728 
 729 void instanceKlass::call_class_initializer(TRAPS) {
 730   instanceKlassHandle ik (THREAD, as_klassOop());
 731   call_class_initializer_impl(ik, THREAD);
 732 }
 733 
 734 static int call_class_initializer_impl_counter = 0;   // for debugging
 735 
 736 methodOop instanceKlass::class_initializer() {
 737   return find_method(vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
 738 }
 739 
 740 void instanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
 741   methodHandle h_method(THREAD, this_oop->class_initializer());
 742   assert(!this_oop->is_initialized(), "we cannot initialize twice");
 743   if (TraceClassInitialization) {
 744     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
 745     this_oop->name()->print_value();
 746     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
 747   }
 748   if (h_method() != NULL) {
 749     JavaCallArguments args; // No arguments
 750     JavaValue result(T_VOID);
 751     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
 752   }
 753 }
 754 
 755 
 756 void instanceKlass::mask_for(methodHandle method, int bci,
 757   InterpreterOopMap* entry_for) {
 758   // Dirty read, then double-check under a lock.
 759   if (_oop_map_cache == NULL) {
 760     // Otherwise, allocate a new one.
 761     MutexLocker x(OopMapCacheAlloc_lock);
 762     // First time use. Allocate a cache in C heap
 763     if (_oop_map_cache == NULL) {
 764       _oop_map_cache = new OopMapCache();
 765     }
 766   }
 767   // _oop_map_cache is constant after init; lookup below does is own locking.
 768   _oop_map_cache->lookup(method, bci, entry_for);
 769 }
 770 
 771 
 772 bool instanceKlass::find_local_field(symbolOop name, symbolOop sig, fieldDescriptor* fd) const {
 773   const int n = fields()->length();
 774   for (int i = 0; i < n; i += next_offset ) {
 775     int name_index = fields()->ushort_at(i + name_index_offset);
 776     int sig_index  = fields()->ushort_at(i + signature_index_offset);
 777     symbolOop f_name = constants()->symbol_at(name_index);
 778     symbolOop f_sig  = constants()->symbol_at(sig_index);
 779     if (f_name == name && f_sig == sig) {
 780       fd->initialize(as_klassOop(), i);
 781       return true;
 782     }
 783   }
 784   return false;
 785 }
 786 
 787 
 788 void instanceKlass::field_names_and_sigs_iterate(OopClosure* closure) {
 789   const int n = fields()->length();
 790   for (int i = 0; i < n; i += next_offset ) {
 791     int name_index = fields()->ushort_at(i + name_index_offset);
 792     symbolOop name = constants()->symbol_at(name_index);
 793     closure->do_oop((oop*)&name);
 794 
 795     int sig_index  = fields()->ushort_at(i + signature_index_offset);
 796     symbolOop sig = constants()->symbol_at(sig_index);
 797     closure->do_oop((oop*)&sig);
 798   }
 799 }
 800 
 801 
 802 klassOop instanceKlass::find_interface_field(symbolOop name, symbolOop sig, fieldDescriptor* fd) const {
 803   const int n = local_interfaces()->length();
 804   for (int i = 0; i < n; i++) {
 805     klassOop intf1 = klassOop(local_interfaces()->obj_at(i));
 806     assert(Klass::cast(intf1)->is_interface(), "just checking type");
 807     // search for field in current interface
 808     if (instanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
 809       assert(fd->is_static(), "interface field must be static");
 810       return intf1;
 811     }
 812     // search for field in direct superinterfaces
 813     klassOop intf2 = instanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
 814     if (intf2 != NULL) return intf2;
 815   }
 816   // otherwise field lookup fails
 817   return NULL;
 818 }
 819 
 820 
 821 klassOop instanceKlass::find_field(symbolOop name, symbolOop sig, fieldDescriptor* fd) const {
 822   // search order according to newest JVM spec (5.4.3.2, p.167).
 823   // 1) search for field in current klass
 824   if (find_local_field(name, sig, fd)) {
 825     return as_klassOop();
 826   }
 827   // 2) search for field recursively in direct superinterfaces
 828   { klassOop intf = find_interface_field(name, sig, fd);
 829     if (intf != NULL) return intf;
 830   }
 831   // 3) apply field lookup recursively if superclass exists
 832   { klassOop supr = super();
 833     if (supr != NULL) return instanceKlass::cast(supr)->find_field(name, sig, fd);
 834   }
 835   // 4) otherwise field lookup fails
 836   return NULL;
 837 }
 838 
 839 
 840 klassOop instanceKlass::find_field(symbolOop name, symbolOop sig, bool is_static, fieldDescriptor* fd) const {
 841   // search order according to newest JVM spec (5.4.3.2, p.167).
 842   // 1) search for field in current klass
 843   if (find_local_field(name, sig, fd)) {
 844     if (fd->is_static() == is_static) return as_klassOop();
 845   }
 846   // 2) search for field recursively in direct superinterfaces
 847   if (is_static) {
 848     klassOop intf = find_interface_field(name, sig, fd);
 849     if (intf != NULL) return intf;
 850   }
 851   // 3) apply field lookup recursively if superclass exists
 852   { klassOop supr = super();
 853     if (supr != NULL) return instanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
 854   }
 855   // 4) otherwise field lookup fails
 856   return NULL;
 857 }
 858 
 859 
 860 bool instanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
 861   int length = fields()->length();
 862   for (int i = 0; i < length; i += next_offset) {
 863     if (offset_from_fields( i ) == offset) {
 864       fd->initialize(as_klassOop(), i);
 865       if (fd->is_static() == is_static) return true;
 866     }
 867   }
 868   return false;
 869 }
 870 
 871 
 872 bool instanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
 873   klassOop klass = as_klassOop();
 874   while (klass != NULL) {
 875     if (instanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
 876       return true;
 877     }
 878     klass = Klass::cast(klass)->super();
 879   }
 880   return false;
 881 }
 882 
 883 
 884 void instanceKlass::methods_do(void f(methodOop method)) {
 885   int len = methods()->length();
 886   for (int index = 0; index < len; index++) {
 887     methodOop m = methodOop(methods()->obj_at(index));
 888     assert(m->is_method(), "must be method");
 889     f(m);
 890   }
 891 }
 892 
 893 void instanceKlass::do_local_static_fields(FieldClosure* cl) {
 894   fieldDescriptor fd;
 895   int length = fields()->length();
 896   for (int i = 0; i < length; i += next_offset) {
 897     fd.initialize(as_klassOop(), i);
 898     if (fd.is_static()) cl->do_field(&fd);
 899   }
 900 }
 901 
 902 
 903 void instanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
 904   instanceKlassHandle h_this(THREAD, as_klassOop());
 905   do_local_static_fields_impl(h_this, f, CHECK);
 906 }
 907 
 908 
 909 void instanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
 910   fieldDescriptor fd;
 911   int length = this_oop->fields()->length();
 912   for (int i = 0; i < length; i += next_offset) {
 913     fd.initialize(this_oop(), i);
 914     if (fd.is_static()) { f(&fd, CHECK); } // Do NOT remove {}! (CHECK macro expands into several statements)
 915   }
 916 }
 917 
 918 
 919 static int compare_fields_by_offset(int* a, int* b) {
 920   return a[0] - b[0];
 921 }
 922 
 923 void instanceKlass::do_nonstatic_fields(FieldClosure* cl) {
 924   instanceKlass* super = superklass();
 925   if (super != NULL) {
 926     super->do_nonstatic_fields(cl);
 927   }
 928   fieldDescriptor fd;
 929   int length = fields()->length();
 930   // In DebugInfo nonstatic fields are sorted by offset.
 931   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1));
 932   int j = 0;
 933   for (int i = 0; i < length; i += next_offset) {
 934     fd.initialize(as_klassOop(), i);
 935     if (!fd.is_static()) {
 936       fields_sorted[j + 0] = fd.offset();
 937       fields_sorted[j + 1] = i;
 938       j += 2;
 939     }
 940   }
 941   if (j > 0) {
 942     length = j;
 943     // _sort_Fn is defined in growableArray.hpp.
 944     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
 945     for (int i = 0; i < length; i += 2) {
 946       fd.initialize(as_klassOop(), fields_sorted[i + 1]);
 947       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
 948       cl->do_field(&fd);
 949     }
 950   }
 951   FREE_C_HEAP_ARRAY(int, fields_sorted);
 952 }
 953 
 954 
 955 void instanceKlass::array_klasses_do(void f(klassOop k)) {
 956   if (array_klasses() != NULL)
 957     arrayKlass::cast(array_klasses())->array_klasses_do(f);
 958 }
 959 
 960 
 961 void instanceKlass::with_array_klasses_do(void f(klassOop k)) {
 962   f(as_klassOop());
 963   array_klasses_do(f);
 964 }
 965 
 966 #ifdef ASSERT
 967 static int linear_search(objArrayOop methods, symbolOop name, symbolOop signature) {
 968   int len = methods->length();
 969   for (int index = 0; index < len; index++) {
 970     methodOop m = (methodOop)(methods->obj_at(index));
 971     assert(m->is_method(), "must be method");
 972     if (m->signature() == signature && m->name() == name) {
 973        return index;
 974     }
 975   }
 976   return -1;
 977 }
 978 #endif
 979 
 980 methodOop instanceKlass::find_method(symbolOop name, symbolOop signature) const {
 981   return instanceKlass::find_method(methods(), name, signature);
 982 }
 983 
 984 methodOop instanceKlass::find_method(objArrayOop methods, symbolOop name, symbolOop signature) {
 985   int len = methods->length();
 986   // methods are sorted, so do binary search
 987   int l = 0;
 988   int h = len - 1;
 989   while (l <= h) {
 990     int mid = (l + h) >> 1;
 991     methodOop m = (methodOop)methods->obj_at(mid);
 992     assert(m->is_method(), "must be method");
 993     int res = m->name()->fast_compare(name);
 994     if (res == 0) {
 995       // found matching name; do linear search to find matching signature
 996       // first, quick check for common case
 997       if (m->signature() == signature) return m;
 998       // search downwards through overloaded methods
 999       int i;
1000       for (i = mid - 1; i >= l; i--) {
1001         methodOop m = (methodOop)methods->obj_at(i);
1002         assert(m->is_method(), "must be method");
1003         if (m->name() != name) break;
1004         if (m->signature() == signature) return m;
1005       }
1006       // search upwards
1007       for (i = mid + 1; i <= h; i++) {
1008         methodOop m = (methodOop)methods->obj_at(i);
1009         assert(m->is_method(), "must be method");
1010         if (m->name() != name) break;
1011         if (m->signature() == signature) return m;
1012       }
1013       // not found
1014 #ifdef ASSERT
1015       int index = linear_search(methods, name, signature);
1016       assert(index == -1, err_msg("binary search should have found entry %d", index));
1017 #endif
1018       return NULL;
1019     } else if (res < 0) {
1020       l = mid + 1;
1021     } else {
1022       h = mid - 1;
1023     }
1024   }
1025 #ifdef ASSERT
1026   int index = linear_search(methods, name, signature);
1027   assert(index == -1, err_msg("binary search should have found entry %d", index));
1028 #endif
1029   return NULL;
1030 }
1031 
1032 methodOop instanceKlass::uncached_lookup_method(symbolOop name, symbolOop signature) const {
1033   klassOop klass = as_klassOop();
1034   while (klass != NULL) {
1035     methodOop method = instanceKlass::cast(klass)->find_method(name, signature);
1036     if (method != NULL) return method;
1037     klass = instanceKlass::cast(klass)->super();
1038   }
1039   return NULL;
1040 }
1041 
1042 // lookup a method in all the interfaces that this class implements
1043 methodOop instanceKlass::lookup_method_in_all_interfaces(symbolOop name,
1044                                                          symbolOop signature) const {
1045   objArrayOop all_ifs = instanceKlass::cast(as_klassOop())->transitive_interfaces();
1046   int num_ifs = all_ifs->length();
1047   instanceKlass *ik = NULL;
1048   for (int i = 0; i < num_ifs; i++) {
1049     ik = instanceKlass::cast(klassOop(all_ifs->obj_at(i)));
1050     methodOop m = ik->lookup_method(name, signature);
1051     if (m != NULL) {
1052       return m;
1053     }
1054   }
1055   return NULL;
1056 }
1057 
1058 /* jni_id_for_impl for jfieldIds only */
1059 JNIid* instanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
1060   MutexLocker ml(JfieldIdCreation_lock);
1061   // Retry lookup after we got the lock
1062   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
1063   if (probe == NULL) {
1064     // Slow case, allocate new static field identifier
1065     probe = new JNIid(this_oop->as_klassOop(), offset, this_oop->jni_ids());
1066     this_oop->set_jni_ids(probe);
1067   }
1068   return probe;
1069 }
1070 
1071 
1072 /* jni_id_for for jfieldIds only */
1073 JNIid* instanceKlass::jni_id_for(int offset) {
1074   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1075   if (probe == NULL) {
1076     probe = jni_id_for_impl(this->as_klassOop(), offset);
1077   }
1078   return probe;
1079 }
1080 
1081 
1082 // Lookup or create a jmethodID.
1083 // This code is called by the VMThread and JavaThreads so the
1084 // locking has to be done very carefully to avoid deadlocks
1085 // and/or other cache consistency problems.
1086 //
1087 jmethodID instanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1088   size_t idnum = (size_t)method_h->method_idnum();
1089   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1090   size_t length = 0;
1091   jmethodID id = NULL;
1092 
1093   // We use a double-check locking idiom here because this cache is
1094   // performance sensitive. In the normal system, this cache only
1095   // transitions from NULL to non-NULL which is safe because we use
1096   // release_set_methods_jmethod_ids() to advertise the new cache.
1097   // A partially constructed cache should never be seen by a racing
1098   // thread. We also use release_store_ptr() to save a new jmethodID
1099   // in the cache so a partially constructed jmethodID should never be
1100   // seen either. Cache reads of existing jmethodIDs proceed without a
1101   // lock, but cache writes of a new jmethodID requires uniqueness and
1102   // creation of the cache itself requires no leaks so a lock is
1103   // generally acquired in those two cases.
1104   //
1105   // If the RedefineClasses() API has been used, then this cache can
1106   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1107   // Cache creation requires no leaks and we require safety between all
1108   // cache accesses and freeing of the old cache so a lock is generally
1109   // acquired when the RedefineClasses() API has been used.
1110 
1111   if (jmeths != NULL) {
1112     // the cache already exists
1113     if (!ik_h->idnum_can_increment()) {
1114       // the cache can't grow so we can just get the current values
1115       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1116     } else {
1117       // cache can grow so we have to be more careful
1118       if (Threads::number_of_threads() == 0 ||
1119           SafepointSynchronize::is_at_safepoint()) {
1120         // we're single threaded or at a safepoint - no locking needed
1121         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1122       } else {
1123         MutexLocker ml(JmethodIdCreation_lock);
1124         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1125       }
1126     }
1127   }
1128   // implied else:
1129   // we need to allocate a cache so default length and id values are good
1130 
1131   if (jmeths == NULL ||   // no cache yet
1132       length <= idnum ||  // cache is too short
1133       id == NULL) {       // cache doesn't contain entry
1134 
1135     // This function can be called by the VMThread so we have to do all
1136     // things that might block on a safepoint before grabbing the lock.
1137     // Otherwise, we can deadlock with the VMThread or have a cache
1138     // consistency issue. These vars keep track of what we might have
1139     // to free after the lock is dropped.
1140     jmethodID  to_dealloc_id     = NULL;
1141     jmethodID* to_dealloc_jmeths = NULL;
1142 
1143     // may not allocate new_jmeths or use it if we allocate it
1144     jmethodID* new_jmeths = NULL;
1145     if (length <= idnum) {
1146       // allocate a new cache that might be used
1147       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1148       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1);
1149       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1150       // cache size is stored in element[0], other elements offset by one
1151       new_jmeths[0] = (jmethodID)size;
1152     }
1153 
1154     // allocate a new jmethodID that might be used
1155     jmethodID new_id = NULL;
1156     if (method_h->is_old() && !method_h->is_obsolete()) {
1157       // The method passed in is old (but not obsolete), we need to use the current version
1158       methodOop current_method = ik_h->method_with_idnum((int)idnum);
1159       assert(current_method != NULL, "old and but not obsolete, so should exist");
1160       methodHandle current_method_h(current_method == NULL? method_h() : current_method);
1161       new_id = JNIHandles::make_jmethod_id(current_method_h);
1162     } else {
1163       // It is the current version of the method or an obsolete method,
1164       // use the version passed in
1165       new_id = JNIHandles::make_jmethod_id(method_h);
1166     }
1167 
1168     if (Threads::number_of_threads() == 0 ||
1169         SafepointSynchronize::is_at_safepoint()) {
1170       // we're single threaded or at a safepoint - no locking needed
1171       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1172                                           &to_dealloc_id, &to_dealloc_jmeths);
1173     } else {
1174       MutexLocker ml(JmethodIdCreation_lock);
1175       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1176                                           &to_dealloc_id, &to_dealloc_jmeths);
1177     }
1178 
1179     // The lock has been dropped so we can free resources.
1180     // Free up either the old cache or the new cache if we allocated one.
1181     if (to_dealloc_jmeths != NULL) {
1182       FreeHeap(to_dealloc_jmeths);
1183     }
1184     // free up the new ID since it wasn't needed
1185     if (to_dealloc_id != NULL) {
1186       JNIHandles::destroy_jmethod_id(to_dealloc_id);
1187     }
1188   }
1189   return id;
1190 }
1191 
1192 
1193 // Common code to fetch the jmethodID from the cache or update the
1194 // cache with the new jmethodID. This function should never do anything
1195 // that causes the caller to go to a safepoint or we can deadlock with
1196 // the VMThread or have cache consistency issues.
1197 //
1198 jmethodID instanceKlass::get_jmethod_id_fetch_or_update(
1199             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1200             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1201             jmethodID** to_dealloc_jmeths_p) {
1202   assert(new_id != NULL, "sanity check");
1203   assert(to_dealloc_id_p != NULL, "sanity check");
1204   assert(to_dealloc_jmeths_p != NULL, "sanity check");
1205   assert(Threads::number_of_threads() == 0 ||
1206          SafepointSynchronize::is_at_safepoint() ||
1207          JmethodIdCreation_lock->owned_by_self(), "sanity check");
1208 
1209   // reacquire the cache - we are locked, single threaded or at a safepoint
1210   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1211   jmethodID  id     = NULL;
1212   size_t     length = 0;
1213 
1214   if (jmeths == NULL ||                         // no cache yet
1215       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1216     if (jmeths != NULL) {
1217       // copy any existing entries from the old cache
1218       for (size_t index = 0; index < length; index++) {
1219         new_jmeths[index+1] = jmeths[index+1];
1220       }
1221       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
1222     }
1223     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1224   } else {
1225     // fetch jmethodID (if any) from the existing cache
1226     id = jmeths[idnum+1];
1227     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1228   }
1229   if (id == NULL) {
1230     // No matching jmethodID in the existing cache or we have a new
1231     // cache or we just grew the cache. This cache write is done here
1232     // by the first thread to win the foot race because a jmethodID
1233     // needs to be unique once it is generally available.
1234     id = new_id;
1235 
1236     // The jmethodID cache can be read while unlocked so we have to
1237     // make sure the new jmethodID is complete before installing it
1238     // in the cache.
1239     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1240   } else {
1241     *to_dealloc_id_p = new_id; // save new id for later delete
1242   }
1243   return id;
1244 }
1245 
1246 
1247 // Common code to get the jmethodID cache length and the jmethodID
1248 // value at index idnum if there is one.
1249 //
1250 void instanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1251        size_t idnum, size_t *length_p, jmethodID* id_p) {
1252   assert(cache != NULL, "sanity check");
1253   assert(length_p != NULL, "sanity check");
1254   assert(id_p != NULL, "sanity check");
1255 
1256   // cache size is stored in element[0], other elements offset by one
1257   *length_p = (size_t)cache[0];
1258   if (*length_p <= idnum) {  // cache is too short
1259     *id_p = NULL;
1260   } else {
1261     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
1262   }
1263 }
1264 
1265 
1266 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1267 jmethodID instanceKlass::jmethod_id_or_null(methodOop method) {
1268   size_t idnum = (size_t)method->method_idnum();
1269   jmethodID* jmeths = methods_jmethod_ids_acquire();
1270   size_t length;                                // length assigned as debugging crumb
1271   jmethodID id = NULL;
1272   if (jmeths != NULL &&                         // If there is a cache
1273       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
1274     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
1275   }
1276   return id;
1277 }
1278 
1279 
1280 // Cache an itable index
1281 void instanceKlass::set_cached_itable_index(size_t idnum, int index) {
1282   int* indices = methods_cached_itable_indices_acquire();
1283   int* to_dealloc_indices = NULL;
1284 
1285   // We use a double-check locking idiom here because this cache is
1286   // performance sensitive. In the normal system, this cache only
1287   // transitions from NULL to non-NULL which is safe because we use
1288   // release_set_methods_cached_itable_indices() to advertise the
1289   // new cache. A partially constructed cache should never be seen
1290   // by a racing thread. Cache reads and writes proceed without a
1291   // lock, but creation of the cache itself requires no leaks so a
1292   // lock is generally acquired in that case.
1293   //
1294   // If the RedefineClasses() API has been used, then this cache can
1295   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1296   // Cache creation requires no leaks and we require safety between all
1297   // cache accesses and freeing of the old cache so a lock is generally
1298   // acquired when the RedefineClasses() API has been used.
1299 
1300   if (indices == NULL || idnum_can_increment()) {
1301     // we need a cache or the cache can grow
1302     MutexLocker ml(JNICachedItableIndex_lock);
1303     // reacquire the cache to see if another thread already did the work
1304     indices = methods_cached_itable_indices_acquire();
1305     size_t length = 0;
1306     // cache size is stored in element[0], other elements offset by one
1307     if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
1308       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
1309       int* new_indices = NEW_C_HEAP_ARRAY(int, size+1);
1310       new_indices[0] = (int)size;
1311       // copy any existing entries
1312       size_t i;
1313       for (i = 0; i < length; i++) {
1314         new_indices[i+1] = indices[i+1];
1315       }
1316       // Set all the rest to -1
1317       for (i = length; i < size; i++) {
1318         new_indices[i+1] = -1;
1319       }
1320       if (indices != NULL) {
1321         // We have an old cache to delete so save it for after we
1322         // drop the lock.
1323         to_dealloc_indices = indices;
1324       }
1325       release_set_methods_cached_itable_indices(indices = new_indices);
1326     }
1327 
1328     if (idnum_can_increment()) {
1329       // this cache can grow so we have to write to it safely
1330       indices[idnum+1] = index;
1331     }
1332   } else {
1333     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1334   }
1335 
1336   if (!idnum_can_increment()) {
1337     // The cache cannot grow and this JNI itable index value does not
1338     // have to be unique like a jmethodID. If there is a race to set it,
1339     // it doesn't matter.
1340     indices[idnum+1] = index;
1341   }
1342 
1343   if (to_dealloc_indices != NULL) {
1344     // we allocated a new cache so free the old one
1345     FreeHeap(to_dealloc_indices);
1346   }
1347 }
1348 
1349 
1350 // Retrieve a cached itable index
1351 int instanceKlass::cached_itable_index(size_t idnum) {
1352   int* indices = methods_cached_itable_indices_acquire();
1353   if (indices != NULL && ((size_t)indices[0]) > idnum) {
1354      // indices exist and are long enough, retrieve possible cached
1355     return indices[idnum+1];
1356   }
1357   return -1;
1358 }
1359 
1360 
1361 //
1362 // nmethodBucket is used to record dependent nmethods for
1363 // deoptimization.  nmethod dependencies are actually <klass, method>
1364 // pairs but we really only care about the klass part for purposes of
1365 // finding nmethods which might need to be deoptimized.  Instead of
1366 // recording the method, a count of how many times a particular nmethod
1367 // was recorded is kept.  This ensures that any recording errors are
1368 // noticed since an nmethod should be removed as many times are it's
1369 // added.
1370 //
1371 class nmethodBucket {
1372  private:
1373   nmethod*       _nmethod;
1374   int            _count;
1375   nmethodBucket* _next;
1376 
1377  public:
1378   nmethodBucket(nmethod* nmethod, nmethodBucket* next) {
1379     _nmethod = nmethod;
1380     _next = next;
1381     _count = 1;
1382   }
1383   int count()                             { return _count; }
1384   int increment()                         { _count += 1; return _count; }
1385   int decrement()                         { _count -= 1; assert(_count >= 0, "don't underflow"); return _count; }
1386   nmethodBucket* next()                   { return _next; }
1387   void set_next(nmethodBucket* b)         { _next = b; }
1388   nmethod* get_nmethod()                  { return _nmethod; }
1389 };
1390 
1391 
1392 //
1393 // Walk the list of dependent nmethods searching for nmethods which
1394 // are dependent on the klassOop that was passed in and mark them for
1395 // deoptimization.  Returns the number of nmethods found.
1396 //
1397 int instanceKlass::mark_dependent_nmethods(DepChange& changes) {
1398   assert_locked_or_safepoint(CodeCache_lock);
1399   int found = 0;
1400   nmethodBucket* b = _dependencies;
1401   while (b != NULL) {
1402     nmethod* nm = b->get_nmethod();
1403     // since dependencies aren't removed until an nmethod becomes a zombie,
1404     // the dependency list may contain nmethods which aren't alive.
1405     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1406       if (TraceDependencies) {
1407         ResourceMark rm;
1408         tty->print_cr("Marked for deoptimization");
1409         tty->print_cr("  context = %s", this->external_name());
1410         changes.print();
1411         nm->print();
1412         nm->print_dependencies();
1413       }
1414       nm->mark_for_deoptimization();
1415       found++;
1416     }
1417     b = b->next();
1418   }
1419   return found;
1420 }
1421 
1422 
1423 //
1424 // Add an nmethodBucket to the list of dependencies for this nmethod.
1425 // It's possible that an nmethod has multiple dependencies on this klass
1426 // so a count is kept for each bucket to guarantee that creation and
1427 // deletion of dependencies is consistent.
1428 //
1429 void instanceKlass::add_dependent_nmethod(nmethod* nm) {
1430   assert_locked_or_safepoint(CodeCache_lock);
1431   nmethodBucket* b = _dependencies;
1432   nmethodBucket* last = NULL;
1433   while (b != NULL) {
1434     if (nm == b->get_nmethod()) {
1435       b->increment();
1436       return;
1437     }
1438     b = b->next();
1439   }
1440   _dependencies = new nmethodBucket(nm, _dependencies);
1441 }
1442 
1443 
1444 //
1445 // Decrement count of the nmethod in the dependency list and remove
1446 // the bucket competely when the count goes to 0.  This method must
1447 // find a corresponding bucket otherwise there's a bug in the
1448 // recording of dependecies.
1449 //
1450 void instanceKlass::remove_dependent_nmethod(nmethod* nm) {
1451   assert_locked_or_safepoint(CodeCache_lock);
1452   nmethodBucket* b = _dependencies;
1453   nmethodBucket* last = NULL;
1454   while (b != NULL) {
1455     if (nm == b->get_nmethod()) {
1456       if (b->decrement() == 0) {
1457         if (last == NULL) {
1458           _dependencies = b->next();
1459         } else {
1460           last->set_next(b->next());
1461         }
1462         delete b;
1463       }
1464       return;
1465     }
1466     last = b;
1467     b = b->next();
1468   }
1469 #ifdef ASSERT
1470   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
1471   nm->print();
1472 #endif // ASSERT
1473   ShouldNotReachHere();
1474 }
1475 
1476 
1477 #ifndef PRODUCT
1478 void instanceKlass::print_dependent_nmethods(bool verbose) {
1479   nmethodBucket* b = _dependencies;
1480   int idx = 0;
1481   while (b != NULL) {
1482     nmethod* nm = b->get_nmethod();
1483     tty->print("[%d] count=%d { ", idx++, b->count());
1484     if (!verbose) {
1485       nm->print_on(tty, "nmethod");
1486       tty->print_cr(" } ");
1487     } else {
1488       nm->print();
1489       nm->print_dependencies();
1490       tty->print_cr("--- } ");
1491     }
1492     b = b->next();
1493   }
1494 }
1495 
1496 
1497 bool instanceKlass::is_dependent_nmethod(nmethod* nm) {
1498   nmethodBucket* b = _dependencies;
1499   while (b != NULL) {
1500     if (nm == b->get_nmethod()) {
1501       return true;
1502     }
1503     b = b->next();
1504   }
1505   return false;
1506 }
1507 #endif //PRODUCT
1508 
1509 
1510 #ifdef ASSERT
1511 template <class T> void assert_is_in(T *p) {
1512   T heap_oop = oopDesc::load_heap_oop(p);
1513   if (!oopDesc::is_null(heap_oop)) {
1514     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1515     assert(Universe::heap()->is_in(o), "should be in heap");
1516   }
1517 }
1518 template <class T> void assert_is_in_closed_subset(T *p) {
1519   T heap_oop = oopDesc::load_heap_oop(p);
1520   if (!oopDesc::is_null(heap_oop)) {
1521     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1522     assert(Universe::heap()->is_in_closed_subset(o), "should be in closed");
1523   }
1524 }
1525 template <class T> void assert_is_in_reserved(T *p) {
1526   T heap_oop = oopDesc::load_heap_oop(p);
1527   if (!oopDesc::is_null(heap_oop)) {
1528     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1529     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
1530   }
1531 }
1532 template <class T> void assert_nothing(T *p) {}
1533 
1534 #else
1535 template <class T> void assert_is_in(T *p) {}
1536 template <class T> void assert_is_in_closed_subset(T *p) {}
1537 template <class T> void assert_is_in_reserved(T *p) {}
1538 template <class T> void assert_nothing(T *p) {}
1539 #endif // ASSERT
1540 
1541 //
1542 // Macros that iterate over areas of oops which are specialized on type of
1543 // oop pointer either narrow or wide, depending on UseCompressedOops
1544 //
1545 // Parameters are:
1546 //   T         - type of oop to point to (either oop or narrowOop)
1547 //   start_p   - starting pointer for region to iterate over
1548 //   count     - number of oops or narrowOops to iterate over
1549 //   do_oop    - action to perform on each oop (it's arbitrary C code which
1550 //               makes it more efficient to put in a macro rather than making
1551 //               it a template function)
1552 //   assert_fn - assert function which is template function because performance
1553 //               doesn't matter when enabled.
1554 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
1555   T, start_p, count, do_oop,                \
1556   assert_fn)                                \
1557 {                                           \
1558   T* p         = (T*)(start_p);             \
1559   T* const end = p + (count);               \
1560   while (p < end) {                         \
1561     (assert_fn)(p);                         \
1562     do_oop;                                 \
1563     ++p;                                    \
1564   }                                         \
1565 }
1566 
1567 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
1568   T, start_p, count, do_oop,                \
1569   assert_fn)                                \
1570 {                                           \
1571   T* const start = (T*)(start_p);           \
1572   T*       p     = start + (count);         \
1573   while (start < p) {                       \
1574     --p;                                    \
1575     (assert_fn)(p);                         \
1576     do_oop;                                 \
1577   }                                         \
1578 }
1579 
1580 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
1581   T, start_p, count, low, high,             \
1582   do_oop, assert_fn)                        \
1583 {                                           \
1584   T* const l = (T*)(low);                   \
1585   T* const h = (T*)(high);                  \
1586   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
1587          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
1588          "bounded region must be properly aligned"); \
1589   T* p       = (T*)(start_p);               \
1590   T* end     = p + (count);                 \
1591   if (p < l) p = l;                         \
1592   if (end > h) end = h;                     \
1593   while (p < end) {                         \
1594     (assert_fn)(p);                         \
1595     do_oop;                                 \
1596     ++p;                                    \
1597   }                                         \
1598 }
1599 
1600 
1601 // The following macros call specialized macros, passing either oop or
1602 // narrowOop as the specialization type.  These test the UseCompressedOops
1603 // flag.
1604 #define InstanceKlass_OOP_ITERATE(start_p, count,    \
1605                                   do_oop, assert_fn) \
1606 {                                                    \
1607   if (UseCompressedOops) {                           \
1608     InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop, \
1609       start_p, count,                                \
1610       do_oop, assert_fn)                             \
1611   } else {                                           \
1612     InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,       \
1613       start_p, count,                                \
1614       do_oop, assert_fn)                             \
1615   }                                                  \
1616 }
1617 
1618 #define InstanceKlass_BOUNDED_OOP_ITERATE(start_p, count, low, high,    \
1619                                           do_oop, assert_fn) \
1620 {                                                            \
1621   if (UseCompressedOops) {                                   \
1622     InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop, \
1623       start_p, count,                                        \
1624       low, high,                                             \
1625       do_oop, assert_fn)                                     \
1626   } else {                                                   \
1627     InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,       \
1628       start_p, count,                                        \
1629       low, high,                                             \
1630       do_oop, assert_fn)                                     \
1631   }                                                          \
1632 }
1633 
1634 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
1635 {                                                                        \
1636   /* Compute oopmap block range. The common case                         \
1637      is nonstatic_oop_map_size == 1. */                                  \
1638   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
1639   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
1640   if (UseCompressedOops) {                                               \
1641     while (map < end_map) {                                              \
1642       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
1643         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
1644         do_oop, assert_fn)                                               \
1645       ++map;                                                             \
1646     }                                                                    \
1647   } else {                                                               \
1648     while (map < end_map) {                                              \
1649       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
1650         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
1651         do_oop, assert_fn)                                               \
1652       ++map;                                                             \
1653     }                                                                    \
1654   }                                                                      \
1655 }
1656 
1657 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
1658 {                                                                        \
1659   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
1660   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
1661   if (UseCompressedOops) {                                               \
1662     while (start_map < map) {                                            \
1663       --map;                                                             \
1664       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
1665         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
1666         do_oop, assert_fn)                                               \
1667     }                                                                    \
1668   } else {                                                               \
1669     while (start_map < map) {                                            \
1670       --map;                                                             \
1671       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
1672         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
1673         do_oop, assert_fn)                                               \
1674     }                                                                    \
1675   }                                                                      \
1676 }
1677 
1678 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
1679                                               assert_fn)                 \
1680 {                                                                        \
1681   /* Compute oopmap block range. The common case is                      \
1682      nonstatic_oop_map_size == 1, so we accept the                       \
1683      usually non-existent extra overhead of examining                    \
1684      all the maps. */                                                    \
1685   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
1686   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
1687   if (UseCompressedOops) {                                               \
1688     while (map < end_map) {                                              \
1689       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
1690         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
1691         low, high,                                                       \
1692         do_oop, assert_fn)                                               \
1693       ++map;                                                             \
1694     }                                                                    \
1695   } else {                                                               \
1696     while (map < end_map) {                                              \
1697       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
1698         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
1699         low, high,                                                       \
1700         do_oop, assert_fn)                                               \
1701       ++map;                                                             \
1702     }                                                                    \
1703   }                                                                      \
1704 }
1705 
1706 void instanceKlass::follow_static_fields() {
1707   InstanceKlass_OOP_ITERATE( \
1708     start_of_static_fields(), static_oop_field_size(), \
1709     MarkSweep::mark_and_push(p), \
1710     assert_is_in_closed_subset)
1711 }
1712 
1713 #ifndef SERIALGC
1714 void instanceKlass::follow_static_fields(ParCompactionManager* cm) {
1715   InstanceKlass_OOP_ITERATE( \
1716     start_of_static_fields(), static_oop_field_size(), \
1717     PSParallelCompact::mark_and_push(cm, p), \
1718     assert_is_in)
1719 }
1720 #endif // SERIALGC
1721 
1722 void instanceKlass::adjust_static_fields() {
1723   InstanceKlass_OOP_ITERATE( \
1724     start_of_static_fields(), static_oop_field_size(), \
1725     MarkSweep::adjust_pointer(p), \
1726     assert_nothing)
1727 }
1728 
1729 #ifndef SERIALGC
1730 void instanceKlass::update_static_fields() {
1731   InstanceKlass_OOP_ITERATE( \
1732     start_of_static_fields(), static_oop_field_size(), \
1733     PSParallelCompact::adjust_pointer(p), \
1734     assert_nothing)
1735 }
1736 
1737 void instanceKlass::update_static_fields(HeapWord* beg_addr, HeapWord* end_addr) {
1738   InstanceKlass_BOUNDED_OOP_ITERATE( \
1739     start_of_static_fields(), static_oop_field_size(), \
1740     beg_addr, end_addr, \
1741     PSParallelCompact::adjust_pointer(p), \
1742     assert_nothing )
1743 }
1744 #endif // SERIALGC
1745 
1746 void instanceKlass::oop_follow_contents(oop obj) {
1747   assert(obj != NULL, "can't follow the content of NULL object");
1748   obj->follow_header();
1749   InstanceKlass_OOP_MAP_ITERATE( \
1750     obj, \
1751     MarkSweep::mark_and_push(p), \
1752     assert_is_in_closed_subset)
1753 }
1754 
1755 #ifndef SERIALGC
1756 void instanceKlass::oop_follow_contents(ParCompactionManager* cm,
1757                                         oop obj) {
1758   assert(obj != NULL, "can't follow the content of NULL object");
1759   obj->follow_header(cm);
1760   InstanceKlass_OOP_MAP_ITERATE( \
1761     obj, \
1762     PSParallelCompact::mark_and_push(cm, p), \
1763     assert_is_in)
1764 }
1765 #endif // SERIALGC
1766 
1767 // closure's do_header() method dicates whether the given closure should be
1768 // applied to the klass ptr in the object header.
1769 
1770 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
1771                                                                              \
1772 int instanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
1773   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
1774   /* header */                                                          \
1775   if (closure->do_header()) {                                           \
1776     obj->oop_iterate_header(closure);                                   \
1777   }                                                                     \
1778   InstanceKlass_OOP_MAP_ITERATE(                                        \
1779     obj,                                                                \
1780     SpecializationStats::                                               \
1781       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
1782     (closure)->do_oop##nv_suffix(p),                                    \
1783     assert_is_in_closed_subset)                                         \
1784   return size_helper();                                                 \
1785 }
1786 
1787 #ifndef SERIALGC
1788 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
1789                                                                                 \
1790 int instanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
1791                                               OopClosureType* closure) {        \
1792   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
1793   /* header */                                                                  \
1794   if (closure->do_header()) {                                                   \
1795     obj->oop_iterate_header(closure);                                           \
1796   }                                                                             \
1797   /* instance variables */                                                      \
1798   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
1799     obj,                                                                        \
1800     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
1801     (closure)->do_oop##nv_suffix(p),                                            \
1802     assert_is_in_closed_subset)                                                 \
1803    return size_helper();                                                        \
1804 }
1805 #endif // !SERIALGC
1806 
1807 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
1808                                                                         \
1809 int instanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
1810                                                   OopClosureType* closure, \
1811                                                   MemRegion mr) {          \
1812   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
1813   if (closure->do_header()) {                                            \
1814     obj->oop_iterate_header(closure, mr);                                \
1815   }                                                                      \
1816   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
1817     obj, mr.start(), mr.end(),                                           \
1818     (closure)->do_oop##nv_suffix(p),                                     \
1819     assert_is_in_closed_subset)                                          \
1820   return size_helper();                                                  \
1821 }
1822 
1823 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
1824 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
1825 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
1826 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
1827 #ifndef SERIALGC
1828 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
1829 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
1830 #endif // !SERIALGC
1831 
1832 void instanceKlass::iterate_static_fields(OopClosure* closure) {
1833     InstanceKlass_OOP_ITERATE( \
1834       start_of_static_fields(), static_oop_field_size(), \
1835       closure->do_oop(p), \
1836       assert_is_in_reserved)
1837 }
1838 
1839 void instanceKlass::iterate_static_fields(OopClosure* closure,
1840                                           MemRegion mr) {
1841   InstanceKlass_BOUNDED_OOP_ITERATE( \
1842     start_of_static_fields(), static_oop_field_size(), \
1843     mr.start(), mr.end(), \
1844     (closure)->do_oop_v(p), \
1845     assert_is_in_closed_subset)
1846 }
1847 
1848 int instanceKlass::oop_adjust_pointers(oop obj) {
1849   int size = size_helper();
1850   InstanceKlass_OOP_MAP_ITERATE( \
1851     obj, \
1852     MarkSweep::adjust_pointer(p), \
1853     assert_is_in)
1854   obj->adjust_header();
1855   return size;
1856 }
1857 
1858 #ifndef SERIALGC
1859 void instanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
1860   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
1861     obj, \
1862     if (PSScavenge::should_scavenge(p)) { \
1863       pm->claim_or_forward_depth(p); \
1864     }, \
1865     assert_nothing )
1866 }
1867 
1868 int instanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
1869   InstanceKlass_OOP_MAP_ITERATE( \
1870     obj, \
1871     PSParallelCompact::adjust_pointer(p), \
1872     assert_nothing)
1873   return size_helper();
1874 }
1875 
1876 int instanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj,
1877                                        HeapWord* beg_addr, HeapWord* end_addr) {
1878   InstanceKlass_BOUNDED_OOP_MAP_ITERATE( \
1879     obj, beg_addr, end_addr, \
1880     PSParallelCompact::adjust_pointer(p), \
1881     assert_nothing)
1882   return size_helper();
1883 }
1884 
1885 void instanceKlass::push_static_fields(PSPromotionManager* pm) {
1886   InstanceKlass_OOP_ITERATE( \
1887     start_of_static_fields(), static_oop_field_size(), \
1888     if (PSScavenge::should_scavenge(p)) { \
1889       pm->claim_or_forward_depth(p); \
1890     }, \
1891     assert_nothing )
1892 }
1893 
1894 void instanceKlass::copy_static_fields(ParCompactionManager* cm) {
1895   InstanceKlass_OOP_ITERATE( \
1896     start_of_static_fields(), static_oop_field_size(), \
1897     PSParallelCompact::adjust_pointer(p), \
1898     assert_is_in)
1899 }
1900 #endif // SERIALGC
1901 
1902 // This klass is alive but the implementor link is not followed/updated.
1903 // Subklass and sibling links are handled by Klass::follow_weak_klass_links
1904 
1905 void instanceKlass::follow_weak_klass_links(
1906   BoolObjectClosure* is_alive, OopClosure* keep_alive) {
1907   assert(is_alive->do_object_b(as_klassOop()), "this oop should be live");
1908   if (ClassUnloading) {
1909     for (int i = 0; i < implementors_limit; i++) {
1910       klassOop impl = _implementors[i];
1911       if (impl == NULL)  break;  // no more in the list
1912       if (!is_alive->do_object_b(impl)) {
1913         // remove this guy from the list by overwriting him with the tail
1914         int lasti = --_nof_implementors;
1915         assert(lasti >= i && lasti < implementors_limit, "just checking");
1916         _implementors[i] = _implementors[lasti];
1917         _implementors[lasti] = NULL;
1918         --i; // rerun the loop at this index
1919       }
1920     }
1921   } else {
1922     for (int i = 0; i < implementors_limit; i++) {
1923       keep_alive->do_oop(&adr_implementors()[i]);
1924     }
1925   }
1926   Klass::follow_weak_klass_links(is_alive, keep_alive);
1927 }
1928 
1929 void instanceKlass::remove_unshareable_info() {
1930   Klass::remove_unshareable_info();
1931   init_implementor();
1932 }
1933 
1934 static void clear_all_breakpoints(methodOop m) {
1935   m->clear_all_breakpoints();
1936 }
1937 
1938 void instanceKlass::release_C_heap_structures() {
1939   // Deallocate oop map cache
1940   if (_oop_map_cache != NULL) {
1941     delete _oop_map_cache;
1942     _oop_map_cache = NULL;
1943   }
1944 
1945   // Deallocate JNI identifiers for jfieldIDs
1946   JNIid::deallocate(jni_ids());
1947   set_jni_ids(NULL);
1948 
1949   jmethodID* jmeths = methods_jmethod_ids_acquire();
1950   if (jmeths != (jmethodID*)NULL) {
1951     release_set_methods_jmethod_ids(NULL);
1952     FreeHeap(jmeths);
1953   }
1954 
1955   int* indices = methods_cached_itable_indices_acquire();
1956   if (indices != (int*)NULL) {
1957     release_set_methods_cached_itable_indices(NULL);
1958     FreeHeap(indices);
1959   }
1960 
1961   // release dependencies
1962   nmethodBucket* b = _dependencies;
1963   _dependencies = NULL;
1964   while (b != NULL) {
1965     nmethodBucket* next = b->next();
1966     delete b;
1967     b = next;
1968   }
1969 
1970   // Deallocate breakpoint records
1971   if (breakpoints() != 0x0) {
1972     methods_do(clear_all_breakpoints);
1973     assert(breakpoints() == 0x0, "should have cleared breakpoints");
1974   }
1975 
1976   // deallocate information about previous versions
1977   if (_previous_versions != NULL) {
1978     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
1979       PreviousVersionNode * pv_node = _previous_versions->at(i);
1980       delete pv_node;
1981     }
1982     delete _previous_versions;
1983     _previous_versions = NULL;
1984   }
1985 
1986   // deallocate the cached class file
1987   if (_cached_class_file_bytes != NULL) {
1988     os::free(_cached_class_file_bytes);
1989     _cached_class_file_bytes = NULL;
1990     _cached_class_file_len = 0;
1991   }
1992 }
1993 
1994 const char* instanceKlass::signature_name() const {
1995   const char* src = (const char*) (name()->as_C_string());
1996   const int src_length = (int)strlen(src);
1997   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
1998   int src_index = 0;
1999   int dest_index = 0;
2000   dest[dest_index++] = 'L';
2001   while (src_index < src_length) {
2002     dest[dest_index++] = src[src_index++];
2003   }
2004   dest[dest_index++] = ';';
2005   dest[dest_index] = '\0';
2006   return dest;
2007 }
2008 
2009 // different verisons of is_same_class_package
2010 bool instanceKlass::is_same_class_package(klassOop class2) {
2011   klassOop class1 = as_klassOop();
2012   oop classloader1 = instanceKlass::cast(class1)->class_loader();
2013   symbolOop classname1 = Klass::cast(class1)->name();
2014 
2015   if (Klass::cast(class2)->oop_is_objArray()) {
2016     class2 = objArrayKlass::cast(class2)->bottom_klass();
2017   }
2018   oop classloader2;
2019   if (Klass::cast(class2)->oop_is_instance()) {
2020     classloader2 = instanceKlass::cast(class2)->class_loader();
2021   } else {
2022     assert(Klass::cast(class2)->oop_is_typeArray(), "should be type array");
2023     classloader2 = NULL;
2024   }
2025   symbolOop classname2 = Klass::cast(class2)->name();
2026 
2027   return instanceKlass::is_same_class_package(classloader1, classname1,
2028                                               classloader2, classname2);
2029 }
2030 
2031 bool instanceKlass::is_same_class_package(oop classloader2, symbolOop classname2) {
2032   klassOop class1 = as_klassOop();
2033   oop classloader1 = instanceKlass::cast(class1)->class_loader();
2034   symbolOop classname1 = Klass::cast(class1)->name();
2035 
2036   return instanceKlass::is_same_class_package(classloader1, classname1,
2037                                               classloader2, classname2);
2038 }
2039 
2040 // return true if two classes are in the same package, classloader
2041 // and classname information is enough to determine a class's package
2042 bool instanceKlass::is_same_class_package(oop class_loader1, symbolOop class_name1,
2043                                           oop class_loader2, symbolOop class_name2) {
2044   if (class_loader1 != class_loader2) {
2045     return false;
2046   } else if (class_name1 == class_name2) {
2047     return true;                // skip painful bytewise comparison
2048   } else {
2049     ResourceMark rm;
2050 
2051     // The symbolOop's are in UTF8 encoding. Since we only need to check explicitly
2052     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2053     // Otherwise, we just compare jbyte values between the strings.
2054     jbyte *name1 = class_name1->base();
2055     jbyte *name2 = class_name2->base();
2056 
2057     jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2058     jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2059 
2060     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2061       // One of the two doesn't have a package.  Only return true
2062       // if the other one also doesn't have a package.
2063       return last_slash1 == last_slash2;
2064     } else {
2065       // Skip over '['s
2066       if (*name1 == '[') {
2067         do {
2068           name1++;
2069         } while (*name1 == '[');
2070         if (*name1 != 'L') {
2071           // Something is terribly wrong.  Shouldn't be here.
2072           return false;
2073         }
2074       }
2075       if (*name2 == '[') {
2076         do {
2077           name2++;
2078         } while (*name2 == '[');
2079         if (*name2 != 'L') {
2080           // Something is terribly wrong.  Shouldn't be here.
2081           return false;
2082         }
2083       }
2084 
2085       // Check that package part is identical
2086       int length1 = last_slash1 - name1;
2087       int length2 = last_slash2 - name2;
2088 
2089       return UTF8::equal(name1, length1, name2, length2);
2090     }
2091   }
2092 }
2093 
2094 // Returns true iff super_method can be overridden by a method in targetclassname
2095 // See JSL 3rd edition 8.4.6.1
2096 // Assumes name-signature match
2097 // "this" is instanceKlass of super_method which must exist
2098 // note that the instanceKlass of the method in the targetclassname has not always been created yet
2099 bool instanceKlass::is_override(methodHandle super_method, Handle targetclassloader, symbolHandle targetclassname, TRAPS) {
2100    // Private methods can not be overridden
2101    if (super_method->is_private()) {
2102      return false;
2103    }
2104    // If super method is accessible, then override
2105    if ((super_method->is_protected()) ||
2106        (super_method->is_public())) {
2107      return true;
2108    }
2109    // Package-private methods are not inherited outside of package
2110    assert(super_method->is_package_private(), "must be package private");
2111    return(is_same_class_package(targetclassloader(), targetclassname()));
2112 }
2113 
2114 /* defined for now in jvm.cpp, for historical reasons *--
2115 klassOop instanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2116                                                      symbolOop& simple_name_result, TRAPS) {
2117   ...
2118 }
2119 */
2120 
2121 // tell if two classes have the same enclosing class (at package level)
2122 bool instanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2123                                                 klassOop class2_oop, TRAPS) {
2124   if (class2_oop == class1->as_klassOop())          return true;
2125   if (!Klass::cast(class2_oop)->oop_is_instance())  return false;
2126   instanceKlassHandle class2(THREAD, class2_oop);
2127 
2128   // must be in same package before we try anything else
2129   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2130     return false;
2131 
2132   // As long as there is an outer1.getEnclosingClass,
2133   // shift the search outward.
2134   instanceKlassHandle outer1 = class1;
2135   for (;;) {
2136     // As we walk along, look for equalities between outer1 and class2.
2137     // Eventually, the walks will terminate as outer1 stops
2138     // at the top-level class around the original class.
2139     bool ignore_inner_is_member;
2140     klassOop next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2141                                                     CHECK_false);
2142     if (next == NULL)  break;
2143     if (next == class2())  return true;
2144     outer1 = instanceKlassHandle(THREAD, next);
2145   }
2146 
2147   // Now do the same for class2.
2148   instanceKlassHandle outer2 = class2;
2149   for (;;) {
2150     bool ignore_inner_is_member;
2151     klassOop next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2152                                                     CHECK_false);
2153     if (next == NULL)  break;
2154     // Might as well check the new outer against all available values.
2155     if (next == class1())  return true;
2156     if (next == outer1())  return true;
2157     outer2 = instanceKlassHandle(THREAD, next);
2158   }
2159 
2160   // If by this point we have not found an equality between the
2161   // two classes, we know they are in separate package members.
2162   return false;
2163 }
2164 
2165 
2166 jint instanceKlass::compute_modifier_flags(TRAPS) const {
2167   klassOop k = as_klassOop();
2168   jint access = access_flags().as_int();
2169 
2170   // But check if it happens to be member class.
2171   typeArrayOop inner_class_list = inner_classes();
2172   int length = (inner_class_list == NULL) ? 0 : inner_class_list->length();
2173   assert (length % instanceKlass::inner_class_next_offset == 0, "just checking");
2174   if (length > 0) {
2175     typeArrayHandle inner_class_list_h(THREAD, inner_class_list);
2176     instanceKlassHandle ik(THREAD, k);
2177     for (int i = 0; i < length; i += instanceKlass::inner_class_next_offset) {
2178       int ioff = inner_class_list_h->ushort_at(
2179                       i + instanceKlass::inner_class_inner_class_info_offset);
2180 
2181       // Inner class attribute can be zero, skip it.
2182       // Strange but true:  JVM spec. allows null inner class refs.
2183       if (ioff == 0) continue;
2184 
2185       // only look at classes that are already loaded
2186       // since we are looking for the flags for our self.
2187       symbolOop inner_name = ik->constants()->klass_name_at(ioff);
2188       if ((ik->name() == inner_name)) {
2189         // This is really a member class.
2190         access = inner_class_list_h->ushort_at(i + instanceKlass::inner_class_access_flags_offset);
2191         break;
2192       }
2193     }
2194   }
2195   // Remember to strip ACC_SUPER bit
2196   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2197 }
2198 
2199 jint instanceKlass::jvmti_class_status() const {
2200   jint result = 0;
2201 
2202   if (is_linked()) {
2203     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2204   }
2205 
2206   if (is_initialized()) {
2207     assert(is_linked(), "Class status is not consistent");
2208     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2209   }
2210   if (is_in_error_state()) {
2211     result |= JVMTI_CLASS_STATUS_ERROR;
2212   }
2213   return result;
2214 }
2215 
2216 methodOop instanceKlass::method_at_itable(klassOop holder, int index, TRAPS) {
2217   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2218   int method_table_offset_in_words = ioe->offset()/wordSize;
2219   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2220                        / itableOffsetEntry::size();
2221 
2222   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2223     // If the interface isn't implemented by the receiver class,
2224     // the VM should throw IncompatibleClassChangeError.
2225     if (cnt >= nof_interfaces) {
2226       THROW_OOP_0(vmSymbols::java_lang_IncompatibleClassChangeError());
2227     }
2228 
2229     klassOop ik = ioe->interface_klass();
2230     if (ik == holder) break;
2231   }
2232 
2233   itableMethodEntry* ime = ioe->first_method_entry(as_klassOop());
2234   methodOop m = ime[index].method();
2235   if (m == NULL) {
2236     THROW_OOP_0(vmSymbols::java_lang_AbstractMethodError());
2237   }
2238   return m;
2239 }
2240 
2241 // On-stack replacement stuff
2242 void instanceKlass::add_osr_nmethod(nmethod* n) {
2243   // only one compilation can be active
2244   NEEDS_CLEANUP
2245   // This is a short non-blocking critical region, so the no safepoint check is ok.
2246   OsrList_lock->lock_without_safepoint_check();
2247   assert(n->is_osr_method(), "wrong kind of nmethod");
2248   n->set_osr_link(osr_nmethods_head());
2249   set_osr_nmethods_head(n);
2250   // Raise the highest osr level if necessary
2251   if (TieredCompilation) {
2252     methodOop m = n->method();
2253     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2254   }
2255   // Remember to unlock again
2256   OsrList_lock->unlock();
2257 
2258   // Get rid of the osr methods for the same bci that have lower levels.
2259   if (TieredCompilation) {
2260     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2261       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2262       if (inv != NULL && inv->is_in_use()) {
2263         inv->make_not_entrant();
2264       }
2265     }
2266   }
2267 }
2268 
2269 
2270 void instanceKlass::remove_osr_nmethod(nmethod* n) {
2271   // This is a short non-blocking critical region, so the no safepoint check is ok.
2272   OsrList_lock->lock_without_safepoint_check();
2273   assert(n->is_osr_method(), "wrong kind of nmethod");
2274   nmethod* last = NULL;
2275   nmethod* cur  = osr_nmethods_head();
2276   int max_level = CompLevel_none;  // Find the max comp level excluding n
2277   methodOop m = n->method();
2278   // Search for match
2279   while(cur != NULL && cur != n) {
2280     if (TieredCompilation) {
2281       // Find max level before n
2282       max_level = MAX2(max_level, cur->comp_level());
2283     }
2284     last = cur;
2285     cur = cur->osr_link();
2286   }
2287   nmethod* next = NULL;
2288   if (cur == n) {
2289     next = cur->osr_link();
2290     if (last == NULL) {
2291       // Remove first element
2292       set_osr_nmethods_head(next);
2293     } else {
2294       last->set_osr_link(next);
2295     }
2296   }
2297   n->set_osr_link(NULL);
2298   if (TieredCompilation) {
2299     cur = next;
2300     while (cur != NULL) {
2301       // Find max level after n
2302       max_level = MAX2(max_level, cur->comp_level());
2303       cur = cur->osr_link();
2304     }
2305     m->set_highest_osr_comp_level(max_level);
2306   }
2307   // Remember to unlock again
2308   OsrList_lock->unlock();
2309 }
2310 
2311 nmethod* instanceKlass::lookup_osr_nmethod(const methodOop m, int bci, int comp_level, bool match_level) const {
2312   // This is a short non-blocking critical region, so the no safepoint check is ok.
2313   OsrList_lock->lock_without_safepoint_check();
2314   nmethod* osr = osr_nmethods_head();
2315   nmethod* best = NULL;
2316   while (osr != NULL) {
2317     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2318     // There can be a time when a c1 osr method exists but we are waiting
2319     // for a c2 version. When c2 completes its osr nmethod we will trash
2320     // the c1 version and only be able to find the c2 version. However
2321     // while we overflow in the c1 code at back branches we don't want to
2322     // try and switch to the same code as we are already running
2323 
2324     if (osr->method() == m &&
2325         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2326       if (match_level) {
2327         if (osr->comp_level() == comp_level) {
2328           // Found a match - return it.
2329           OsrList_lock->unlock();
2330           return osr;
2331         }
2332       } else {
2333         if (best == NULL || (osr->comp_level() > best->comp_level())) {
2334           if (osr->comp_level() == CompLevel_highest_tier) {
2335             // Found the best possible - return it.
2336             OsrList_lock->unlock();
2337             return osr;
2338           }
2339           best = osr;
2340         }
2341       }
2342     }
2343     osr = osr->osr_link();
2344   }
2345   OsrList_lock->unlock();
2346   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2347     return best;
2348   }
2349   return NULL;
2350 }
2351 
2352 // -----------------------------------------------------------------------------------------------------
2353 #ifndef PRODUCT
2354 
2355 // Printing
2356 
2357 #define BULLET  " - "
2358 
2359 void FieldPrinter::do_field(fieldDescriptor* fd) {
2360   _st->print(BULLET);
2361    if (fd->is_static() || (_obj == NULL)) {
2362      fd->print_on(_st);
2363      _st->cr();
2364    } else {
2365      fd->print_on_for(_st, _obj);
2366      _st->cr();
2367    }
2368 }
2369 
2370 
2371 void instanceKlass::oop_print_on(oop obj, outputStream* st) {
2372   Klass::oop_print_on(obj, st);
2373 
2374   if (as_klassOop() == SystemDictionary::String_klass()) {
2375     typeArrayOop value  = java_lang_String::value(obj);
2376     juint        offset = java_lang_String::offset(obj);
2377     juint        length = java_lang_String::length(obj);
2378     if (value != NULL &&
2379         value->is_typeArray() &&
2380         offset          <= (juint) value->length() &&
2381         offset + length <= (juint) value->length()) {
2382       st->print(BULLET"string: ");
2383       Handle h_obj(obj);
2384       java_lang_String::print(h_obj, st);
2385       st->cr();
2386       if (!WizardMode)  return;  // that is enough
2387     }
2388   }
2389 
2390   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
2391   FieldPrinter print_nonstatic_field(st, obj);
2392   do_nonstatic_fields(&print_nonstatic_field);
2393 
2394   if (as_klassOop() == SystemDictionary::Class_klass()) {
2395     st->print(BULLET"signature: ");
2396     java_lang_Class::print_signature(obj, st);
2397     st->cr();
2398     klassOop mirrored_klass = java_lang_Class::as_klassOop(obj);
2399     st->print(BULLET"fake entry for mirror: ");
2400     mirrored_klass->print_value_on(st);
2401     st->cr();
2402     st->print(BULLET"fake entry resolved_constructor: ");
2403     methodOop ctor = java_lang_Class::resolved_constructor(obj);
2404     ctor->print_value_on(st);
2405     klassOop array_klass = java_lang_Class::array_klass(obj);
2406     st->cr();
2407     st->print(BULLET"fake entry for array: ");
2408     array_klass->print_value_on(st);
2409     st->cr();
2410   } else if (as_klassOop() == SystemDictionary::MethodType_klass()) {
2411     st->print(BULLET"signature: ");
2412     java_dyn_MethodType::print_signature(obj, st);
2413     st->cr();
2414   }
2415 }
2416 
2417 #endif //PRODUCT
2418 
2419 void instanceKlass::oop_print_value_on(oop obj, outputStream* st) {
2420   st->print("a ");
2421   name()->print_value_on(st);
2422   obj->print_address_on(st);
2423   if (as_klassOop() == SystemDictionary::String_klass()
2424       && java_lang_String::value(obj) != NULL) {
2425     ResourceMark rm;
2426     int len = java_lang_String::length(obj);
2427     int plen = (len < 24 ? len : 12);
2428     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
2429     st->print(" = \"%s\"", str);
2430     if (len > plen)
2431       st->print("...[%d]", len);
2432   } else if (as_klassOop() == SystemDictionary::Class_klass()) {
2433     klassOop k = java_lang_Class::as_klassOop(obj);
2434     st->print(" = ");
2435     if (k != NULL) {
2436       k->print_value_on(st);
2437     } else {
2438       const char* tname = type2name(java_lang_Class::primitive_type(obj));
2439       st->print("%s", tname ? tname : "type?");
2440     }
2441   } else if (as_klassOop() == SystemDictionary::MethodType_klass()) {
2442     st->print(" = ");
2443     java_dyn_MethodType::print_signature(obj, st);
2444   } else if (java_lang_boxing_object::is_instance(obj)) {
2445     st->print(" = ");
2446     java_lang_boxing_object::print(obj, st);
2447   }
2448 }
2449 
2450 const char* instanceKlass::internal_name() const {
2451   return external_name();
2452 }
2453 
2454 // Verification
2455 
2456 class VerifyFieldClosure: public OopClosure {
2457  protected:
2458   template <class T> void do_oop_work(T* p) {
2459     guarantee(Universe::heap()->is_in_closed_subset(p), "should be in heap");
2460     oop obj = oopDesc::load_decode_heap_oop(p);
2461     if (!obj->is_oop_or_null()) {
2462       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
2463       Universe::print();
2464       guarantee(false, "boom");
2465     }
2466   }
2467  public:
2468   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
2469   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
2470 };
2471 
2472 void instanceKlass::oop_verify_on(oop obj, outputStream* st) {
2473   Klass::oop_verify_on(obj, st);
2474   VerifyFieldClosure blk;
2475   oop_oop_iterate(obj, &blk);
2476 }
2477 
2478 #ifndef PRODUCT
2479 
2480 void instanceKlass::verify_class_klass_nonstatic_oop_maps(klassOop k) {
2481   // This verification code is disabled.  JDK_Version::is_gte_jdk14x_version()
2482   // cannot be called since this function is called before the VM is
2483   // able to determine what JDK version is running with.
2484   // The check below always is false since 1.4.
2485   return;
2486 
2487   // This verification code temporarily disabled for the 1.4
2488   // reflection implementation since java.lang.Class now has
2489   // Java-level instance fields. Should rewrite this to handle this
2490   // case.
2491   if (!(JDK_Version::is_gte_jdk14x_version() && UseNewReflection)) {
2492     // Verify that java.lang.Class instances have a fake oop field added.
2493     instanceKlass* ik = instanceKlass::cast(k);
2494 
2495     // Check that we have the right class
2496     static bool first_time = true;
2497     guarantee(k == SystemDictionary::Class_klass() && first_time, "Invalid verify of maps");
2498     first_time = false;
2499     const int extra = java_lang_Class::number_of_fake_oop_fields;
2500     guarantee(ik->nonstatic_field_size() == extra, "just checking");
2501     guarantee(ik->nonstatic_oop_map_count() == 1, "just checking");
2502     guarantee(ik->size_helper() == align_object_size(instanceOopDesc::header_size() + extra), "just checking");
2503 
2504     // Check that the map is (2,extra)
2505     int offset = java_lang_Class::klass_offset;
2506 
2507     OopMapBlock* map = ik->start_of_nonstatic_oop_maps();
2508     guarantee(map->offset() == offset && map->count() == (unsigned int) extra,
2509               "sanity");
2510   }
2511 }
2512 
2513 #endif // ndef PRODUCT
2514 
2515 // JNIid class for jfieldIDs only
2516 // Note to reviewers:
2517 // These JNI functions are just moved over to column 1 and not changed
2518 // in the compressed oops workspace.
2519 JNIid::JNIid(klassOop holder, int offset, JNIid* next) {
2520   _holder = holder;
2521   _offset = offset;
2522   _next = next;
2523   debug_only(_is_static_field_id = false;)
2524 }
2525 
2526 
2527 JNIid* JNIid::find(int offset) {
2528   JNIid* current = this;
2529   while (current != NULL) {
2530     if (current->offset() == offset) return current;
2531     current = current->next();
2532   }
2533   return NULL;
2534 }
2535 
2536 void JNIid::oops_do(OopClosure* f) {
2537   for (JNIid* cur = this; cur != NULL; cur = cur->next()) {
2538     f->do_oop(cur->holder_addr());
2539   }
2540 }
2541 
2542 void JNIid::deallocate(JNIid* current) {
2543   while (current != NULL) {
2544     JNIid* next = current->next();
2545     delete current;
2546     current = next;
2547   }
2548 }
2549 
2550 
2551 void JNIid::verify(klassOop holder) {
2552   int first_field_offset  = instanceKlass::cast(holder)->offset_of_static_fields();
2553   int end_field_offset;
2554   end_field_offset = first_field_offset + (instanceKlass::cast(holder)->static_field_size() * wordSize);
2555 
2556   JNIid* current = this;
2557   while (current != NULL) {
2558     guarantee(current->holder() == holder, "Invalid klass in JNIid");
2559 #ifdef ASSERT
2560     int o = current->offset();
2561     if (current->is_static_field_id()) {
2562       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
2563     }
2564 #endif
2565     current = current->next();
2566   }
2567 }
2568 
2569 
2570 #ifdef ASSERT
2571 void instanceKlass::set_init_state(ClassState state) {
2572   bool good_state = as_klassOop()->is_shared() ? (_init_state <= state)
2573                                                : (_init_state < state);
2574   assert(good_state || state == allocated, "illegal state transition");
2575   _init_state = state;
2576 }
2577 #endif
2578 
2579 
2580 // RedefineClasses() support for previous versions:
2581 
2582 // Add an information node that contains weak references to the
2583 // interesting parts of the previous version of the_class.
2584 // This is also where we clean out any unused weak references.
2585 // Note that while we delete nodes from the _previous_versions
2586 // array, we never delete the array itself until the klass is
2587 // unloaded. The has_been_redefined() query depends on that fact.
2588 //
2589 void instanceKlass::add_previous_version(instanceKlassHandle ikh,
2590        BitMap* emcp_methods, int emcp_method_count) {
2591   assert(Thread::current()->is_VM_thread(),
2592          "only VMThread can add previous versions");
2593 
2594   if (_previous_versions == NULL) {
2595     // This is the first previous version so make some space.
2596     // Start with 2 elements under the assumption that the class
2597     // won't be redefined much.
2598     _previous_versions =  new (ResourceObj::C_HEAP)
2599                             GrowableArray<PreviousVersionNode *>(2, true);
2600   }
2601 
2602   // RC_TRACE macro has an embedded ResourceMark
2603   RC_TRACE(0x00000100, ("adding previous version ref for %s @%d, EMCP_cnt=%d",
2604     ikh->external_name(), _previous_versions->length(), emcp_method_count));
2605   constantPoolHandle cp_h(ikh->constants());
2606   jobject cp_ref;
2607   if (cp_h->is_shared()) {
2608     // a shared ConstantPool requires a regular reference; a weak
2609     // reference would be collectible
2610     cp_ref = JNIHandles::make_global(cp_h);
2611   } else {
2612     cp_ref = JNIHandles::make_weak_global(cp_h);
2613   }
2614   PreviousVersionNode * pv_node = NULL;
2615   objArrayOop old_methods = ikh->methods();
2616 
2617   if (emcp_method_count == 0) {
2618     // non-shared ConstantPool gets a weak reference
2619     pv_node = new PreviousVersionNode(cp_ref, !cp_h->is_shared(), NULL);
2620     RC_TRACE(0x00000400,
2621       ("add: all methods are obsolete; flushing any EMCP weak refs"));
2622   } else {
2623     int local_count = 0;
2624     GrowableArray<jweak>* method_refs = new (ResourceObj::C_HEAP)
2625       GrowableArray<jweak>(emcp_method_count, true);
2626     for (int i = 0; i < old_methods->length(); i++) {
2627       if (emcp_methods->at(i)) {
2628         // this old method is EMCP so save a weak ref
2629         methodOop old_method = (methodOop) old_methods->obj_at(i);
2630         methodHandle old_method_h(old_method);
2631         jweak method_ref = JNIHandles::make_weak_global(old_method_h);
2632         method_refs->append(method_ref);
2633         if (++local_count >= emcp_method_count) {
2634           // no more EMCP methods so bail out now
2635           break;
2636         }
2637       }
2638     }
2639     // non-shared ConstantPool gets a weak reference
2640     pv_node = new PreviousVersionNode(cp_ref, !cp_h->is_shared(), method_refs);
2641   }
2642 
2643   _previous_versions->append(pv_node);
2644 
2645   // Using weak references allows the interesting parts of previous
2646   // classes to be GC'ed when they are no longer needed. Since the
2647   // caller is the VMThread and we are at a safepoint, this is a good
2648   // time to clear out unused weak references.
2649 
2650   RC_TRACE(0x00000400, ("add: previous version length=%d",
2651     _previous_versions->length()));
2652 
2653   // skip the last entry since we just added it
2654   for (int i = _previous_versions->length() - 2; i >= 0; i--) {
2655     // check the previous versions array for a GC'ed weak refs
2656     pv_node = _previous_versions->at(i);
2657     cp_ref = pv_node->prev_constant_pool();
2658     assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
2659     if (cp_ref == NULL) {
2660       delete pv_node;
2661       _previous_versions->remove_at(i);
2662       // Since we are traversing the array backwards, we don't have to
2663       // do anything special with the index.
2664       continue;  // robustness
2665     }
2666 
2667     constantPoolOop cp = (constantPoolOop)JNIHandles::resolve(cp_ref);
2668     if (cp == NULL) {
2669       // this entry has been GC'ed so remove it
2670       delete pv_node;
2671       _previous_versions->remove_at(i);
2672       // Since we are traversing the array backwards, we don't have to
2673       // do anything special with the index.
2674       continue;
2675     } else {
2676       RC_TRACE(0x00000400, ("add: previous version @%d is alive", i));
2677     }
2678 
2679     GrowableArray<jweak>* method_refs = pv_node->prev_EMCP_methods();
2680     if (method_refs != NULL) {
2681       RC_TRACE(0x00000400, ("add: previous methods length=%d",
2682         method_refs->length()));
2683       for (int j = method_refs->length() - 1; j >= 0; j--) {
2684         jweak method_ref = method_refs->at(j);
2685         assert(method_ref != NULL, "weak method ref was unexpectedly cleared");
2686         if (method_ref == NULL) {
2687           method_refs->remove_at(j);
2688           // Since we are traversing the array backwards, we don't have to
2689           // do anything special with the index.
2690           continue;  // robustness
2691         }
2692 
2693         methodOop method = (methodOop)JNIHandles::resolve(method_ref);
2694         if (method == NULL || emcp_method_count == 0) {
2695           // This method entry has been GC'ed or the current
2696           // RedefineClasses() call has made all methods obsolete
2697           // so remove it.
2698           JNIHandles::destroy_weak_global(method_ref);
2699           method_refs->remove_at(j);
2700         } else {
2701           // RC_TRACE macro has an embedded ResourceMark
2702           RC_TRACE(0x00000400,
2703             ("add: %s(%s): previous method @%d in version @%d is alive",
2704             method->name()->as_C_string(), method->signature()->as_C_string(),
2705             j, i));
2706         }
2707       }
2708     }
2709   }
2710 
2711   int obsolete_method_count = old_methods->length() - emcp_method_count;
2712 
2713   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
2714       _previous_versions->length() > 1) {
2715     // We have a mix of obsolete and EMCP methods. If there is more
2716     // than the previous version that we just added, then we have to
2717     // clear out any matching EMCP method entries the hard way.
2718     int local_count = 0;
2719     for (int i = 0; i < old_methods->length(); i++) {
2720       if (!emcp_methods->at(i)) {
2721         // only obsolete methods are interesting
2722         methodOop old_method = (methodOop) old_methods->obj_at(i);
2723         symbolOop m_name = old_method->name();
2724         symbolOop m_signature = old_method->signature();
2725 
2726         // skip the last entry since we just added it
2727         for (int j = _previous_versions->length() - 2; j >= 0; j--) {
2728           // check the previous versions array for a GC'ed weak refs
2729           pv_node = _previous_versions->at(j);
2730           cp_ref = pv_node->prev_constant_pool();
2731           assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
2732           if (cp_ref == NULL) {
2733             delete pv_node;
2734             _previous_versions->remove_at(j);
2735             // Since we are traversing the array backwards, we don't have to
2736             // do anything special with the index.
2737             continue;  // robustness
2738           }
2739 
2740           constantPoolOop cp = (constantPoolOop)JNIHandles::resolve(cp_ref);
2741           if (cp == NULL) {
2742             // this entry has been GC'ed so remove it
2743             delete pv_node;
2744             _previous_versions->remove_at(j);
2745             // Since we are traversing the array backwards, we don't have to
2746             // do anything special with the index.
2747             continue;
2748           }
2749 
2750           GrowableArray<jweak>* method_refs = pv_node->prev_EMCP_methods();
2751           if (method_refs == NULL) {
2752             // We have run into a PreviousVersion generation where
2753             // all methods were made obsolete during that generation's
2754             // RedefineClasses() operation. At the time of that
2755             // operation, all EMCP methods were flushed so we don't
2756             // have to go back any further.
2757             //
2758             // A NULL method_refs is different than an empty method_refs.
2759             // We cannot infer any optimizations about older generations
2760             // from an empty method_refs for the current generation.
2761             break;
2762           }
2763 
2764           for (int k = method_refs->length() - 1; k >= 0; k--) {
2765             jweak method_ref = method_refs->at(k);
2766             assert(method_ref != NULL,
2767               "weak method ref was unexpectedly cleared");
2768             if (method_ref == NULL) {
2769               method_refs->remove_at(k);
2770               // Since we are traversing the array backwards, we don't
2771               // have to do anything special with the index.
2772               continue;  // robustness
2773             }
2774 
2775             methodOop method = (methodOop)JNIHandles::resolve(method_ref);
2776             if (method == NULL) {
2777               // this method entry has been GC'ed so skip it
2778               JNIHandles::destroy_weak_global(method_ref);
2779               method_refs->remove_at(k);
2780               continue;
2781             }
2782 
2783             if (method->name() == m_name &&
2784                 method->signature() == m_signature) {
2785               // The current RedefineClasses() call has made all EMCP
2786               // versions of this method obsolete so mark it as obsolete
2787               // and remove the weak ref.
2788               RC_TRACE(0x00000400,
2789                 ("add: %s(%s): flush obsolete method @%d in version @%d",
2790                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
2791 
2792               method->set_is_obsolete();
2793               JNIHandles::destroy_weak_global(method_ref);
2794               method_refs->remove_at(k);
2795               break;
2796             }
2797           }
2798 
2799           // The previous loop may not find a matching EMCP method, but
2800           // that doesn't mean that we can optimize and not go any
2801           // further back in the PreviousVersion generations. The EMCP
2802           // method for this generation could have already been GC'ed,
2803           // but there still may be an older EMCP method that has not
2804           // been GC'ed.
2805         }
2806 
2807         if (++local_count >= obsolete_method_count) {
2808           // no more obsolete methods so bail out now
2809           break;
2810         }
2811       }
2812     }
2813   }
2814 } // end add_previous_version()
2815 
2816 
2817 // Determine if instanceKlass has a previous version.
2818 bool instanceKlass::has_previous_version() const {
2819   if (_previous_versions == NULL) {
2820     // no previous versions array so answer is easy
2821     return false;
2822   }
2823 
2824   for (int i = _previous_versions->length() - 1; i >= 0; i--) {
2825     // Check the previous versions array for an info node that hasn't
2826     // been GC'ed
2827     PreviousVersionNode * pv_node = _previous_versions->at(i);
2828 
2829     jobject cp_ref = pv_node->prev_constant_pool();
2830     assert(cp_ref != NULL, "cp reference was unexpectedly cleared");
2831     if (cp_ref == NULL) {
2832       continue;  // robustness
2833     }
2834 
2835     constantPoolOop cp = (constantPoolOop)JNIHandles::resolve(cp_ref);
2836     if (cp != NULL) {
2837       // we have at least one previous version
2838       return true;
2839     }
2840 
2841     // We don't have to check the method refs. If the constant pool has
2842     // been GC'ed then so have the methods.
2843   }
2844 
2845   // all of the underlying nodes' info has been GC'ed
2846   return false;
2847 } // end has_previous_version()
2848 
2849 methodOop instanceKlass::method_with_idnum(int idnum) {
2850   methodOop m = NULL;
2851   if (idnum < methods()->length()) {
2852     m = (methodOop) methods()->obj_at(idnum);
2853   }
2854   if (m == NULL || m->method_idnum() != idnum) {
2855     for (int index = 0; index < methods()->length(); ++index) {
2856       m = (methodOop) methods()->obj_at(index);
2857       if (m->method_idnum() == idnum) {
2858         return m;
2859       }
2860     }
2861   }
2862   return m;
2863 }
2864 
2865 
2866 // Set the annotation at 'idnum' to 'anno'.
2867 // We don't want to create or extend the array if 'anno' is NULL, since that is the
2868 // default value.  However, if the array exists and is long enough, we must set NULL values.
2869 void instanceKlass::set_methods_annotations_of(int idnum, typeArrayOop anno, objArrayOop* md_p) {
2870   objArrayOop md = *md_p;
2871   if (md != NULL && md->length() > idnum) {
2872     md->obj_at_put(idnum, anno);
2873   } else if (anno != NULL) {
2874     // create the array
2875     int length = MAX2(idnum+1, (int)_idnum_allocated_count);
2876     md = oopFactory::new_system_objArray(length, Thread::current());
2877     if (*md_p != NULL) {
2878       // copy the existing entries
2879       for (int index = 0; index < (*md_p)->length(); index++) {
2880         md->obj_at_put(index, (*md_p)->obj_at(index));
2881       }
2882     }
2883     set_annotations(md, md_p);
2884     md->obj_at_put(idnum, anno);
2885   } // if no array and idnum isn't included there is nothing to do
2886 }
2887 
2888 // Construct a PreviousVersionNode entry for the array hung off
2889 // the instanceKlass.
2890 PreviousVersionNode::PreviousVersionNode(jobject prev_constant_pool,
2891   bool prev_cp_is_weak, GrowableArray<jweak>* prev_EMCP_methods) {
2892 
2893   _prev_constant_pool = prev_constant_pool;
2894   _prev_cp_is_weak = prev_cp_is_weak;
2895   _prev_EMCP_methods = prev_EMCP_methods;
2896 }
2897 
2898 
2899 // Destroy a PreviousVersionNode
2900 PreviousVersionNode::~PreviousVersionNode() {
2901   if (_prev_constant_pool != NULL) {
2902     if (_prev_cp_is_weak) {
2903       JNIHandles::destroy_weak_global(_prev_constant_pool);
2904     } else {
2905       JNIHandles::destroy_global(_prev_constant_pool);
2906     }
2907   }
2908 
2909   if (_prev_EMCP_methods != NULL) {
2910     for (int i = _prev_EMCP_methods->length() - 1; i >= 0; i--) {
2911       jweak method_ref = _prev_EMCP_methods->at(i);
2912       if (method_ref != NULL) {
2913         JNIHandles::destroy_weak_global(method_ref);
2914       }
2915     }
2916     delete _prev_EMCP_methods;
2917   }
2918 }
2919 
2920 
2921 // Construct a PreviousVersionInfo entry
2922 PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
2923   _prev_constant_pool_handle = constantPoolHandle();  // NULL handle
2924   _prev_EMCP_method_handles = NULL;
2925 
2926   jobject cp_ref = pv_node->prev_constant_pool();
2927   assert(cp_ref != NULL, "constant pool ref was unexpectedly cleared");
2928   if (cp_ref == NULL) {
2929     return;  // robustness
2930   }
2931 
2932   constantPoolOop cp = (constantPoolOop)JNIHandles::resolve(cp_ref);
2933   if (cp == NULL) {
2934     // Weak reference has been GC'ed. Since the constant pool has been
2935     // GC'ed, the methods have also been GC'ed.
2936     return;
2937   }
2938 
2939   // make the constantPoolOop safe to return
2940   _prev_constant_pool_handle = constantPoolHandle(cp);
2941 
2942   GrowableArray<jweak>* method_refs = pv_node->prev_EMCP_methods();
2943   if (method_refs == NULL) {
2944     // the instanceKlass did not have any EMCP methods
2945     return;
2946   }
2947 
2948   _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);
2949 
2950   int n_methods = method_refs->length();
2951   for (int i = 0; i < n_methods; i++) {
2952     jweak method_ref = method_refs->at(i);
2953     assert(method_ref != NULL, "weak method ref was unexpectedly cleared");
2954     if (method_ref == NULL) {
2955       continue;  // robustness
2956     }
2957 
2958     methodOop method = (methodOop)JNIHandles::resolve(method_ref);
2959     if (method == NULL) {
2960       // this entry has been GC'ed so skip it
2961       continue;
2962     }
2963 
2964     // make the methodOop safe to return
2965     _prev_EMCP_method_handles->append(methodHandle(method));
2966   }
2967 }
2968 
2969 
2970 // Destroy a PreviousVersionInfo
2971 PreviousVersionInfo::~PreviousVersionInfo() {
2972   // Since _prev_EMCP_method_handles is not C-heap allocated, we
2973   // don't have to delete it.
2974 }
2975 
2976 
2977 // Construct a helper for walking the previous versions array
2978 PreviousVersionWalker::PreviousVersionWalker(instanceKlass *ik) {
2979   _previous_versions = ik->previous_versions();
2980   _current_index = 0;
2981   // _hm needs no initialization
2982   _current_p = NULL;
2983 }
2984 
2985 
2986 // Destroy a PreviousVersionWalker
2987 PreviousVersionWalker::~PreviousVersionWalker() {
2988   // Delete the current info just in case the caller didn't walk to
2989   // the end of the previous versions list. No harm if _current_p is
2990   // already NULL.
2991   delete _current_p;
2992 
2993   // When _hm is destroyed, all the Handles returned in
2994   // PreviousVersionInfo objects will be destroyed.
2995   // Also, after this destructor is finished it will be
2996   // safe to delete the GrowableArray allocated in the
2997   // PreviousVersionInfo objects.
2998 }
2999 
3000 
3001 // Return the interesting information for the next previous version
3002 // of the klass. Returns NULL if there are no more previous versions.
3003 PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
3004   if (_previous_versions == NULL) {
3005     // no previous versions so nothing to return
3006     return NULL;
3007   }
3008 
3009   delete _current_p;  // cleanup the previous info for the caller
3010   _current_p = NULL;  // reset to NULL so we don't delete same object twice
3011 
3012   int length = _previous_versions->length();
3013 
3014   while (_current_index < length) {
3015     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
3016     PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP)
3017                                           PreviousVersionInfo(pv_node);
3018 
3019     constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
3020     if (cp_h.is_null()) {
3021       delete pv_info;
3022 
3023       // The underlying node's info has been GC'ed so try the next one.
3024       // We don't have to check the methods. If the constant pool has
3025       // GC'ed then so have the methods.
3026       continue;
3027     }
3028 
3029     // Found a node with non GC'ed info so return it. The caller will
3030     // need to delete pv_info when they are done with it.
3031     _current_p = pv_info;
3032     return pv_info;
3033   }
3034 
3035   // all of the underlying nodes' info has been GC'ed
3036   return NULL;
3037 } // end next_previous_version()