1 /*
   2  * Copyright (c) 1997, 2023, 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 "cds/archiveHeapWriter.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveBuilder.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/classPrelinker.hpp"
  31 #include "cds/lambdaFormInvokers.inline.hpp"
  32 #include "cds/heapShared.hpp"
  33 #include "classfile/classLoader.hpp"
  34 #include "classfile/classLoaderData.hpp"
  35 #include "classfile/javaClasses.inline.hpp"
  36 #include "classfile/metadataOnStackMark.hpp"
  37 #include "classfile/stringTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/systemDictionaryShared.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "code/codeCache.hpp"
  43 #include "interpreter/bootstrapInfo.hpp"
  44 #include "interpreter/linkResolver.hpp"
  45 #include "jvm.h"
  46 #include "logging/log.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/metadataFactory.hpp"
  50 #include "memory/metaspaceClosure.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/array.hpp"
  55 #include "oops/constantPool.inline.hpp"
  56 #include "oops/cpCache.inline.hpp"
  57 #include "oops/instanceKlass.hpp"
  58 #include "oops/klass.inline.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.inline.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "oops/typeArrayOop.inline.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "runtime/atomic.hpp"
  65 //#include "runtime/fieldDescriptor.inline.hpp"
  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/init.hpp"
  68 #include "runtime/javaCalls.hpp"
  69 #include "runtime/javaThread.inline.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/signature.hpp"
  72 #include "runtime/vframe.inline.hpp"
  73 #include "utilities/checkedCast.hpp"
  74 #include "utilities/copy.hpp"
  75 
  76 ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
  77   Array<u1>* tags = MetadataFactory::new_array<u1>(loader_data, length, 0, CHECK_NULL);
  78   int size = ConstantPool::size(length);
  79   return new (loader_data, size, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);
  80 }
  81 
  82 void ConstantPool::copy_fields(const ConstantPool* orig) {
  83   // Preserve dynamic constant information from the original pool
  84   if (orig->has_dynamic_constant()) {
  85     set_has_dynamic_constant();
  86   }
  87 
  88   set_major_version(orig->major_version());
  89   set_minor_version(orig->minor_version());
  90 
  91   set_source_file_name_index(orig->source_file_name_index());
  92   set_generic_signature_index(orig->generic_signature_index());
  93 }
  94 
  95 #ifdef ASSERT
  96 
  97 // MetaspaceObj allocation invariant is calloc equivalent memory
  98 // simple verification of this here (JVM_CONSTANT_Invalid == 0 )
  99 static bool tag_array_is_zero_initialized(Array<u1>* tags) {
 100   assert(tags != nullptr, "invariant");
 101   const int length = tags->length();
 102   for (int index = 0; index < length; ++index) {
 103     if (JVM_CONSTANT_Invalid != tags->at(index)) {
 104       return false;
 105     }
 106   }
 107   return true;
 108 }
 109 
 110 #endif
 111 
 112 ConstantPool::ConstantPool() {
 113   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 114 }
 115 
 116 ConstantPool::ConstantPool(Array<u1>* tags) :
 117   _tags(tags),
 118   _length(tags->length()) {
 119 
 120     assert(_tags != nullptr, "invariant");
 121     assert(tags->length() == _length, "invariant");
 122     assert(tag_array_is_zero_initialized(tags), "invariant");
 123     assert(0 == flags(), "invariant");
 124     assert(0 == version(), "invariant");
 125     assert(nullptr == _pool_holder, "invariant");
 126 }
 127 
 128 void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
 129   if (cache() != nullptr) {
 130     MetadataFactory::free_metadata(loader_data, cache());
 131     set_cache(nullptr);
 132   }
 133 
 134   MetadataFactory::free_array<Klass*>(loader_data, resolved_klasses());
 135   set_resolved_klasses(nullptr);
 136 
 137   MetadataFactory::free_array<jushort>(loader_data, operands());
 138   set_operands(nullptr);
 139 
 140   release_C_heap_structures();
 141 
 142   // free tag array
 143   MetadataFactory::free_array<u1>(loader_data, tags());
 144   set_tags(nullptr);
 145 }
 146 
 147 void ConstantPool::release_C_heap_structures() {
 148   // walk constant pool and decrement symbol reference counts
 149   unreference_symbols();
 150 }
 151 
 152 void ConstantPool::metaspace_pointers_do(MetaspaceClosure* it) {
 153   log_trace(cds)("Iter(ConstantPool): %p", this);
 154 
 155   it->push(&_tags, MetaspaceClosure::_writable);
 156   it->push(&_cache);
 157   it->push(&_pool_holder);
 158   it->push(&_operands);
 159   it->push(&_resolved_klasses, MetaspaceClosure::_writable);
 160 
 161   for (int i = 0; i < length(); i++) {
 162     // The only MSO's embedded in the CP entries are Symbols:
 163     //   JVM_CONSTANT_String
 164     //   JVM_CONSTANT_Utf8
 165     constantTag ctag = tag_at(i);
 166     if (ctag.is_string() || ctag.is_utf8()) {
 167       it->push(symbol_at_addr(i));
 168     }
 169   }
 170 }
 171 
 172 objArrayOop ConstantPool::resolved_references() const {
 173   return _cache->resolved_references();
 174 }
 175 
 176 // Called from outside constant pool resolution where a resolved_reference array
 177 // may not be present.
 178 objArrayOop ConstantPool::resolved_references_or_null() const {
 179   if (_cache == nullptr) {
 180     return nullptr;
 181   } else {
 182     return _cache->resolved_references();
 183   }
 184 }
 185 
 186 oop ConstantPool::resolved_reference_at(int index) const {
 187   oop result = resolved_references()->obj_at(index);
 188   assert(oopDesc::is_oop_or_null(result), "Must be oop");
 189   return result;
 190 }
 191 
 192 // Use a CAS for multithreaded access
 193 oop ConstantPool::set_resolved_reference_at(int index, oop new_result) {
 194   assert(oopDesc::is_oop_or_null(new_result), "Must be oop");
 195   return resolved_references()->replace_if_null(index, new_result);
 196 }
 197 
 198 // Create resolved_references array and mapping array for original cp indexes
 199 // The ldc bytecode was rewritten to have the resolved reference array index so need a way
 200 // to map it back for resolving and some unlikely miscellaneous uses.
 201 // The objects created by invokedynamic are appended to this list.
 202 void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
 203                                                   const intStack& reference_map,
 204                                                   int constant_pool_map_length,
 205                                                   TRAPS) {
 206   // Initialized the resolved object cache.
 207   int map_length = reference_map.length();
 208   if (map_length > 0) {
 209     // Only need mapping back to constant pool entries.  The map isn't used for
 210     // invokedynamic resolved_reference entries.  For invokedynamic entries,
 211     // the constant pool cache index has the mapping back to both the constant
 212     // pool and to the resolved reference index.
 213     if (constant_pool_map_length > 0) {
 214       Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);
 215 
 216       for (int i = 0; i < constant_pool_map_length; i++) {
 217         int x = reference_map.at(i);
 218         assert(x == (int)(jushort) x, "klass index is too big");
 219         om->at_put(i, (jushort)x);
 220       }
 221       set_reference_map(om);
 222     }
 223 
 224     // Create Java array for holding resolved strings, methodHandles,
 225     // methodTypes, invokedynamic and invokehandle appendix objects, etc.
 226     objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 227     HandleMark hm(THREAD);
 228     Handle refs_handle (THREAD, stom);  // must handleize.
 229     set_resolved_references(loader_data->add_handle(refs_handle));
 230 
 231     // Create a "scratch" copy of the resolved references array to archive
 232     if (CDSConfig::is_dumping_heap()) {
 233       objArrayOop scratch_references = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 234       HeapShared::add_scratch_resolved_references(this, scratch_references);
 235     }
 236   }
 237 }
 238 
 239 void ConstantPool::allocate_resolved_klasses(ClassLoaderData* loader_data, int num_klasses, TRAPS) {
 240   // A ConstantPool can't possibly have 0xffff valid class entries,
 241   // because entry #0 must be CONSTANT_Invalid, and each class entry must refer to a UTF8
 242   // entry for the class's name. So at most we will have 0xfffe class entries.
 243   // This allows us to use 0xffff (ConstantPool::_temp_resolved_klass_index) to indicate
 244   // UnresolvedKlass entries that are temporarily created during class redefinition.
 245   assert(num_klasses < CPKlassSlot::_temp_resolved_klass_index, "sanity");
 246   assert(resolved_klasses() == nullptr, "sanity");
 247   Array<Klass*>* rk = MetadataFactory::new_array<Klass*>(loader_data, num_klasses, CHECK);
 248   set_resolved_klasses(rk);
 249 }
 250 
 251 void ConstantPool::initialize_unresolved_klasses(ClassLoaderData* loader_data, TRAPS) {
 252   int len = length();
 253   int num_klasses = 0;
 254   for (int i = 1; i <len; i++) {
 255     switch (tag_at(i).value()) {
 256     case JVM_CONSTANT_ClassIndex:
 257       {
 258         const int class_index = klass_index_at(i);
 259         unresolved_klass_at_put(i, class_index, num_klasses++);
 260       }
 261       break;
 262 #ifndef PRODUCT
 263     case JVM_CONSTANT_Class:
 264     case JVM_CONSTANT_UnresolvedClass:
 265     case JVM_CONSTANT_UnresolvedClassInError:
 266       // All of these should have been reverted back to ClassIndex before calling
 267       // this function.
 268       ShouldNotReachHere();
 269 #endif
 270     }
 271   }
 272   allocate_resolved_klasses(loader_data, num_klasses, THREAD);
 273 }
 274 
 275 // Hidden class support:
 276 void ConstantPool::klass_at_put(int class_index, Klass* k) {
 277   assert(k != nullptr, "must be valid klass");
 278   CPKlassSlot kslot = klass_slot_at(class_index);
 279   int resolved_klass_index = kslot.resolved_klass_index();
 280   Klass** adr = resolved_klasses()->adr_at(resolved_klass_index);
 281   Atomic::release_store(adr, k);
 282 
 283   // The interpreter assumes when the tag is stored, the klass is resolved
 284   // and the Klass* non-null, so we need hardware store ordering here.
 285   release_tag_at_put(class_index, JVM_CONSTANT_Class);
 286 }
 287 
 288 #if INCLUDE_CDS_JAVA_HEAP
 289 // Returns the _resolved_reference array after removing unarchivable items from it.
 290 // Returns null if this class is not supported, or _resolved_reference doesn't exist.
 291 objArrayOop ConstantPool::prepare_resolved_references_for_archiving() {
 292   if (_cache == nullptr) {
 293     return nullptr; // nothing to do
 294   }
 295 
 296   InstanceKlass *ik = pool_holder();
 297   if (!(ik->is_shared_boot_class() || ik->is_shared_platform_class() ||
 298         ik->is_shared_app_class())) {
 299     // Archiving resolved references for classes from non-builtin loaders
 300     // is not yet supported.
 301     return nullptr;
 302   }
 303 
 304   objArrayOop rr = resolved_references();
 305   if (rr != nullptr) {
 306     ResourceMark rm;
 307     int rr_len = rr->length();
 308     GrowableArray<bool> keep_resolved_refs(rr_len, rr_len, false);
 309     ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 310 
 311     if (cache() != nullptr && ArchiveInvokeDynamic) {
 312       Array<ResolvedIndyEntry>* indy_entries = cache()->resolved_indy_entries();
 313       if (indy_entries != nullptr) {
 314         for (int i = 0; i < indy_entries->length(); i++) {
 315           ResolvedIndyEntry *rie = indy_entries->adr_at(i);
 316           if (rie->is_resolved() && ClassPrelinker::is_resolution_deterministic(src_cp, rie->constant_pool_index())) {
 317             int rr_index = rie->resolved_references_index();
 318             keep_resolved_refs.at_put(rr_index, true);
 319           }
 320         }
 321       }
 322 
 323       Array<ResolvedMethodEntry>* method_entries = cache()->resolved_method_entries();
 324       if (method_entries != nullptr) {
 325         for (int i = 0; i < method_entries->length(); i++) {
 326           ResolvedMethodEntry* rme = method_entries->adr_at(i);
 327           if (rme->is_resolved(Bytecodes::_invokehandle) && rme->has_appendix() &&
 328               can_archive_resolved_method(rme)) {
 329             int rr_index = rme->resolved_references_index();
 330             keep_resolved_refs.at_put(rr_index, true);
 331           }
 332         }
 333       }
 334     }
 335 
 336     objArrayOop scratch_rr = HeapShared::scratch_resolved_references(src_cp);
 337     Array<u2>* ref_map = reference_map();
 338     int ref_map_len = ref_map == nullptr ? 0 : ref_map->length();
 339     for (int i = 0; i < rr_len; i++) {
 340       oop obj = rr->obj_at(i);
 341       scratch_rr->obj_at_put(i, nullptr);
 342       if (obj != nullptr) {
 343         if (i < ref_map_len) {
 344           int index = object_to_cp_index(i);
 345           if (tag_at(index).is_string()) {
 346             assert(java_lang_String::is_instance(obj), "must be");
 347             if (!ArchiveHeapWriter::is_string_too_large_to_archive(obj)) {
 348               scratch_rr->obj_at_put(i, obj);
 349             }
 350           }
 351         } else if (keep_resolved_refs.at(i)) {
 352           scratch_rr->obj_at_put(i, obj);
 353         }
 354       }
 355     }
 356     return scratch_rr;
 357   }
 358   return rr;
 359 }
 360 
 361 void ConstantPool::add_dumped_interned_strings() {
 362   objArrayOop rr = resolved_references();
 363   if (rr != nullptr) {
 364     int rr_len = rr->length();
 365     for (int i = 0; i < rr_len; i++) {
 366       oop p = rr->obj_at(i);
 367       if (java_lang_String::is_instance(p) &&
 368           !ArchiveHeapWriter::is_string_too_large_to_archive(p)) {
 369         HeapShared::add_to_dumped_interned_strings(p);
 370       }
 371     }
 372   }
 373 }
 374 #endif
 375 
 376 #if INCLUDE_CDS
 377 // CDS support. Create a new resolved_references array.
 378 void ConstantPool::restore_unshareable_info(TRAPS) {
 379   if (!_pool_holder->is_linked() && !_pool_holder->is_rewritten()) {
 380     return;
 381   }
 382   assert(is_constantPool(), "ensure C++ vtable is restored");
 383   assert(on_stack(), "should always be set for shared constant pools");
 384   assert(is_shared(), "should always be set for shared constant pools");
 385   if (is_for_method_handle_intrinsic()) {
 386     return;
 387   }
 388   assert(_cache != nullptr, "constant pool _cache should not be null");
 389 
 390   // Only create the new resolved references array if it hasn't been attempted before
 391   if (resolved_references() != nullptr) return;
 392 
 393   if (vmClasses::Object_klass_loaded()) {
 394     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
 395 #if INCLUDE_CDS_JAVA_HEAP
 396     if (ArchiveHeapLoader::is_in_use() &&
 397         _cache->archived_references() != nullptr) {
 398       oop archived = _cache->archived_references();
 399       // Create handle for the archived resolved reference array object
 400       HandleMark hm(THREAD);
 401       Handle refs_handle(THREAD, archived);
 402       set_resolved_references(loader_data->add_handle(refs_handle));
 403       _cache->clear_archived_references();
 404     } else
 405 #endif
 406     {
 407       // No mapped archived resolved reference array
 408       // Recreate the object array and add to ClassLoaderData.
 409       int map_length = resolved_reference_length();
 410       if (map_length > 0) {
 411         objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 412         HandleMark hm(THREAD);
 413         Handle refs_handle(THREAD, stom);  // must handleize.
 414         set_resolved_references(loader_data->add_handle(refs_handle));
 415       }
 416     }
 417   }
 418 
 419   if (CDSConfig::is_dumping_final_static_archive() && resolved_references() != nullptr) {
 420     objArrayOop scratch_references = oopFactory::new_objArray(vmClasses::Object_klass(), resolved_references()->length(), CHECK);
 421     HeapShared::add_scratch_resolved_references(this, scratch_references);
 422   }
 423 }
 424 
 425 void ConstantPool::remove_unshareable_info() {
 426   // Shared ConstantPools are in the RO region, so the _flags cannot be modified.
 427   // The _on_stack flag is used to prevent ConstantPools from deallocation during
 428   // class redefinition. Since shared ConstantPools cannot be deallocated anyway,
 429   // we always set _on_stack to true to avoid having to change _flags during runtime.
 430   _flags |= (_on_stack | _is_shared);
 431 
 432   if (!ArchiveBuilder::current()->get_source_addr(_pool_holder)->is_linked()) {
 433     return;
 434   }
 435 
 436   if (is_for_method_handle_intrinsic()) {
 437     // This CP was created by Method::make_method_handle_intrinsic() and has nothing
 438     // that need to be removed/restored. It has no cpCache since the intrinsic methods
 439     // don't have any bytecodes.
 440     assert(cache() == NULL, "must not have cpCache");
 441     return;
 442   }
 443 
 444   // Resolved references are not in the shared archive.
 445   // Save the length for restoration.  It is not necessarily the same length
 446   // as reference_map.length() if invokedynamic is saved. It is needed when
 447   // re-creating the resolved reference array if archived heap data cannot be map
 448   // at runtime.
 449   set_resolved_reference_length(
 450     resolved_references() != nullptr ? resolved_references()->length() : 0);
 451   set_resolved_references(OopHandle());
 452 
 453   remove_unshareable_entries();
 454 }
 455 
 456 static const char* get_type(Klass* k) {
 457   const char* type;
 458   Klass* src_k;
 459   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(k)) {
 460     src_k = ArchiveBuilder::current()->get_source_addr(k);
 461   } else {
 462     src_k = k;
 463   }
 464 
 465   if (src_k->is_objArray_klass()) {
 466     src_k = ObjArrayKlass::cast(src_k)->bottom_klass();
 467     assert(!src_k->is_objArray_klass(), "sanity");
 468   }
 469 
 470   if (src_k->is_typeArray_klass()) {
 471     type = "prim";
 472   } else {
 473     InstanceKlass* src_ik = InstanceKlass::cast(src_k);
 474     oop loader = src_ik->class_loader();
 475     if (loader == nullptr) {
 476       type = "boot";
 477     } else if (loader == SystemDictionary::java_platform_loader()) {
 478       type = "plat";
 479     } else if (loader == SystemDictionary::java_system_loader()) {
 480       type = "app";
 481     } else {
 482       type = "unreg";
 483     }
 484   }
 485 
 486   return type;
 487 }
 488 
 489 void ConstantPool::remove_unshareable_entries() {
 490   ResourceMark rm;
 491   log_info(cds, resolve)("Archiving CP entries for %s", pool_holder()->name()->as_C_string());
 492   for (int cp_index = 1; cp_index < length(); cp_index++) { // cp_index 0 is unused
 493     int cp_tag = tag_at(cp_index).value();
 494     switch (cp_tag) {
 495     case JVM_CONSTANT_UnresolvedClass:
 496       ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false);
 497       break;
 498     case JVM_CONSTANT_UnresolvedClassInError:
 499       tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
 500       ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false);
 501       break;
 502     case JVM_CONSTANT_MethodHandleInError:
 503       tag_at_put(cp_index, JVM_CONSTANT_MethodHandle);
 504       break;
 505     case JVM_CONSTANT_MethodTypeInError:
 506       tag_at_put(cp_index, JVM_CONSTANT_MethodType);
 507       break;
 508     case JVM_CONSTANT_DynamicInError:
 509       tag_at_put(cp_index, JVM_CONSTANT_Dynamic);
 510       break;
 511     case JVM_CONSTANT_Class:
 512       remove_resolved_klass_if_non_deterministic(cp_index);
 513       break;
 514     default:
 515       break;
 516     }
 517   }
 518 
 519   if (cache() != nullptr) {
 520     // cache() is null if this class is not yet linked.
 521     remove_resolved_field_entries_if_non_deterministic();
 522     remove_resolved_method_entries_if_non_deterministic();
 523     remove_resolved_indy_entries_if_non_deterministic();
 524   }
 525 }
 526 
 527 void ConstantPool::remove_resolved_klass_if_non_deterministic(int cp_index) {
 528   assert(ArchiveBuilder::current()->is_in_buffer_space(this), "must be");
 529   assert(tag_at(cp_index).is_klass(), "must be resolved");
 530 
 531   // k could be null if the referenced class has been excluded via
 532   // SystemDictionaryShared::is_excluded_class().
 533   Klass* k = resolved_klass_at(cp_index);
 534   bool revert = true;
 535   if (k != nullptr) {
 536     ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 537     if (ClassPrelinker::is_resolution_deterministic(src_cp, cp_index)) {
 538       revert = false;
 539     }
 540   }
 541 
 542   if (revert) {
 543     // This resolved klass entry cannot be archived. Revert the tag to UnresolvedClass,
 544     // so that it will be resolved at runtime.
 545     int resolved_klass_index = klass_slot_at(cp_index).resolved_klass_index();
 546     resolved_klasses()->at_put(resolved_klass_index, nullptr);
 547     tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
 548   }
 549 
 550   LogStreamHandle(Trace, cds, resolve) log;
 551   if (log.is_enabled()) {
 552     ResourceMark rm;
 553     log.print("%s klass  CP entry [%3d]: %s %s",
 554               (revert ? "reverted" : "archived"),
 555               cp_index, pool_holder()->name()->as_C_string(), get_type(pool_holder()));
 556     if (revert) {
 557       Symbol* name = klass_name_at(cp_index);
 558       log.print("  \"%s\"", name->as_C_string());
 559     } else {
 560       log.print(" => %s %s%s", k->name()->as_C_string(), get_type(k),
 561                 (!k->is_instance_klass() || pool_holder()->is_subtype_of(k)) ? "" : " (not supertype)");
 562     }
 563   }
 564   ArchiveBuilder::alloc_stats()->record_klass_cp_entry(!revert);
 565 }
 566 
 567 void ConstantPool::remove_resolved_field_entries_if_non_deterministic() {
 568   ConstantPool* src_cp =  ArchiveBuilder::current()->get_source_addr(this);
 569   Array<ResolvedFieldEntry>* field_entries = cache()->resolved_field_entries();
 570   if (field_entries != nullptr) {
 571     for (int i = 0; i < field_entries->length(); i++) {
 572       ResolvedFieldEntry* rfi = field_entries->adr_at(i);
 573       int cp_index = rfi->constant_pool_index();
 574       bool archived = false;
 575       bool resolved = rfi->is_resolved(Bytecodes::_getstatic) ||
 576                       rfi->is_resolved(Bytecodes::_putstatic) ||
 577                       rfi->is_resolved(Bytecodes::_putfield)  ||
 578                       rfi->is_resolved(Bytecodes::_putfield);
 579       if (resolved && ClassPrelinker::is_resolution_deterministic(src_cp, cp_index)) {
 580         rfi->mark_and_relocate();
 581         archived = true;
 582       } else {
 583         rfi->remove_unshareable_info();
 584       }
 585       if (resolved) {
 586         LogStreamHandle(Trace, cds, resolve) log;
 587         if (log.is_enabled()) {
 588           ResourceMark rm;
 589           int klass_cp_index = uncached_klass_ref_index_at(cp_index);
 590           Symbol* klass_name = klass_name_at(klass_cp_index);
 591           Symbol* name = uncached_name_ref_at(cp_index);
 592           Symbol* signature = uncached_signature_ref_at(cp_index);
 593           log.print("%s field  CP entry [%3d]: %s %s %s.%s:%s",
 594                     (archived ? "archived" : "excluded"),
 595                     cp_index,
 596                     pool_holder()->name()->as_C_string(),
 597                     (archived ? "=>" : "  "),
 598                     klass_name->as_C_string(), name->as_C_string(), signature->as_C_string());
 599         }
 600       }
 601       ArchiveBuilder::alloc_stats()->record_field_cp_entry(archived, resolved && !archived);
 602     }
 603   }
 604 }
 605 
 606 void ConstantPool::remove_resolved_method_entries_if_non_deterministic() {
 607   ConstantPool* src_cp =  ArchiveBuilder::current()->get_source_addr(this);
 608   Array<ResolvedMethodEntry>* method_entries = cache()->resolved_method_entries();
 609   if (method_entries != nullptr) {
 610     for (int i = 0; i < method_entries->length(); i++) {
 611       ResolvedMethodEntry* rme = method_entries->adr_at(i);
 612       int cp_index = rme->constant_pool_index();
 613       bool archived = false;
 614       bool resolved = rme->is_resolved(Bytecodes::_invokevirtual)   ||
 615                       rme->is_resolved(Bytecodes::_invokespecial)   ||
 616                       rme->is_resolved(Bytecodes::_invokestatic)    ||
 617                       rme->is_resolved(Bytecodes::_invokeinterface) ||
 618                       rme->is_resolved(Bytecodes::_invokehandle);
 619       if (resolved && can_archive_resolved_method(rme)) {
 620         rme->mark_and_relocate(src_cp);
 621         archived = true;
 622       } else {
 623         rme->remove_unshareable_info();
 624       }
 625       if (resolved) {
 626         LogStreamHandle(Trace, cds, resolve) log;
 627         if (log.is_enabled()) {
 628           ResourceMark rm;
 629           int klass_cp_index = uncached_klass_ref_index_at(cp_index);
 630           Symbol* klass_name = klass_name_at(klass_cp_index);
 631           Symbol* name = uncached_name_ref_at(cp_index);
 632           Symbol* signature = uncached_signature_ref_at(cp_index);
 633           log.print("%s%s method CP entry [%3d]: %s %s.%s:%s",
 634                     (archived ? "archived" : "excluded"),
 635                     (rme->is_resolved(Bytecodes::_invokeinterface) ? " interface" : ""),
 636                     cp_index,
 637                     pool_holder()->name()->as_C_string(),
 638                     klass_name->as_C_string(), name->as_C_string(), signature->as_C_string());
 639           if (archived) {
 640             Klass* resolved_klass = resolved_klass_at(klass_cp_index);
 641             log.print(" => %s%s",
 642                       resolved_klass->name()->as_C_string(),
 643                       (rme->is_resolved(Bytecodes::_invokestatic) ? " *** static" : ""));
 644           }
 645         }
 646       }
 647       ArchiveBuilder::alloc_stats()->record_method_cp_entry(archived, resolved && !archived);
 648     }
 649   }
 650 }
 651 
 652 void ConstantPool::remove_resolved_indy_entries_if_non_deterministic() {
 653   ConstantPool* src_cp =  ArchiveBuilder::current()->get_source_addr(this);
 654   Array<ResolvedIndyEntry>* indy_entries = cache()->resolved_indy_entries();
 655   if (indy_entries != nullptr) {
 656     for (int i = 0; i < indy_entries->length(); i++) {
 657       ResolvedIndyEntry* rei = indy_entries->adr_at(i);
 658       int cp_index = rei->constant_pool_index();
 659       bool archived = false;
 660       bool resolved = rei->is_resolved();
 661       if (resolved && ClassPrelinker::is_resolution_deterministic(src_cp, cp_index)) {
 662         rei->mark_and_relocate();
 663         archived = true;
 664       } else {
 665         rei->remove_unshareable_info();
 666       }
 667       if (resolved) {
 668         LogStreamHandle(Trace, cds, resolve) log;
 669         if (log.is_enabled()) {
 670           ResourceMark rm;
 671           int bsm = bootstrap_method_ref_index_at(cp_index);
 672           int bsm_ref = method_handle_index_at(bsm);
 673           Symbol* bsm_name = uncached_name_ref_at(bsm_ref);
 674           Symbol* bsm_signature = uncached_signature_ref_at(bsm_ref);
 675           Symbol* bsm_klass = klass_name_at(uncached_klass_ref_index_at(bsm_ref));
 676           log.print("%s indy   CP entry [%3d]: %s (%d)",
 677                     (archived ? "archived" : "excluded"),
 678                     cp_index, pool_holder()->name()->as_C_string(), i);
 679           log.print(" %s %s.%s:%s", (archived ? "=>" : "  "), bsm_klass->as_C_string(), bsm_name->as_C_string(), bsm_signature->as_C_string());
 680         }
 681       }
 682       ArchiveBuilder::alloc_stats()->record_indy_cp_entry(archived, resolved && !archived);
 683     }
 684   }
 685 }
 686 
 687 bool ConstantPool::can_archive_invokehandle(ResolvedMethodEntry* rme) {
 688   assert(rme->is_resolved(Bytecodes::_invokehandle), "sanity");
 689 
 690   int cp_index = rme->constant_pool_index();
 691   int klass_cp_index = uncached_klass_ref_index_at(cp_index);
 692   Klass* resolved_klass = resolved_klass_at(klass_cp_index);
 693   if (!resolved_klass->is_instance_klass()) {
 694     // FIXME: can this ever happen?
 695     return false;
 696   }
 697   // FIXME -- any class referenced by the archived CP entries should be added to ArchiveBuilder::classes, or should be
 698   // filtered out.
 699   return true;
 700 }
 701 
 702 bool ConstantPool::can_archive_resolved_method(ResolvedMethodEntry* method_entry) {
 703   if (!(pool_holder()->is_shared_boot_class() || pool_holder()->is_shared_platform_class() ||
 704         pool_holder()->is_shared_app_class())) {
 705     // Archiving resolved cp entries for classes from non-builtin loaders
 706     // is not yet supported.
 707     return false;
 708   }
 709 
 710   if (CDSConfig::is_dumping_dynamic_archive()) {
 711     // InstanceKlass::methods() is has been resorted. We need to
 712     // update the vtable_index in method_entry (not implemented)
 713     return false;
 714   }
 715 
 716   if (!method_entry->is_resolved(Bytecodes::_invokevirtual)) {
 717     if (method_entry->method() == nullptr) {
 718       return false;
 719     }
 720     if (method_entry->method()->is_continuation_native_intrinsic()) {
 721       return false; // FIXME: corresponding stub is generated on demand during method resolution (see LinkResolver::resolve_static_call).
 722     }
 723   }
 724 
 725   int cp_index = method_entry->constant_pool_index();
 726   ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 727   assert(src_cp->tag_at(cp_index).is_method() || src_cp->tag_at(cp_index).is_interface_method(), "sanity");
 728 
 729   if (!ClassPrelinker::is_resolution_deterministic(src_cp, cp_index)) {
 730     return false;
 731   }
 732 
 733   if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
 734     if (!ArchiveInvokeDynamic) {
 735       // invokehandle depends on archived MethodType and LambdaForms.
 736       return false;
 737     } else if (!can_archive_invokehandle(method_entry)) {
 738       return false;
 739     }
 740   } else if (method_entry->is_resolved(Bytecodes::_invokestatic) ||
 741              method_entry->is_resolved(Bytecodes::_invokeinterface) ||
 742              method_entry->is_resolved(Bytecodes::_invokevirtual) ||
 743              method_entry->is_resolved(Bytecodes::_invokespecial)) {
 744     // OK
 745   } else {
 746     return false; // just to be safe.
 747   }
 748 
 749   return true;
 750 }
 751 #endif // INCLUDE_CDS
 752 
 753 int ConstantPool::cp_to_object_index(int cp_index) {
 754   // this is harder don't do this so much.
 755   int i = reference_map()->find(checked_cast<u2>(cp_index));
 756   // We might not find the index for jsr292 call.
 757   return (i < 0) ? _no_index_sentinel : i;
 758 }
 759 
 760 void ConstantPool::string_at_put(int obj_index, oop str) {
 761   oop result = set_resolved_reference_at(obj_index, str);
 762   assert(result == nullptr || result == str, "Only set once or to the same string.");
 763 }
 764 
 765 void ConstantPool::trace_class_resolution(const constantPoolHandle& this_cp, Klass* k) {
 766   ResourceMark rm;
 767   int line_number = -1;
 768   const char * source_file = nullptr;
 769   if (JavaThread::current()->has_last_Java_frame()) {
 770     // try to identify the method which called this function.
 771     vframeStream vfst(JavaThread::current());
 772     if (!vfst.at_end()) {
 773       line_number = vfst.method()->line_number_from_bci(vfst.bci());
 774       Symbol* s = vfst.method()->method_holder()->source_file_name();
 775       if (s != nullptr) {
 776         source_file = s->as_C_string();
 777       }
 778     }
 779   }
 780   if (k != this_cp->pool_holder()) {
 781     // only print something if the classes are different
 782     if (source_file != nullptr) {
 783       log_debug(class, resolve)("%s %s %s:%d",
 784                  this_cp->pool_holder()->external_name(),
 785                  k->external_name(), source_file, line_number);
 786     } else {
 787       log_debug(class, resolve)("%s %s",
 788                  this_cp->pool_holder()->external_name(),
 789                  k->external_name());
 790     }
 791   }
 792 }
 793 
 794 Klass* ConstantPool::klass_at_impl(const constantPoolHandle& this_cp, int cp_index,
 795                                    TRAPS) {
 796   JavaThread* javaThread = THREAD;
 797 
 798   // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
 799   // It is not safe to rely on the tag bit's here, since we don't have a lock, and
 800   // the entry and tag is not updated atomically.
 801   CPKlassSlot kslot = this_cp->klass_slot_at(cp_index);
 802   int resolved_klass_index = kslot.resolved_klass_index();
 803   int name_index = kslot.name_index();
 804   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 805 
 806   // The tag must be JVM_CONSTANT_Class in order to read the correct value from
 807   // the unresolved_klasses() array.
 808   if (this_cp->tag_at(cp_index).is_klass()) {
 809     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 810     if (klass != nullptr) {
 811       return klass;
 812     }
 813   }
 814 
 815   // This tag doesn't change back to unresolved class unless at a safepoint.
 816   if (this_cp->tag_at(cp_index).is_unresolved_klass_in_error()) {
 817     // The original attempt to resolve this constant pool entry failed so find the
 818     // class of the original error and throw another error of the same class
 819     // (JVMS 5.4.3).
 820     // If there is a detail message, pass that detail message to the error.
 821     // The JVMS does not strictly require us to duplicate the same detail message,
 822     // or any internal exception fields such as cause or stacktrace.  But since the
 823     // detail message is often a class name or other literal string, we will repeat it
 824     // if we can find it in the symbol table.
 825     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
 826     ShouldNotReachHere();
 827   }
 828 
 829   HandleMark hm(THREAD);
 830   Handle mirror_handle;
 831   Symbol* name = this_cp->symbol_at(name_index);
 832   Handle loader (THREAD, this_cp->pool_holder()->class_loader());
 833   Handle protection_domain (THREAD, this_cp->pool_holder()->protection_domain());
 834 
 835   Klass* k;
 836   {
 837     // Turn off the single stepping while doing class resolution
 838     JvmtiHideSingleStepping jhss(javaThread);
 839     k = SystemDictionary::resolve_or_fail(name, loader, protection_domain, true, THREAD);
 840   } //  JvmtiHideSingleStepping jhss(javaThread);
 841 
 842   if (!HAS_PENDING_EXCEPTION) {
 843     // preserve the resolved klass from unloading
 844     mirror_handle = Handle(THREAD, k->java_mirror());
 845     // Do access check for klasses
 846     verify_constant_pool_resolve(this_cp, k, THREAD);
 847   }
 848 
 849   // Failed to resolve class. We must record the errors so that subsequent attempts
 850   // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
 851   if (HAS_PENDING_EXCEPTION) {
 852     save_and_throw_exception(this_cp, cp_index, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_NULL);
 853     // If CHECK_NULL above doesn't return the exception, that means that
 854     // some other thread has beaten us and has resolved the class.
 855     // To preserve old behavior, we return the resolved class.
 856     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 857     assert(klass != nullptr, "must be resolved if exception was cleared");
 858     return klass;
 859   }
 860 
 861   // logging for class+resolve.
 862   if (log_is_enabled(Debug, class, resolve)){
 863     trace_class_resolution(this_cp, k);
 864   }
 865 
 866   Klass** adr = this_cp->resolved_klasses()->adr_at(resolved_klass_index);
 867   Atomic::release_store(adr, k);
 868   // The interpreter assumes when the tag is stored, the klass is resolved
 869   // and the Klass* stored in _resolved_klasses is non-null, so we need
 870   // hardware store ordering here.
 871   // We also need to CAS to not overwrite an error from a racing thread.
 872 
 873   jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
 874                                   (jbyte)JVM_CONSTANT_UnresolvedClass,
 875                                   (jbyte)JVM_CONSTANT_Class);
 876 
 877   // We need to recheck exceptions from racing thread and return the same.
 878   if (old_tag == JVM_CONSTANT_UnresolvedClassInError) {
 879     // Remove klass.
 880     this_cp->resolved_klasses()->at_put(resolved_klass_index, nullptr);
 881     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
 882   }
 883 
 884   return k;
 885 }
 886 
 887 
 888 // Does not update ConstantPool* - to avoid any exception throwing. Used
 889 // by compiler and exception handling.  Also used to avoid classloads for
 890 // instanceof operations. Returns null if the class has not been loaded or
 891 // if the verification of constant pool failed
 892 Klass* ConstantPool::klass_at_if_loaded(const constantPoolHandle& this_cp, int which) {
 893   CPKlassSlot kslot = this_cp->klass_slot_at(which);
 894   int resolved_klass_index = kslot.resolved_klass_index();
 895   int name_index = kslot.name_index();
 896   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 897 
 898   if (this_cp->tag_at(which).is_klass()) {
 899     Klass* k = this_cp->resolved_klasses()->at(resolved_klass_index);
 900     assert(k != nullptr, "should be resolved");
 901     return k;
 902   } else if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
 903     return nullptr;
 904   } else {
 905     Thread* current = Thread::current();
 906     HandleMark hm(current);
 907     Symbol* name = this_cp->symbol_at(name_index);
 908     oop loader = this_cp->pool_holder()->class_loader();
 909     oop protection_domain = this_cp->pool_holder()->protection_domain();
 910     Handle h_prot (current, protection_domain);
 911     Handle h_loader (current, loader);
 912     Klass* k = SystemDictionary::find_instance_klass(current, name, h_loader, h_prot);
 913 
 914     // Avoid constant pool verification at a safepoint, as it takes the Module_lock.
 915     if (k != nullptr && current->is_Java_thread()) {
 916       // Make sure that resolving is legal
 917       JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 918       ExceptionMark em(THREAD);
 919       // return null if verification fails
 920       verify_constant_pool_resolve(this_cp, k, THREAD);
 921       if (HAS_PENDING_EXCEPTION) {
 922         CLEAR_PENDING_EXCEPTION;
 923         return nullptr;
 924       }
 925       return k;
 926     } else {
 927       return k;
 928     }
 929   }
 930 }
 931 
 932 Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,
 933                                                    int which) {
 934   if (cpool->cache() == nullptr)  return nullptr;  // nothing to load yet
 935   if (!(which >= 0 && which < cpool->resolved_method_entries_length())) {
 936     // FIXME: should be an assert
 937     log_debug(class, resolve)("bad operand %d in:", which); cpool->print();
 938     return nullptr;
 939   }
 940   return cpool->cache()->method_if_resolved(which);
 941 }
 942 
 943 
 944 bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 945   if (cpool->cache() == nullptr)  return false;  // nothing to load yet
 946   if (code == Bytecodes::_invokedynamic) {
 947     return cpool->resolved_indy_entry_at(which)->has_appendix();
 948   } else {
 949     return cpool->resolved_method_entry_at(which)->has_appendix();
 950   }
 951 }
 952 
 953 oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 954   if (cpool->cache() == nullptr)  return nullptr;  // nothing to load yet
 955   if (code == Bytecodes::_invokedynamic) {
 956     return cpool->resolved_reference_from_indy(which);
 957   } else {
 958     return cpool->cache()->appendix_if_resolved(which);
 959   }
 960 }
 961 
 962 
 963 bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 964   if (cpool->cache() == nullptr)  return false;  // nothing to load yet
 965   if (code == Bytecodes::_invokedynamic) {
 966     return cpool->resolved_indy_entry_at(which)->has_local_signature();
 967   } else {
 968     return cpool->resolved_method_entry_at(which)->has_local_signature();
 969   }
 970 }
 971 
 972 // Translate index, which could be CPCache index or Indy index, to a constant pool index
 973 int ConstantPool::to_cp_index(int index, Bytecodes::Code code) {
 974   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
 975   switch(code) {
 976     case Bytecodes::_invokedynamic:
 977       return invokedynamic_bootstrap_ref_index_at(index);
 978     case Bytecodes::_getfield:
 979     case Bytecodes::_getstatic:
 980     case Bytecodes::_putfield:
 981     case Bytecodes::_putstatic:
 982       return resolved_field_entry_at(index)->constant_pool_index();
 983     case Bytecodes::_invokeinterface:
 984     case Bytecodes::_invokehandle:
 985     case Bytecodes::_invokespecial:
 986     case Bytecodes::_invokestatic:
 987     case Bytecodes::_invokevirtual:
 988     case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
 989       return resolved_method_entry_at(index)->constant_pool_index();
 990     default:
 991       fatal("Unexpected bytecode: %s", Bytecodes::name(code));
 992   }
 993 }
 994 
 995 bool ConstantPool::is_resolved(int index, Bytecodes::Code code) {
 996   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
 997   switch(code) {
 998     case Bytecodes::_invokedynamic:
 999       return resolved_indy_entry_at(index)->is_resolved();
1000 
1001     case Bytecodes::_getfield:
1002     case Bytecodes::_getstatic:
1003     case Bytecodes::_putfield:
1004     case Bytecodes::_putstatic:
1005       return resolved_field_entry_at(index)->is_resolved(code);
1006 
1007     case Bytecodes::_invokeinterface:
1008     case Bytecodes::_invokehandle:
1009     case Bytecodes::_invokespecial:
1010     case Bytecodes::_invokestatic:
1011     case Bytecodes::_invokevirtual:
1012     case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
1013       return resolved_method_entry_at(index)->is_resolved(code);
1014 
1015     default:
1016       fatal("Unexpected bytecode: %s", Bytecodes::name(code));
1017   }
1018 }
1019 
1020 u2 ConstantPool::uncached_name_and_type_ref_index_at(int cp_index)  {
1021   if (tag_at(cp_index).has_bootstrap()) {
1022     u2 pool_index = bootstrap_name_and_type_ref_index_at(cp_index);
1023     assert(tag_at(pool_index).is_name_and_type(), "");
1024     return pool_index;
1025   }
1026   assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
1027   assert(!tag_at(cp_index).has_bootstrap(), "Must be handled above");
1028   jint ref_index = *int_at_addr(cp_index);
1029   return extract_high_short_from_int(ref_index);
1030 }
1031 
1032 u2 ConstantPool::name_and_type_ref_index_at(int index, Bytecodes::Code code) {
1033   return uncached_name_and_type_ref_index_at(to_cp_index(index, code));
1034 }
1035 
1036 constantTag ConstantPool::tag_ref_at(int which, Bytecodes::Code code) {
1037   // which may be either a Constant Pool index or a rewritten index
1038   int pool_index = which;
1039   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
1040   pool_index = to_cp_index(which, code);
1041   return tag_at(pool_index);
1042 }
1043 
1044 u2 ConstantPool::uncached_klass_ref_index_at(int cp_index) {
1045   assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
1046   jint ref_index = *int_at_addr(cp_index);
1047   return extract_low_short_from_int(ref_index);
1048 }
1049 
1050 u2 ConstantPool::klass_ref_index_at(int index, Bytecodes::Code code) {
1051   assert(code != Bytecodes::_invokedynamic,
1052             "an invokedynamic instruction does not have a klass");
1053   return uncached_klass_ref_index_at(to_cp_index(index, code));
1054 }
1055 
1056 void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {
1057   if (!(k->is_instance_klass() || k->is_objArray_klass())) {
1058     return;  // short cut, typeArray klass is always accessible
1059   }
1060   Klass* holder = this_cp->pool_holder();
1061   LinkResolver::check_klass_accessibility(holder, k, CHECK);
1062 }
1063 
1064 
1065 u2 ConstantPool::name_ref_index_at(int cp_index) {
1066   jint ref_index = name_and_type_at(cp_index);
1067   return extract_low_short_from_int(ref_index);
1068 }
1069 
1070 
1071 u2 ConstantPool::signature_ref_index_at(int cp_index) {
1072   jint ref_index = name_and_type_at(cp_index);
1073   return extract_high_short_from_int(ref_index);
1074 }
1075 
1076 
1077 Klass* ConstantPool::klass_ref_at(int which, Bytecodes::Code code, TRAPS) {
1078   return klass_at(klass_ref_index_at(which, code), THREAD);
1079 }
1080 
1081 Symbol* ConstantPool::klass_name_at(int cp_index) const {
1082   return symbol_at(klass_slot_at(cp_index).name_index());
1083 }
1084 
1085 Symbol* ConstantPool::klass_ref_at_noresolve(int which, Bytecodes::Code code) {
1086   jint ref_index = klass_ref_index_at(which, code);
1087   return klass_at_noresolve(ref_index);
1088 }
1089 
1090 Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int cp_index) {
1091   jint ref_index = uncached_klass_ref_index_at(cp_index);
1092   return klass_at_noresolve(ref_index);
1093 }
1094 
1095 char* ConstantPool::string_at_noresolve(int cp_index) {
1096   return unresolved_string_at(cp_index)->as_C_string();
1097 }
1098 
1099 BasicType ConstantPool::basic_type_for_signature_at(int cp_index) const {
1100   return Signature::basic_type(symbol_at(cp_index));
1101 }
1102 
1103 
1104 void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {
1105   for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused
1106     if (this_cp->tag_at(index).is_string()) {
1107       this_cp->string_at(index, CHECK);
1108     }
1109   }
1110 }
1111 
1112 static const char* exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {
1113   // Note: caller needs ResourceMark
1114 
1115   // Dig out the detailed message to reuse if possible
1116   const char* msg = java_lang_Throwable::message_as_utf8(pending_exception);
1117   if (msg != nullptr) {
1118     return msg;
1119   }
1120 
1121   Symbol* message = nullptr;
1122   // Return specific message for the tag
1123   switch (tag.value()) {
1124   case JVM_CONSTANT_UnresolvedClass:
1125     // return the class name in the error message
1126     message = this_cp->klass_name_at(which);
1127     break;
1128   case JVM_CONSTANT_MethodHandle:
1129     // return the method handle name in the error message
1130     message = this_cp->method_handle_name_ref_at(which);
1131     break;
1132   case JVM_CONSTANT_MethodType:
1133     // return the method type signature in the error message
1134     message = this_cp->method_type_signature_at(which);
1135     break;
1136   case JVM_CONSTANT_Dynamic:
1137     // return the name of the condy in the error message
1138     message = this_cp->uncached_name_ref_at(which);
1139     break;
1140   default:
1141     ShouldNotReachHere();
1142   }
1143 
1144   return message != nullptr ? message->as_C_string() : nullptr;
1145 }
1146 
1147 static void add_resolution_error(JavaThread* current, const constantPoolHandle& this_cp, int which,
1148                                  constantTag tag, oop pending_exception) {
1149 
1150   ResourceMark rm(current);
1151   Symbol* error = pending_exception->klass()->name();
1152   oop cause = java_lang_Throwable::cause(pending_exception);
1153 
1154   // Also dig out the exception cause, if present.
1155   Symbol* cause_sym = nullptr;
1156   const char* cause_msg = nullptr;
1157   if (cause != nullptr && cause != pending_exception) {
1158     cause_sym = cause->klass()->name();
1159     cause_msg = java_lang_Throwable::message_as_utf8(cause);
1160   }
1161 
1162   const char* message = exception_message(this_cp, which, tag, pending_exception);
1163   SystemDictionary::add_resolution_error(this_cp, which, error, message, cause_sym, cause_msg);
1164 }
1165 
1166 
1167 void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {
1168   ResourceMark rm(THREAD);
1169   const char* message = nullptr;
1170   Symbol* cause = nullptr;
1171   const char* cause_msg = nullptr;
1172   Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message, &cause, &cause_msg);
1173   assert(error != nullptr, "checking");
1174 
1175   CLEAR_PENDING_EXCEPTION;
1176   if (message != nullptr) {
1177     if (cause != nullptr) {
1178       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1179       THROW_MSG_CAUSE(error, message, h_cause);
1180     } else {
1181       THROW_MSG(error, message);
1182     }
1183   } else {
1184     if (cause != nullptr) {
1185       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1186       THROW_CAUSE(error, h_cause);
1187     } else {
1188       THROW(error);
1189     }
1190   }
1191 }
1192 
1193 // If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the
1194 // exception in the resolution error table, so that the same exception is thrown again.
1195 void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int cp_index,
1196                                             constantTag tag, TRAPS) {
1197 
1198   int error_tag = tag.error_value();
1199 
1200   if (!PENDING_EXCEPTION->
1201     is_a(vmClasses::LinkageError_klass())) {
1202     // Just throw the exception and don't prevent these classes from
1203     // being loaded due to virtual machine errors like StackOverflow
1204     // and OutOfMemoryError, etc, or if the thread was hit by stop()
1205     // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
1206   } else if (this_cp->tag_at(cp_index).value() != error_tag) {
1207     add_resolution_error(THREAD, this_cp, cp_index, tag, PENDING_EXCEPTION);
1208     // CAS in the tag.  If a thread beat us to registering this error that's fine.
1209     // If another thread resolved the reference, this is a race condition. This
1210     // thread may have had a security manager or something temporary.
1211     // This doesn't deterministically get an error.   So why do we save this?
1212     // We save this because jvmti can add classes to the bootclass path after
1213     // this error, so it needs to get the same error if the error is first.
1214     jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
1215                                     (jbyte)tag.value(),
1216                                     (jbyte)error_tag);
1217     if (old_tag != error_tag && old_tag != tag.value()) {
1218       // MethodHandles and MethodType doesn't change to resolved version.
1219       assert(this_cp->tag_at(cp_index).is_klass(), "Wrong tag value");
1220       // Forget the exception and use the resolved class.
1221       CLEAR_PENDING_EXCEPTION;
1222     }
1223   } else {
1224     // some other thread put this in error state
1225     throw_resolution_error(this_cp, cp_index, CHECK);
1226   }
1227 }
1228 
1229 constantTag ConstantPool::constant_tag_at(int cp_index) {
1230   constantTag tag = tag_at(cp_index);
1231   if (tag.is_dynamic_constant()) {
1232     BasicType bt = basic_type_for_constant_at(cp_index);
1233     return constantTag(constantTag::type2tag(bt));
1234   }
1235   return tag;
1236 }
1237 
1238 BasicType ConstantPool::basic_type_for_constant_at(int cp_index) {
1239   constantTag tag = tag_at(cp_index);
1240   if (tag.is_dynamic_constant() ||
1241       tag.is_dynamic_constant_in_error()) {
1242     // have to look at the signature for this one
1243     Symbol* constant_type = uncached_signature_ref_at(cp_index);
1244     return Signature::basic_type(constant_type);
1245   }
1246   return tag.basic_type();
1247 }
1248 
1249 // Called to resolve constants in the constant pool and return an oop.
1250 // Some constant pool entries cache their resolved oop. This is also
1251 // called to create oops from constants to use in arguments for invokedynamic
1252 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
1253                                            int cp_index, int cache_index,
1254                                            bool* status_return, TRAPS) {
1255   oop result_oop = nullptr;
1256 
1257   if (cache_index == _possible_index_sentinel) {
1258     // It is possible that this constant is one which is cached in the objects.
1259     // We'll do a linear search.  This should be OK because this usage is rare.
1260     // FIXME: If bootstrap specifiers stress this code, consider putting in
1261     // a reverse index.  Binary search over a short array should do it.
1262     assert(cp_index > 0, "valid constant pool index");
1263     cache_index = this_cp->cp_to_object_index(cp_index);
1264   }
1265   assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
1266   assert(cp_index == _no_index_sentinel || cp_index >= 0, "");
1267 
1268   if (cache_index >= 0) {
1269     result_oop = this_cp->resolved_reference_at(cache_index);
1270     if (result_oop != nullptr) {
1271       if (result_oop == Universe::the_null_sentinel()) {
1272         DEBUG_ONLY(int temp_index = (cp_index >= 0 ? cp_index : this_cp->object_to_cp_index(cache_index)));
1273         assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
1274         result_oop = nullptr;
1275       }
1276       if (status_return != nullptr)  (*status_return) = true;
1277       return result_oop;
1278       // That was easy...
1279     }
1280     cp_index = this_cp->object_to_cp_index(cache_index);
1281   }
1282 
1283   jvalue prim_value;  // temp used only in a few cases below
1284 
1285   constantTag tag = this_cp->tag_at(cp_index);
1286 
1287   if (status_return != nullptr) {
1288     // don't trigger resolution if the constant might need it
1289     switch (tag.value()) {
1290     case JVM_CONSTANT_Class:
1291     {
1292       CPKlassSlot kslot = this_cp->klass_slot_at(cp_index);
1293       int resolved_klass_index = kslot.resolved_klass_index();
1294       if (this_cp->resolved_klasses()->at(resolved_klass_index) == nullptr) {
1295         (*status_return) = false;
1296         return nullptr;
1297       }
1298       // the klass is waiting in the CP; go get it
1299       break;
1300     }
1301     case JVM_CONSTANT_String:
1302     case JVM_CONSTANT_Integer:
1303     case JVM_CONSTANT_Float:
1304     case JVM_CONSTANT_Long:
1305     case JVM_CONSTANT_Double:
1306       // these guys trigger OOM at worst
1307       break;
1308     default:
1309       (*status_return) = false;
1310       return nullptr;
1311     }
1312     // from now on there is either success or an OOME
1313     (*status_return) = true;
1314   }
1315 
1316   switch (tag.value()) {
1317 
1318   case JVM_CONSTANT_UnresolvedClass:
1319   case JVM_CONSTANT_Class:
1320     {
1321       assert(cache_index == _no_index_sentinel, "should not have been set");
1322       Klass* resolved = klass_at_impl(this_cp, cp_index, CHECK_NULL);
1323       // ldc wants the java mirror.
1324       result_oop = resolved->java_mirror();
1325       break;
1326     }
1327 
1328   case JVM_CONSTANT_Dynamic:
1329     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_invokedynamic_time(),
1330                                 ClassLoader::perf_resolve_invokedynamic_count(),
1331                                 THREAD->class_being_initialized() == nullptr);
1332       // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
1333       BootstrapInfo bootstrap_specifier(this_cp, cp_index);
1334 
1335       // The initial step in resolving an unresolved symbolic reference to a
1336       // dynamically-computed constant is to resolve the symbolic reference to a
1337       // method handle which will be the bootstrap method for the dynamically-computed
1338       // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
1339       // method fails, then a MethodHandleInError is stored at the corresponding
1340       // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
1341       // set a DynamicConstantInError here since any subsequent use of this
1342       // bootstrap method will encounter the resolution of MethodHandleInError.
1343       // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
1344       // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
1345       // for the bootstrap_specifier created above.
1346       SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1347       Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);
1348       if (HAS_PENDING_EXCEPTION) {
1349         // Resolution failure of the dynamically-computed constant, save_and_throw_exception
1350         // will check for a LinkageError and store a DynamicConstantInError.
1351         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1352       }
1353       result_oop = bootstrap_specifier.resolved_value()();
1354       BasicType type = Signature::basic_type(bootstrap_specifier.signature());
1355       if (!is_reference_type(type)) {
1356         // Make sure the primitive value is properly boxed.
1357         // This is a JDK responsibility.
1358         const char* fail = nullptr;
1359         if (result_oop == nullptr) {
1360           fail = "null result instead of box";
1361         } else if (!is_java_primitive(type)) {
1362           // FIXME: support value types via unboxing
1363           fail = "can only handle references and primitives";
1364         } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
1365           fail = "primitive is not properly boxed";
1366         }
1367         if (fail != nullptr) {
1368           // Since this exception is not a LinkageError, throw exception
1369           // but do not save a DynamicInError resolution result.
1370           // See section 5.4.3 of the VM spec.
1371           THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
1372         }
1373       }
1374 
1375       LogTarget(Debug, methodhandles, condy) lt_condy;
1376       if (lt_condy.is_enabled()) {
1377         LogStream ls(lt_condy);
1378         bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");
1379       }
1380       break;
1381     }
1382 
1383   case JVM_CONSTANT_String:
1384     assert(cache_index != _no_index_sentinel, "should have been set");
1385     result_oop = string_at_impl(this_cp, cp_index, cache_index, CHECK_NULL);
1386     break;
1387 
1388   case JVM_CONSTANT_MethodHandle:
1389     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_handle_time(),
1390                                 ClassLoader::perf_resolve_method_handle_count(),
1391                                 THREAD->class_being_initialized() == nullptr);
1392       int ref_kind                 = this_cp->method_handle_ref_kind_at(cp_index);
1393       int callee_index             = this_cp->method_handle_klass_index_at(cp_index);
1394       Symbol*  name =      this_cp->method_handle_name_ref_at(cp_index);
1395       Symbol*  signature = this_cp->method_handle_signature_ref_at(cp_index);
1396       constantTag m_tag  = this_cp->tag_at(this_cp->method_handle_index_at(cp_index));
1397       { ResourceMark rm(THREAD);
1398         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1399                               ref_kind, cp_index, this_cp->method_handle_index_at(cp_index),
1400                               callee_index, name->as_C_string(), signature->as_C_string());
1401       }
1402 
1403       Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);
1404       if (HAS_PENDING_EXCEPTION) {
1405         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1406       }
1407 
1408       // Check constant pool method consistency
1409       if ((callee->is_interface() && m_tag.is_method()) ||
1410           (!callee->is_interface() && m_tag.is_interface_method())) {
1411         ResourceMark rm(THREAD);
1412         stringStream ss;
1413         ss.print("Inconsistent constant pool data in classfile for class %s. "
1414                  "Method '", callee->name()->as_C_string());
1415         signature->print_as_signature_external_return_type(&ss);
1416         ss.print(" %s(", name->as_C_string());
1417         signature->print_as_signature_external_parameters(&ss);
1418         ss.print(")' at index %d is %s and should be %s",
1419                  cp_index,
1420                  callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1421                  callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1422         Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());
1423         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1424       }
1425 
1426       Klass* klass = this_cp->pool_holder();
1427       HandleMark hm(THREAD);
1428       Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1429                                                                    callee, name, signature,
1430                                                                    THREAD);
1431       if (HAS_PENDING_EXCEPTION) {
1432         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1433       }
1434       result_oop = value();
1435       break;
1436     }
1437 
1438   case JVM_CONSTANT_MethodType:
1439     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_type_time(),
1440                                 ClassLoader::perf_resolve_method_type_count(),
1441                                 THREAD->class_being_initialized() == nullptr);
1442       Symbol*  signature = this_cp->method_type_signature_at(cp_index);
1443       { ResourceMark rm(THREAD);
1444         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1445                               cp_index, this_cp->method_type_index_at(cp_index),
1446                               signature->as_C_string());
1447       }
1448       Klass* klass = this_cp->pool_holder();
1449       HandleMark hm(THREAD);
1450       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1451       result_oop = value();
1452       if (HAS_PENDING_EXCEPTION) {
1453         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1454       }
1455       break;
1456     }
1457 
1458   case JVM_CONSTANT_Integer:
1459     assert(cache_index == _no_index_sentinel, "should not have been set");
1460     prim_value.i = this_cp->int_at(cp_index);
1461     result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1462     break;
1463 
1464   case JVM_CONSTANT_Float:
1465     assert(cache_index == _no_index_sentinel, "should not have been set");
1466     prim_value.f = this_cp->float_at(cp_index);
1467     result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1468     break;
1469 
1470   case JVM_CONSTANT_Long:
1471     assert(cache_index == _no_index_sentinel, "should not have been set");
1472     prim_value.j = this_cp->long_at(cp_index);
1473     result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1474     break;
1475 
1476   case JVM_CONSTANT_Double:
1477     assert(cache_index == _no_index_sentinel, "should not have been set");
1478     prim_value.d = this_cp->double_at(cp_index);
1479     result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1480     break;
1481 
1482   case JVM_CONSTANT_UnresolvedClassInError:
1483   case JVM_CONSTANT_DynamicInError:
1484   case JVM_CONSTANT_MethodHandleInError:
1485   case JVM_CONSTANT_MethodTypeInError:
1486     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
1487     break;
1488 
1489   default:
1490     fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), cp_index, cache_index, tag.value());
1491     break;
1492   }
1493 
1494   if (cache_index >= 0) {
1495     // Benign race condition:  resolved_references may already be filled in.
1496     // The important thing here is that all threads pick up the same result.
1497     // It doesn't matter which racing thread wins, as long as only one
1498     // result is used by all threads, and all future queries.
1499     oop new_result = (result_oop == nullptr ? Universe::the_null_sentinel() : result_oop);
1500     oop old_result = this_cp->set_resolved_reference_at(cache_index, new_result);
1501     if (old_result == nullptr) {
1502       return result_oop;  // was installed
1503     } else {
1504       // Return the winning thread's result.  This can be different than
1505       // the result here for MethodHandles.
1506       if (old_result == Universe::the_null_sentinel())
1507         old_result = nullptr;
1508       return old_result;
1509     }
1510   } else {
1511     assert(result_oop != Universe::the_null_sentinel(), "");
1512     return result_oop;
1513   }
1514 }
1515 
1516 oop ConstantPool::uncached_string_at(int cp_index, TRAPS) {
1517   Symbol* sym = unresolved_string_at(cp_index);
1518   oop str = StringTable::intern(sym, CHECK_(nullptr));
1519   assert(java_lang_String::is_instance(str), "must be string");
1520   return str;
1521 }
1522 
1523 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int cp_index,
1524                                                     int start_arg, int end_arg,
1525                                                     objArrayHandle info, int pos,
1526                                                     bool must_resolve, Handle if_not_available,
1527                                                     TRAPS) {
1528   int limit = pos + end_arg - start_arg;
1529   // checks: cp_index in range [0..this_cp->length),
1530   // tag at cp_index, start..end in range [0..this_cp->bootstrap_argument_count],
1531   // info array non-null, pos..limit in [0..info.length]
1532   if ((0 >= cp_index    || cp_index >= this_cp->length())  ||
1533       !(this_cp->tag_at(cp_index).is_invoke_dynamic()    ||
1534         this_cp->tag_at(cp_index).is_dynamic_constant()) ||
1535       (0 > start_arg || start_arg > end_arg) ||
1536       (end_arg > this_cp->bootstrap_argument_count_at(cp_index)) ||
1537       (0 > pos       || pos > limit)         ||
1538       (info.is_null() || limit > info->length())) {
1539     // An index or something else went wrong; throw an error.
1540     // Since this is an internal API, we don't expect this,
1541     // so we don't bother to craft a nice message.
1542     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1543   }
1544   // now we can loop safely
1545   int info_i = pos;
1546   for (int i = start_arg; i < end_arg; i++) {
1547     int arg_index = this_cp->bootstrap_argument_index_at(cp_index, i);
1548     oop arg_oop;
1549     if (must_resolve) {
1550       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1551     } else {
1552       bool found_it = false;
1553       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1554       if (!found_it)  arg_oop = if_not_available();
1555     }
1556     info->obj_at_put(info_i++, arg_oop);
1557   }
1558 }
1559 
1560 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int cp_index, int obj_index, TRAPS) {
1561   // If the string has already been interned, this entry will be non-null
1562   oop str = this_cp->resolved_reference_at(obj_index);
1563   assert(str != Universe::the_null_sentinel(), "");
1564   if (str != nullptr) return str;
1565   Symbol* sym = this_cp->unresolved_string_at(cp_index);
1566   str = StringTable::intern(sym, CHECK_(nullptr));
1567   this_cp->string_at_put(obj_index, str);
1568   assert(java_lang_String::is_instance(str), "must be string");
1569   return str;
1570 }
1571 
1572 
1573 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int cp_index) {
1574   // Names are interned, so we can compare Symbol*s directly
1575   Symbol* cp_name = klass_name_at(cp_index);
1576   return (cp_name == k->name());
1577 }
1578 
1579 
1580 // Iterate over symbols and decrement ones which are Symbol*s
1581 // This is done during GC.
1582 // Only decrement the UTF8 symbols. Strings point to
1583 // these symbols but didn't increment the reference count.
1584 void ConstantPool::unreference_symbols() {
1585   for (int index = 1; index < length(); index++) { // Index 0 is unused
1586     constantTag tag = tag_at(index);
1587     if (tag.is_symbol()) {
1588       symbol_at(index)->decrement_refcount();
1589     }
1590   }
1591 }
1592 
1593 
1594 // Compare this constant pool's entry at index1 to the constant pool
1595 // cp2's entry at index2.
1596 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1597        int index2) {
1598 
1599   // The error tags are equivalent to non-error tags when comparing
1600   jbyte t1 = tag_at(index1).non_error_value();
1601   jbyte t2 = cp2->tag_at(index2).non_error_value();
1602 
1603   // Some classes are pre-resolved (like Throwable) which may lead to
1604   // consider it as a different entry. We then revert them back temporarily
1605   // to ensure proper comparison.
1606   if (t1 == JVM_CONSTANT_Class) {
1607     t1 = JVM_CONSTANT_UnresolvedClass;
1608   }
1609   if (t2 == JVM_CONSTANT_Class) {
1610     t2 = JVM_CONSTANT_UnresolvedClass;
1611   }
1612 
1613   if (t1 != t2) {
1614     // Not the same entry type so there is nothing else to check. Note
1615     // that this style of checking will consider resolved/unresolved
1616     // class pairs as different.
1617     // From the ConstantPool* API point of view, this is correct
1618     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1619     // plays out in the context of ConstantPool* merging.
1620     return false;
1621   }
1622 
1623   switch (t1) {
1624   case JVM_CONSTANT_ClassIndex:
1625   {
1626     int recur1 = klass_index_at(index1);
1627     int recur2 = cp2->klass_index_at(index2);
1628     if (compare_entry_to(recur1, cp2, recur2)) {
1629       return true;
1630     }
1631   } break;
1632 
1633   case JVM_CONSTANT_Double:
1634   {
1635     jdouble d1 = double_at(index1);
1636     jdouble d2 = cp2->double_at(index2);
1637     if (d1 == d2) {
1638       return true;
1639     }
1640   } break;
1641 
1642   case JVM_CONSTANT_Fieldref:
1643   case JVM_CONSTANT_InterfaceMethodref:
1644   case JVM_CONSTANT_Methodref:
1645   {
1646     int recur1 = uncached_klass_ref_index_at(index1);
1647     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1648     bool match = compare_entry_to(recur1, cp2, recur2);
1649     if (match) {
1650       recur1 = uncached_name_and_type_ref_index_at(index1);
1651       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1652       if (compare_entry_to(recur1, cp2, recur2)) {
1653         return true;
1654       }
1655     }
1656   } break;
1657 
1658   case JVM_CONSTANT_Float:
1659   {
1660     jfloat f1 = float_at(index1);
1661     jfloat f2 = cp2->float_at(index2);
1662     if (f1 == f2) {
1663       return true;
1664     }
1665   } break;
1666 
1667   case JVM_CONSTANT_Integer:
1668   {
1669     jint i1 = int_at(index1);
1670     jint i2 = cp2->int_at(index2);
1671     if (i1 == i2) {
1672       return true;
1673     }
1674   } break;
1675 
1676   case JVM_CONSTANT_Long:
1677   {
1678     jlong l1 = long_at(index1);
1679     jlong l2 = cp2->long_at(index2);
1680     if (l1 == l2) {
1681       return true;
1682     }
1683   } break;
1684 
1685   case JVM_CONSTANT_NameAndType:
1686   {
1687     int recur1 = name_ref_index_at(index1);
1688     int recur2 = cp2->name_ref_index_at(index2);
1689     if (compare_entry_to(recur1, cp2, recur2)) {
1690       recur1 = signature_ref_index_at(index1);
1691       recur2 = cp2->signature_ref_index_at(index2);
1692       if (compare_entry_to(recur1, cp2, recur2)) {
1693         return true;
1694       }
1695     }
1696   } break;
1697 
1698   case JVM_CONSTANT_StringIndex:
1699   {
1700     int recur1 = string_index_at(index1);
1701     int recur2 = cp2->string_index_at(index2);
1702     if (compare_entry_to(recur1, cp2, recur2)) {
1703       return true;
1704     }
1705   } break;
1706 
1707   case JVM_CONSTANT_UnresolvedClass:
1708   {
1709     Symbol* k1 = klass_name_at(index1);
1710     Symbol* k2 = cp2->klass_name_at(index2);
1711     if (k1 == k2) {
1712       return true;
1713     }
1714   } break;
1715 
1716   case JVM_CONSTANT_MethodType:
1717   {
1718     int k1 = method_type_index_at(index1);
1719     int k2 = cp2->method_type_index_at(index2);
1720     if (compare_entry_to(k1, cp2, k2)) {
1721       return true;
1722     }
1723   } break;
1724 
1725   case JVM_CONSTANT_MethodHandle:
1726   {
1727     int k1 = method_handle_ref_kind_at(index1);
1728     int k2 = cp2->method_handle_ref_kind_at(index2);
1729     if (k1 == k2) {
1730       int i1 = method_handle_index_at(index1);
1731       int i2 = cp2->method_handle_index_at(index2);
1732       if (compare_entry_to(i1, cp2, i2)) {
1733         return true;
1734       }
1735     }
1736   } break;
1737 
1738   case JVM_CONSTANT_Dynamic:
1739   {
1740     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1741     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1742     int i1 = bootstrap_methods_attribute_index(index1);
1743     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1744     bool match_entry = compare_entry_to(k1, cp2, k2);
1745     bool match_operand = compare_operand_to(i1, cp2, i2);
1746     return (match_entry && match_operand);
1747   } break;
1748 
1749   case JVM_CONSTANT_InvokeDynamic:
1750   {
1751     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1752     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1753     int i1 = bootstrap_methods_attribute_index(index1);
1754     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1755     bool match_entry = compare_entry_to(k1, cp2, k2);
1756     bool match_operand = compare_operand_to(i1, cp2, i2);
1757     return (match_entry && match_operand);
1758   } break;
1759 
1760   case JVM_CONSTANT_String:
1761   {
1762     Symbol* s1 = unresolved_string_at(index1);
1763     Symbol* s2 = cp2->unresolved_string_at(index2);
1764     if (s1 == s2) {
1765       return true;
1766     }
1767   } break;
1768 
1769   case JVM_CONSTANT_Utf8:
1770   {
1771     Symbol* s1 = symbol_at(index1);
1772     Symbol* s2 = cp2->symbol_at(index2);
1773     if (s1 == s2) {
1774       return true;
1775     }
1776   } break;
1777 
1778   // Invalid is used as the tag for the second constant pool entry
1779   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1780   // not be seen by itself.
1781   case JVM_CONSTANT_Invalid: // fall through
1782 
1783   default:
1784     ShouldNotReachHere();
1785     break;
1786   }
1787 
1788   return false;
1789 } // end compare_entry_to()
1790 
1791 
1792 // Resize the operands array with delta_len and delta_size.
1793 // Used in RedefineClasses for CP merge.
1794 void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
1795   int old_len  = operand_array_length(operands());
1796   int new_len  = old_len + delta_len;
1797   int min_len  = (delta_len > 0) ? old_len : new_len;
1798 
1799   int old_size = operands()->length();
1800   int new_size = old_size + delta_size;
1801   int min_size = (delta_size > 0) ? old_size : new_size;
1802 
1803   ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1804   Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
1805 
1806   // Set index in the resized array for existing elements only
1807   for (int idx = 0; idx < min_len; idx++) {
1808     int offset = operand_offset_at(idx);                       // offset in original array
1809     operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
1810   }
1811   // Copy the bootstrap specifiers only
1812   Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
1813                                new_ops->adr_at(2*new_len),
1814                                (min_size - 2*min_len) * sizeof(u2));
1815   // Explicitly deallocate old operands array.
1816   // Note, it is not needed for 7u backport.
1817   if ( operands() != nullptr) { // the safety check
1818     MetadataFactory::free_array<u2>(loader_data, operands());
1819   }
1820   set_operands(new_ops);
1821 } // end resize_operands()
1822 
1823 
1824 // Extend the operands array with the length and size of the ext_cp operands.
1825 // Used in RedefineClasses for CP merge.
1826 void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {
1827   int delta_len = operand_array_length(ext_cp->operands());
1828   if (delta_len == 0) {
1829     return; // nothing to do
1830   }
1831   int delta_size = ext_cp->operands()->length();
1832 
1833   assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");
1834 
1835   if (operand_array_length(operands()) == 0) {
1836     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1837     Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
1838     // The first element index defines the offset of second part
1839     operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
1840     set_operands(new_ops);
1841   } else {
1842     resize_operands(delta_len, delta_size, CHECK);
1843   }
1844 
1845 } // end extend_operands()
1846 
1847 
1848 // Shrink the operands array to a smaller array with new_len length.
1849 // Used in RedefineClasses for CP merge.
1850 void ConstantPool::shrink_operands(int new_len, TRAPS) {
1851   int old_len = operand_array_length(operands());
1852   if (new_len == old_len) {
1853     return; // nothing to do
1854   }
1855   assert(new_len < old_len, "shrunken operands array must be smaller");
1856 
1857   int free_base  = operand_next_offset_at(new_len - 1);
1858   int delta_len  = new_len - old_len;
1859   int delta_size = 2*delta_len + free_base - operands()->length();
1860 
1861   resize_operands(delta_len, delta_size, CHECK);
1862 
1863 } // end shrink_operands()
1864 
1865 
1866 void ConstantPool::copy_operands(const constantPoolHandle& from_cp,
1867                                  const constantPoolHandle& to_cp,
1868                                  TRAPS) {
1869 
1870   int from_oplen = operand_array_length(from_cp->operands());
1871   int old_oplen  = operand_array_length(to_cp->operands());
1872   if (from_oplen != 0) {
1873     ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1874     // append my operands to the target's operands array
1875     if (old_oplen == 0) {
1876       // Can't just reuse from_cp's operand list because of deallocation issues
1877       int len = from_cp->operands()->length();
1878       Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
1879       Copy::conjoint_memory_atomic(
1880           from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
1881       to_cp->set_operands(new_ops);
1882     } else {
1883       int old_len  = to_cp->operands()->length();
1884       int from_len = from_cp->operands()->length();
1885       int old_off  = old_oplen * sizeof(u2);
1886       int from_off = from_oplen * sizeof(u2);
1887       // Use the metaspace for the destination constant pool
1888       Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1889       int fillp = 0, len = 0;
1890       // first part of dest
1891       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
1892                                    new_operands->adr_at(fillp),
1893                                    (len = old_off) * sizeof(u2));
1894       fillp += len;
1895       // first part of src
1896       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1897                                    new_operands->adr_at(fillp),
1898                                    (len = from_off) * sizeof(u2));
1899       fillp += len;
1900       // second part of dest
1901       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
1902                                    new_operands->adr_at(fillp),
1903                                    (len = old_len - old_off) * sizeof(u2));
1904       fillp += len;
1905       // second part of src
1906       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1907                                    new_operands->adr_at(fillp),
1908                                    (len = from_len - from_off) * sizeof(u2));
1909       fillp += len;
1910       assert(fillp == new_operands->length(), "");
1911 
1912       // Adjust indexes in the first part of the copied operands array.
1913       for (int j = 0; j < from_oplen; j++) {
1914         int offset = operand_offset_at(new_operands, old_oplen + j);
1915         assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
1916         offset += old_len;  // every new tuple is preceded by old_len extra u2's
1917         operand_offset_at_put(new_operands, old_oplen + j, offset);
1918       }
1919 
1920       // replace target operands array with combined array
1921       to_cp->set_operands(new_operands);
1922     }
1923   }
1924 } // end copy_operands()
1925 
1926 
1927 // Copy this constant pool's entries at start_i to end_i (inclusive)
1928 // to the constant pool to_cp's entries starting at to_i. A total of
1929 // (end_i - start_i) + 1 entries are copied.
1930 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1931        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1932 
1933 
1934   int dest_cpi = to_i;  // leave original alone for debug purposes
1935 
1936   for (int src_cpi = start_i; src_cpi <= end_i; /* see loop bottom */ ) {
1937     copy_entry_to(from_cp, src_cpi, to_cp, dest_cpi);
1938 
1939     switch (from_cp->tag_at(src_cpi).value()) {
1940     case JVM_CONSTANT_Double:
1941     case JVM_CONSTANT_Long:
1942       // double and long take two constant pool entries
1943       src_cpi += 2;
1944       dest_cpi += 2;
1945       break;
1946 
1947     default:
1948       // all others take one constant pool entry
1949       src_cpi++;
1950       dest_cpi++;
1951       break;
1952     }
1953   }
1954   copy_operands(from_cp, to_cp, CHECK);
1955 
1956 } // end copy_cp_to_impl()
1957 
1958 
1959 // Copy this constant pool's entry at from_i to the constant pool
1960 // to_cp's entry at to_i.
1961 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1962                                         const constantPoolHandle& to_cp, int to_i) {
1963 
1964   int tag = from_cp->tag_at(from_i).value();
1965   switch (tag) {
1966   case JVM_CONSTANT_ClassIndex:
1967   {
1968     jint ki = from_cp->klass_index_at(from_i);
1969     to_cp->klass_index_at_put(to_i, ki);
1970   } break;
1971 
1972   case JVM_CONSTANT_Double:
1973   {
1974     jdouble d = from_cp->double_at(from_i);
1975     to_cp->double_at_put(to_i, d);
1976     // double takes two constant pool entries so init second entry's tag
1977     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1978   } break;
1979 
1980   case JVM_CONSTANT_Fieldref:
1981   {
1982     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1983     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1984     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1985   } break;
1986 
1987   case JVM_CONSTANT_Float:
1988   {
1989     jfloat f = from_cp->float_at(from_i);
1990     to_cp->float_at_put(to_i, f);
1991   } break;
1992 
1993   case JVM_CONSTANT_Integer:
1994   {
1995     jint i = from_cp->int_at(from_i);
1996     to_cp->int_at_put(to_i, i);
1997   } break;
1998 
1999   case JVM_CONSTANT_InterfaceMethodref:
2000   {
2001     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
2002     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
2003     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
2004   } break;
2005 
2006   case JVM_CONSTANT_Long:
2007   {
2008     jlong l = from_cp->long_at(from_i);
2009     to_cp->long_at_put(to_i, l);
2010     // long takes two constant pool entries so init second entry's tag
2011     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
2012   } break;
2013 
2014   case JVM_CONSTANT_Methodref:
2015   {
2016     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
2017     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
2018     to_cp->method_at_put(to_i, class_index, name_and_type_index);
2019   } break;
2020 
2021   case JVM_CONSTANT_NameAndType:
2022   {
2023     int name_ref_index = from_cp->name_ref_index_at(from_i);
2024     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
2025     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
2026   } break;
2027 
2028   case JVM_CONSTANT_StringIndex:
2029   {
2030     jint si = from_cp->string_index_at(from_i);
2031     to_cp->string_index_at_put(to_i, si);
2032   } break;
2033 
2034   case JVM_CONSTANT_Class:
2035   case JVM_CONSTANT_UnresolvedClass:
2036   case JVM_CONSTANT_UnresolvedClassInError:
2037   {
2038     // Revert to JVM_CONSTANT_ClassIndex
2039     int name_index = from_cp->klass_slot_at(from_i).name_index();
2040     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
2041     to_cp->klass_index_at_put(to_i, name_index);
2042   } break;
2043 
2044   case JVM_CONSTANT_String:
2045   {
2046     Symbol* s = from_cp->unresolved_string_at(from_i);
2047     to_cp->unresolved_string_at_put(to_i, s);
2048   } break;
2049 
2050   case JVM_CONSTANT_Utf8:
2051   {
2052     Symbol* s = from_cp->symbol_at(from_i);
2053     // Need to increase refcount, the old one will be thrown away and deferenced
2054     s->increment_refcount();
2055     to_cp->symbol_at_put(to_i, s);
2056   } break;
2057 
2058   case JVM_CONSTANT_MethodType:
2059   case JVM_CONSTANT_MethodTypeInError:
2060   {
2061     jint k = from_cp->method_type_index_at(from_i);
2062     to_cp->method_type_index_at_put(to_i, k);
2063   } break;
2064 
2065   case JVM_CONSTANT_MethodHandle:
2066   case JVM_CONSTANT_MethodHandleInError:
2067   {
2068     int k1 = from_cp->method_handle_ref_kind_at(from_i);
2069     int k2 = from_cp->method_handle_index_at(from_i);
2070     to_cp->method_handle_index_at_put(to_i, k1, k2);
2071   } break;
2072 
2073   case JVM_CONSTANT_Dynamic:
2074   case JVM_CONSTANT_DynamicInError:
2075   {
2076     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
2077     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
2078     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
2079     to_cp->dynamic_constant_at_put(to_i, k1, k2);
2080   } break;
2081 
2082   case JVM_CONSTANT_InvokeDynamic:
2083   {
2084     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
2085     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
2086     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
2087     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
2088   } break;
2089 
2090   // Invalid is used as the tag for the second constant pool entry
2091   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
2092   // not be seen by itself.
2093   case JVM_CONSTANT_Invalid: // fall through
2094 
2095   default:
2096   {
2097     ShouldNotReachHere();
2098   } break;
2099   }
2100 } // end copy_entry_to()
2101 
2102 // Search constant pool search_cp for an entry that matches this
2103 // constant pool's entry at pattern_i. Returns the index of a
2104 // matching entry or zero (0) if there is no matching entry.
2105 int ConstantPool::find_matching_entry(int pattern_i,
2106       const constantPoolHandle& search_cp) {
2107 
2108   // index zero (0) is not used
2109   for (int i = 1; i < search_cp->length(); i++) {
2110     bool found = compare_entry_to(pattern_i, search_cp, i);
2111     if (found) {
2112       return i;
2113     }
2114   }
2115 
2116   return 0;  // entry not found; return unused index zero (0)
2117 } // end find_matching_entry()
2118 
2119 
2120 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
2121 // cp2's bootstrap specifier at idx2.
2122 bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {
2123   int k1 = operand_bootstrap_method_ref_index_at(idx1);
2124   int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
2125   bool match = compare_entry_to(k1, cp2, k2);
2126 
2127   if (!match) {
2128     return false;
2129   }
2130   int argc = operand_argument_count_at(idx1);
2131   if (argc == cp2->operand_argument_count_at(idx2)) {
2132     for (int j = 0; j < argc; j++) {
2133       k1 = operand_argument_index_at(idx1, j);
2134       k2 = cp2->operand_argument_index_at(idx2, j);
2135       match = compare_entry_to(k1, cp2, k2);
2136       if (!match) {
2137         return false;
2138       }
2139     }
2140     return true;           // got through loop; all elements equal
2141   }
2142   return false;
2143 } // end compare_operand_to()
2144 
2145 // Search constant pool search_cp for a bootstrap specifier that matches
2146 // this constant pool's bootstrap specifier data at pattern_i index.
2147 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
2148 int ConstantPool::find_matching_operand(int pattern_i,
2149                     const constantPoolHandle& search_cp, int search_len) {
2150   for (int i = 0; i < search_len; i++) {
2151     bool found = compare_operand_to(pattern_i, search_cp, i);
2152     if (found) {
2153       return i;
2154     }
2155   }
2156   return -1;  // bootstrap specifier data not found; return unused index (-1)
2157 } // end find_matching_operand()
2158 
2159 
2160 #ifndef PRODUCT
2161 
2162 const char* ConstantPool::printable_name_at(int cp_index) {
2163 
2164   constantTag tag = tag_at(cp_index);
2165 
2166   if (tag.is_string()) {
2167     return string_at_noresolve(cp_index);
2168   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
2169     return klass_name_at(cp_index)->as_C_string();
2170   } else if (tag.is_symbol()) {
2171     return symbol_at(cp_index)->as_C_string();
2172   }
2173   return "";
2174 }
2175 
2176 #endif // PRODUCT
2177 
2178 
2179 // JVMTI GetConstantPool support
2180 
2181 // For debugging of constant pool
2182 const bool debug_cpool = false;
2183 
2184 #define DBG(code) do { if (debug_cpool) { (code); } } while(0)
2185 
2186 static void print_cpool_bytes(jint cnt, u1 *bytes) {
2187   const char* WARN_MSG = "Must not be such entry!";
2188   jint size = 0;
2189   u2   idx1, idx2;
2190 
2191   for (jint idx = 1; idx < cnt; idx++) {
2192     jint ent_size = 0;
2193     u1   tag  = *bytes++;
2194     size++;                       // count tag
2195 
2196     printf("const #%03d, tag: %02d ", idx, tag);
2197     switch(tag) {
2198       case JVM_CONSTANT_Invalid: {
2199         printf("Invalid");
2200         break;
2201       }
2202       case JVM_CONSTANT_Unicode: {
2203         printf("Unicode      %s", WARN_MSG);
2204         break;
2205       }
2206       case JVM_CONSTANT_Utf8: {
2207         u2 len = Bytes::get_Java_u2(bytes);
2208         char str[128];
2209         if (len > 127) {
2210            len = 127;
2211         }
2212         strncpy(str, (char *) (bytes+2), len);
2213         str[len] = '\0';
2214         printf("Utf8          \"%s\"", str);
2215         ent_size = 2 + len;
2216         break;
2217       }
2218       case JVM_CONSTANT_Integer: {
2219         u4 val = Bytes::get_Java_u4(bytes);
2220         printf("int          %d", *(int *) &val);
2221         ent_size = 4;
2222         break;
2223       }
2224       case JVM_CONSTANT_Float: {
2225         u4 val = Bytes::get_Java_u4(bytes);
2226         printf("float        %5.3ff", *(float *) &val);
2227         ent_size = 4;
2228         break;
2229       }
2230       case JVM_CONSTANT_Long: {
2231         u8 val = Bytes::get_Java_u8(bytes);
2232         printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
2233         ent_size = 8;
2234         idx++; // Long takes two cpool slots
2235         break;
2236       }
2237       case JVM_CONSTANT_Double: {
2238         u8 val = Bytes::get_Java_u8(bytes);
2239         printf("double       %5.3fd", *(jdouble *)&val);
2240         ent_size = 8;
2241         idx++; // Double takes two cpool slots
2242         break;
2243       }
2244       case JVM_CONSTANT_Class: {
2245         idx1 = Bytes::get_Java_u2(bytes);
2246         printf("class        #%03d", idx1);
2247         ent_size = 2;
2248         break;
2249       }
2250       case JVM_CONSTANT_String: {
2251         idx1 = Bytes::get_Java_u2(bytes);
2252         printf("String       #%03d", idx1);
2253         ent_size = 2;
2254         break;
2255       }
2256       case JVM_CONSTANT_Fieldref: {
2257         idx1 = Bytes::get_Java_u2(bytes);
2258         idx2 = Bytes::get_Java_u2(bytes+2);
2259         printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
2260         ent_size = 4;
2261         break;
2262       }
2263       case JVM_CONSTANT_Methodref: {
2264         idx1 = Bytes::get_Java_u2(bytes);
2265         idx2 = Bytes::get_Java_u2(bytes+2);
2266         printf("Method       #%03d, #%03d", idx1, idx2);
2267         ent_size = 4;
2268         break;
2269       }
2270       case JVM_CONSTANT_InterfaceMethodref: {
2271         idx1 = Bytes::get_Java_u2(bytes);
2272         idx2 = Bytes::get_Java_u2(bytes+2);
2273         printf("InterfMethod #%03d, #%03d", idx1, idx2);
2274         ent_size = 4;
2275         break;
2276       }
2277       case JVM_CONSTANT_NameAndType: {
2278         idx1 = Bytes::get_Java_u2(bytes);
2279         idx2 = Bytes::get_Java_u2(bytes+2);
2280         printf("NameAndType  #%03d, #%03d", idx1, idx2);
2281         ent_size = 4;
2282         break;
2283       }
2284       case JVM_CONSTANT_ClassIndex: {
2285         printf("ClassIndex  %s", WARN_MSG);
2286         break;
2287       }
2288       case JVM_CONSTANT_UnresolvedClass: {
2289         printf("UnresolvedClass: %s", WARN_MSG);
2290         break;
2291       }
2292       case JVM_CONSTANT_UnresolvedClassInError: {
2293         printf("UnresolvedClassInErr: %s", WARN_MSG);
2294         break;
2295       }
2296       case JVM_CONSTANT_StringIndex: {
2297         printf("StringIndex: %s", WARN_MSG);
2298         break;
2299       }
2300     }
2301     printf(";\n");
2302     bytes += ent_size;
2303     size  += ent_size;
2304   }
2305   printf("Cpool size: %d\n", size);
2306   fflush(0);
2307   return;
2308 } /* end print_cpool_bytes */
2309 
2310 
2311 // Returns size of constant pool entry.
2312 jint ConstantPool::cpool_entry_size(jint idx) {
2313   switch(tag_at(idx).value()) {
2314     case JVM_CONSTANT_Invalid:
2315     case JVM_CONSTANT_Unicode:
2316       return 1;
2317 
2318     case JVM_CONSTANT_Utf8:
2319       return 3 + symbol_at(idx)->utf8_length();
2320 
2321     case JVM_CONSTANT_Class:
2322     case JVM_CONSTANT_String:
2323     case JVM_CONSTANT_ClassIndex:
2324     case JVM_CONSTANT_UnresolvedClass:
2325     case JVM_CONSTANT_UnresolvedClassInError:
2326     case JVM_CONSTANT_StringIndex:
2327     case JVM_CONSTANT_MethodType:
2328     case JVM_CONSTANT_MethodTypeInError:
2329       return 3;
2330 
2331     case JVM_CONSTANT_MethodHandle:
2332     case JVM_CONSTANT_MethodHandleInError:
2333       return 4; //tag, ref_kind, ref_index
2334 
2335     case JVM_CONSTANT_Integer:
2336     case JVM_CONSTANT_Float:
2337     case JVM_CONSTANT_Fieldref:
2338     case JVM_CONSTANT_Methodref:
2339     case JVM_CONSTANT_InterfaceMethodref:
2340     case JVM_CONSTANT_NameAndType:
2341       return 5;
2342 
2343     case JVM_CONSTANT_Dynamic:
2344     case JVM_CONSTANT_DynamicInError:
2345     case JVM_CONSTANT_InvokeDynamic:
2346       // u1 tag, u2 bsm, u2 nt
2347       return 5;
2348 
2349     case JVM_CONSTANT_Long:
2350     case JVM_CONSTANT_Double:
2351       return 9;
2352   }
2353   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
2354   return 1;
2355 } /* end cpool_entry_size */
2356 
2357 
2358 // SymbolHash is used to find a constant pool index from a string.
2359 // This function fills in SymbolHashs, one for utf8s and one for
2360 // class names, returns size of the cpool raw bytes.
2361 jint ConstantPool::hash_entries_to(SymbolHash *symmap,
2362                                    SymbolHash *classmap) {
2363   jint size = 0;
2364 
2365   for (u2 idx = 1; idx < length(); idx++) {
2366     u2 tag = tag_at(idx).value();
2367     size += cpool_entry_size(idx);
2368 
2369     switch(tag) {
2370       case JVM_CONSTANT_Utf8: {
2371         Symbol* sym = symbol_at(idx);
2372         symmap->add_if_absent(sym, idx);
2373         DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
2374         break;
2375       }
2376       case JVM_CONSTANT_Class:
2377       case JVM_CONSTANT_UnresolvedClass:
2378       case JVM_CONSTANT_UnresolvedClassInError: {
2379         Symbol* sym = klass_name_at(idx);
2380         classmap->add_if_absent(sym, idx);
2381         DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
2382         break;
2383       }
2384       case JVM_CONSTANT_Long:
2385       case JVM_CONSTANT_Double: {
2386         idx++; // Both Long and Double take two cpool slots
2387         break;
2388       }
2389     }
2390   }
2391   return size;
2392 } /* end hash_utf8_entries_to */
2393 
2394 
2395 // Copy cpool bytes.
2396 // Returns:
2397 //    0, in case of OutOfMemoryError
2398 //   -1, in case of internal error
2399 //  > 0, count of the raw cpool bytes that have been copied
2400 int ConstantPool::copy_cpool_bytes(int cpool_size,
2401                                    SymbolHash* tbl,
2402                                    unsigned char *bytes) {
2403   u2   idx1, idx2;
2404   jint size  = 0;
2405   jint cnt   = length();
2406   unsigned char *start_bytes = bytes;
2407 
2408   for (jint idx = 1; idx < cnt; idx++) {
2409     u1   tag      = tag_at(idx).value();
2410     jint ent_size = cpool_entry_size(idx);
2411 
2412     assert(size + ent_size <= cpool_size, "Size mismatch");
2413 
2414     *bytes = tag;
2415     DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));
2416     switch(tag) {
2417       case JVM_CONSTANT_Invalid: {
2418         DBG(printf("JVM_CONSTANT_Invalid"));
2419         break;
2420       }
2421       case JVM_CONSTANT_Unicode: {
2422         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2423         DBG(printf("JVM_CONSTANT_Unicode"));
2424         break;
2425       }
2426       case JVM_CONSTANT_Utf8: {
2427         Symbol* sym = symbol_at(idx);
2428         char*     str = sym->as_utf8();
2429         // Warning! It's crashing on x86 with len = sym->utf8_length()
2430         int       len = (int) strlen(str);
2431         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2432         for (int i = 0; i < len; i++) {
2433             bytes[3+i] = (u1) str[i];
2434         }
2435         DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
2436         break;
2437       }
2438       case JVM_CONSTANT_Integer: {
2439         jint val = int_at(idx);
2440         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2441         break;
2442       }
2443       case JVM_CONSTANT_Float: {
2444         jfloat val = float_at(idx);
2445         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2446         break;
2447       }
2448       case JVM_CONSTANT_Long: {
2449         jlong val = long_at(idx);
2450         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2451         idx++;             // Long takes two cpool slots
2452         break;
2453       }
2454       case JVM_CONSTANT_Double: {
2455         jdouble val = double_at(idx);
2456         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2457         idx++;             // Double takes two cpool slots
2458         break;
2459       }
2460       case JVM_CONSTANT_Class:
2461       case JVM_CONSTANT_UnresolvedClass:
2462       case JVM_CONSTANT_UnresolvedClassInError: {
2463         *bytes = JVM_CONSTANT_Class;
2464         Symbol* sym = klass_name_at(idx);
2465         idx1 = tbl->symbol_to_value(sym);
2466         assert(idx1 != 0, "Have not found a hashtable entry");
2467         Bytes::put_Java_u2((address) (bytes+1), idx1);
2468         DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
2469         break;
2470       }
2471       case JVM_CONSTANT_String: {
2472         *bytes = JVM_CONSTANT_String;
2473         Symbol* sym = unresolved_string_at(idx);
2474         idx1 = tbl->symbol_to_value(sym);
2475         assert(idx1 != 0, "Have not found a hashtable entry");
2476         Bytes::put_Java_u2((address) (bytes+1), idx1);
2477         DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
2478         break;
2479       }
2480       case JVM_CONSTANT_Fieldref:
2481       case JVM_CONSTANT_Methodref:
2482       case JVM_CONSTANT_InterfaceMethodref: {
2483         idx1 = uncached_klass_ref_index_at(idx);
2484         idx2 = uncached_name_and_type_ref_index_at(idx);
2485         Bytes::put_Java_u2((address) (bytes+1), idx1);
2486         Bytes::put_Java_u2((address) (bytes+3), idx2);
2487         DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
2488         break;
2489       }
2490       case JVM_CONSTANT_NameAndType: {
2491         idx1 = name_ref_index_at(idx);
2492         idx2 = signature_ref_index_at(idx);
2493         Bytes::put_Java_u2((address) (bytes+1), idx1);
2494         Bytes::put_Java_u2((address) (bytes+3), idx2);
2495         DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
2496         break;
2497       }
2498       case JVM_CONSTANT_ClassIndex: {
2499         *bytes = JVM_CONSTANT_Class;
2500         idx1 = checked_cast<u2>(klass_index_at(idx));
2501         Bytes::put_Java_u2((address) (bytes+1), idx1);
2502         DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
2503         break;
2504       }
2505       case JVM_CONSTANT_StringIndex: {
2506         *bytes = JVM_CONSTANT_String;
2507         idx1 = checked_cast<u2>(string_index_at(idx));
2508         Bytes::put_Java_u2((address) (bytes+1), idx1);
2509         DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
2510         break;
2511       }
2512       case JVM_CONSTANT_MethodHandle:
2513       case JVM_CONSTANT_MethodHandleInError: {
2514         *bytes = JVM_CONSTANT_MethodHandle;
2515         int kind = method_handle_ref_kind_at(idx);
2516         idx1 = checked_cast<u2>(method_handle_index_at(idx));
2517         *(bytes+1) = (unsigned char) kind;
2518         Bytes::put_Java_u2((address) (bytes+2), idx1);
2519         DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
2520         break;
2521       }
2522       case JVM_CONSTANT_MethodType:
2523       case JVM_CONSTANT_MethodTypeInError: {
2524         *bytes = JVM_CONSTANT_MethodType;
2525         idx1 = checked_cast<u2>(method_type_index_at(idx));
2526         Bytes::put_Java_u2((address) (bytes+1), idx1);
2527         DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
2528         break;
2529       }
2530       case JVM_CONSTANT_Dynamic:
2531       case JVM_CONSTANT_DynamicInError: {
2532         *bytes = tag;
2533         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2534         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2535         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2536         Bytes::put_Java_u2((address) (bytes+1), idx1);
2537         Bytes::put_Java_u2((address) (bytes+3), idx2);
2538         DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));
2539         break;
2540       }
2541       case JVM_CONSTANT_InvokeDynamic: {
2542         *bytes = tag;
2543         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2544         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2545         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2546         Bytes::put_Java_u2((address) (bytes+1), idx1);
2547         Bytes::put_Java_u2((address) (bytes+3), idx2);
2548         DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
2549         break;
2550       }
2551     }
2552     DBG(printf("\n"));
2553     bytes += ent_size;
2554     size  += ent_size;
2555   }
2556   assert(size == cpool_size, "Size mismatch");
2557 
2558   // Keep temporarily for debugging until it's stable.
2559   DBG(print_cpool_bytes(cnt, start_bytes));
2560   return (int)(bytes - start_bytes);
2561 } /* end copy_cpool_bytes */
2562 
2563 #undef DBG
2564 
2565 bool ConstantPool::is_maybe_on_stack() const {
2566   // This method uses the similar logic as nmethod::is_maybe_on_stack()
2567   if (!Continuations::enabled()) {
2568     return false;
2569   }
2570 
2571   // If the condition below is true, it means that the nmethod was found to
2572   // be alive the previous completed marking cycle.
2573   return cache()->gc_epoch() >= CodeCache::previous_completed_gc_marking_cycle();
2574 }
2575 
2576 // For redefinition, if any methods found in loom stack chunks, the gc_epoch is
2577 // recorded in their constant pool cache. The on_stack-ness of the constant pool controls whether
2578 // memory for the method is reclaimed.
2579 bool ConstantPool::on_stack() const {
2580   if ((_flags &_on_stack) != 0) {
2581     return true;
2582   }
2583 
2584   if (_cache == nullptr) {
2585     return false;
2586   }
2587 
2588   return is_maybe_on_stack();
2589 }
2590 
2591 void ConstantPool::set_on_stack(const bool value) {
2592   if (value) {
2593     // Only record if it's not already set.
2594     if (!on_stack()) {
2595       assert(!is_shared(), "should always be set for shared constant pools");
2596       _flags |= _on_stack;
2597       MetadataOnStackMark::record(this);
2598     }
2599   } else {
2600     // Clearing is done single-threadedly.
2601     if (!is_shared()) {
2602       _flags &= (u2)(~_on_stack);
2603     }
2604   }
2605 }
2606 
2607 // Printing
2608 
2609 void ConstantPool::print_on(outputStream* st) const {
2610   assert(is_constantPool(), "must be constantPool");
2611   st->print_cr("%s", internal_name());
2612   if (flags() != 0) {
2613     st->print(" - flags: 0x%x", flags());
2614     if (has_preresolution()) st->print(" has_preresolution");
2615     if (on_stack()) st->print(" on_stack");
2616     st->cr();
2617   }
2618   if (pool_holder() != nullptr) {
2619     st->print_cr(" - holder: " PTR_FORMAT, p2i(pool_holder()));
2620   }
2621   st->print_cr(" - cache: " PTR_FORMAT, p2i(cache()));
2622   st->print_cr(" - resolved_references: " PTR_FORMAT, p2i(resolved_references_or_null()));
2623   st->print_cr(" - reference_map: " PTR_FORMAT, p2i(reference_map()));
2624   st->print_cr(" - resolved_klasses: " PTR_FORMAT, p2i(resolved_klasses()));
2625   st->print_cr(" - cp length: %d", length());
2626 
2627   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2628     ((ConstantPool*)this)->print_entry_on(index, st);
2629     switch (tag_at(index).value()) {
2630       case JVM_CONSTANT_Long :
2631       case JVM_CONSTANT_Double :
2632         index++;   // Skip entry following eigth-byte constant
2633     }
2634 
2635   }
2636   st->cr();
2637 }
2638 
2639 // Print one constant pool entry
2640 void ConstantPool::print_entry_on(const int cp_index, outputStream* st) {
2641   EXCEPTION_MARK;
2642   st->print(" - %3d : ", cp_index);
2643   tag_at(cp_index).print_on(st);
2644   st->print(" : ");
2645   switch (tag_at(cp_index).value()) {
2646     case JVM_CONSTANT_Class :
2647       { Klass* k = klass_at(cp_index, CATCH);
2648         guarantee(k != nullptr, "need klass");
2649         k->print_value_on(st);
2650         st->print(" {" PTR_FORMAT "}", p2i(k));
2651       }
2652       break;
2653     case JVM_CONSTANT_Fieldref :
2654     case JVM_CONSTANT_Methodref :
2655     case JVM_CONSTANT_InterfaceMethodref :
2656       st->print("klass_index=%d", uncached_klass_ref_index_at(cp_index));
2657       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(cp_index));
2658       break;
2659     case JVM_CONSTANT_String :
2660       unresolved_string_at(cp_index)->print_value_on(st);
2661       break;
2662     case JVM_CONSTANT_Integer :
2663       st->print("%d", int_at(cp_index));
2664       break;
2665     case JVM_CONSTANT_Float :
2666       st->print("%f", float_at(cp_index));
2667       break;
2668     case JVM_CONSTANT_Long :
2669       st->print_jlong(long_at(cp_index));
2670       break;
2671     case JVM_CONSTANT_Double :
2672       st->print("%lf", double_at(cp_index));
2673       break;
2674     case JVM_CONSTANT_NameAndType :
2675       st->print("name_index=%d", name_ref_index_at(cp_index));
2676       st->print(" signature_index=%d", signature_ref_index_at(cp_index));
2677       break;
2678     case JVM_CONSTANT_Utf8 :
2679       symbol_at(cp_index)->print_value_on(st);
2680       break;
2681     case JVM_CONSTANT_ClassIndex: {
2682         int name_index = *int_at_addr(cp_index);
2683         st->print("klass_index=%d ", name_index);
2684         symbol_at(name_index)->print_value_on(st);
2685       }
2686       break;
2687     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2688     case JVM_CONSTANT_UnresolvedClassInError: {
2689         CPKlassSlot kslot = klass_slot_at(cp_index);
2690         int resolved_klass_index = kslot.resolved_klass_index();
2691         int name_index = kslot.name_index();
2692         assert(tag_at(name_index).is_symbol(), "sanity");
2693         symbol_at(name_index)->print_value_on(st);
2694       }
2695       break;
2696     case JVM_CONSTANT_MethodHandle :
2697     case JVM_CONSTANT_MethodHandleInError :
2698       st->print("ref_kind=%d", method_handle_ref_kind_at(cp_index));
2699       st->print(" ref_index=%d", method_handle_index_at(cp_index));
2700       break;
2701     case JVM_CONSTANT_MethodType :
2702     case JVM_CONSTANT_MethodTypeInError :
2703       st->print("signature_index=%d", method_type_index_at(cp_index));
2704       break;
2705     case JVM_CONSTANT_Dynamic :
2706     case JVM_CONSTANT_DynamicInError :
2707       {
2708         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2709         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2710         int argc = bootstrap_argument_count_at(cp_index);
2711         if (argc > 0) {
2712           for (int arg_i = 0; arg_i < argc; arg_i++) {
2713             int arg = bootstrap_argument_index_at(cp_index, arg_i);
2714             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2715           }
2716           st->print("}");
2717         }
2718       }
2719       break;
2720     case JVM_CONSTANT_InvokeDynamic :
2721       {
2722         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2723         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2724         int argc = bootstrap_argument_count_at(cp_index);
2725         if (argc > 0) {
2726           for (int arg_i = 0; arg_i < argc; arg_i++) {
2727             int arg = bootstrap_argument_index_at(cp_index, arg_i);
2728             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2729           }
2730           st->print("}");
2731         }
2732       }
2733       break;
2734     default:
2735       ShouldNotReachHere();
2736       break;
2737   }
2738   st->cr();
2739 }
2740 
2741 void ConstantPool::print_value_on(outputStream* st) const {
2742   assert(is_constantPool(), "must be constantPool");
2743   st->print("constant pool [%d]", length());
2744   if (has_preresolution()) st->print("/preresolution");
2745   if (operands() != nullptr)  st->print("/operands[%d]", operands()->length());
2746   print_address_on(st);
2747   if (pool_holder() != nullptr) {
2748     st->print(" for ");
2749     pool_holder()->print_value_on(st);
2750     bool extra = (pool_holder()->constants() != this);
2751     if (extra)  st->print(" (extra)");
2752   }
2753   if (cache() != nullptr) {
2754     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2755   }
2756 }
2757 
2758 // Verification
2759 
2760 void ConstantPool::verify_on(outputStream* st) {
2761   guarantee(is_constantPool(), "object must be constant pool");
2762   for (int i = 0; i< length();  i++) {
2763     constantTag tag = tag_at(i);
2764     if (tag.is_klass() || tag.is_unresolved_klass()) {
2765       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2766     } else if (tag.is_symbol()) {
2767       Symbol* entry = symbol_at(i);
2768       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2769     } else if (tag.is_string()) {
2770       Symbol* entry = unresolved_string_at(i);
2771       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2772     }
2773   }
2774   if (pool_holder() != nullptr) {
2775     // Note: pool_holder() can be null in temporary constant pools
2776     // used during constant pool merging
2777     guarantee(pool_holder()->is_klass(),    "should be klass");
2778   }
2779 }