1 /*
   2  * Copyright (c) 1997, 2026, 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 "cds/aotConstantPoolResolver.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "cds/heapShared.inline.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/metadataOnStackMark.hpp"
  33 #include "classfile/stringTable.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "classfile/systemDictionaryShared.hpp"
  36 #include "classfile/vmClasses.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "code/codeCache.hpp"
  39 #include "interpreter/bootstrapInfo.hpp"
  40 #include "interpreter/linkResolver.hpp"
  41 #include "jvm.h"
  42 #include "logging/log.hpp"
  43 #include "logging/logStream.hpp"
  44 #include "memory/allocation.inline.hpp"
  45 #include "memory/metadataFactory.hpp"
  46 #include "memory/metaspaceClosure.hpp"
  47 #include "memory/oopFactory.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/array.hpp"
  51 #include "oops/constantPool.inline.hpp"
  52 #include "oops/cpCache.inline.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/flatArrayKlass.hpp"
  55 #include "oops/instanceKlass.hpp"
  56 #include "oops/klass.inline.hpp"
  57 #include "oops/objArrayKlass.hpp"
  58 #include "oops/objArrayOop.inline.hpp"
  59 #include "oops/oop.inline.hpp"
  60 #include "oops/oopCast.inline.hpp"
  61 #include "oops/refArrayOop.hpp"
  62 #include "oops/typeArrayOop.inline.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "runtime/atomicAccess.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() || CDSConfig::is_using_archive(), "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   bsm_entries().deallocate_contents(loader_data);
 138 
 139   release_C_heap_structures();
 140 
 141   // free tag array
 142   MetadataFactory::free_array<u1>(loader_data, tags());
 143   set_tags(nullptr);
 144 }
 145 
 146 void ConstantPool::release_C_heap_structures() {
 147   // walk constant pool and decrement symbol reference counts
 148   unreference_symbols();
 149 }
 150 
 151 void ConstantPool::metaspace_pointers_do(MetaspaceClosure* it) {
 152   log_trace(aot)("Iter(ConstantPool): %p", this);
 153 
 154   it->push(&_tags, MetaspaceClosure::_writable);
 155   it->push(&_cache);
 156   it->push(&_pool_holder);
 157   it->push(&bsm_entries().offsets());
 158   it->push(&bsm_entries().bootstrap_methods());
 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 refArrayOop 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 refArrayOop 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 oop_cast<refArrayOop>(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     refArrayOop stom = oopFactory::new_refArray(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       refArrayOop scratch_references = oopFactory::new_refArray(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 Unresolved 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   AtomicAccess::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 template <typename Function>
 290 void ConstantPool::iterate_archivable_resolved_references(Function function) {
 291   objArrayOop rr = resolved_references();
 292   if (rr != nullptr && cache() != nullptr && CDSConfig::is_dumping_method_handles()) {
 293     Array<ResolvedIndyEntry>* indy_entries = cache()->resolved_indy_entries();
 294     if (indy_entries != nullptr) {
 295       for (int i = 0; i < indy_entries->length(); i++) {
 296         ResolvedIndyEntry *rie = indy_entries->adr_at(i);
 297         if (rie->is_resolved() && AOTConstantPoolResolver::is_resolution_deterministic(this, rie->constant_pool_index())) {
 298           int rr_index = rie->resolved_references_index();
 299           assert(resolved_reference_at(rr_index) != nullptr, "must exist");
 300           function(rr_index);
 301 
 302           // Save the BSM as well (sometimes the JIT looks up the BSM it for replay)
 303           int indy_cp_index = rie->constant_pool_index();
 304           int bsm_mh_cp_index = bootstrap_method_ref_index_at(indy_cp_index);
 305           int bsm_rr_index = cp_to_object_index(bsm_mh_cp_index);
 306           assert(resolved_reference_at(bsm_rr_index) != nullptr, "must exist");
 307           function(bsm_rr_index);
 308         }
 309       }
 310     }
 311 
 312     Array<ResolvedMethodEntry>* method_entries = cache()->resolved_method_entries();
 313     if (method_entries != nullptr) {
 314       for (int i = 0; i < method_entries->length(); i++) {
 315         ResolvedMethodEntry* rme = method_entries->adr_at(i);
 316         const char* rejection_reason = nullptr;
 317         if (rme->is_resolved(Bytecodes::_invokehandle) && rme->has_appendix() &&
 318                                cache()->can_archive_resolved_method(this, rme, rejection_reason)) {
 319           int rr_index = rme->resolved_references_index();
 320           assert(resolved_reference_at(rr_index) != nullptr, "must exist");
 321           function(rr_index);
 322         }
 323       }
 324     }
 325   }
 326 }
 327 
 328 // Returns the _resolved_reference array after removing unarchivable items from it.
 329 // Returns null if this class is not supported, or _resolved_reference doesn't exist.
 330 refArrayOop ConstantPool::prepare_resolved_references_for_archiving() {
 331   if (_cache == nullptr) {
 332     return nullptr; // nothing to do
 333   }
 334 
 335   InstanceKlass *ik = pool_holder();
 336   if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
 337     // Archiving resolved references for classes from non-builtin loaders
 338     // is not yet supported.
 339     return nullptr;
 340   }
 341 
 342   refArrayOop rr = resolved_references();
 343   if (rr != nullptr) {
 344     ResourceMark rm;
 345     int rr_len = rr->length();
 346     GrowableArray<bool> keep_resolved_refs(rr_len, rr_len, false);
 347 
 348     iterate_archivable_resolved_references([&](int rr_index) {
 349       keep_resolved_refs.at_put(rr_index, true);
 350     });
 351 
 352     refArrayOop scratch_rr = HeapShared::scratch_resolved_references(this);
 353     Array<u2>* ref_map = reference_map();
 354     int ref_map_len = ref_map == nullptr ? 0 : ref_map->length();
 355     for (int i = 0; i < rr_len; i++) {
 356       oop obj = rr->obj_at(i);
 357       scratch_rr->obj_at_put(i, nullptr);
 358       if (obj != nullptr) {
 359         if (i < ref_map_len) {
 360           int index = object_to_cp_index(i);
 361           if (tag_at(index).is_string()) {
 362             assert(java_lang_String::is_instance(obj), "must be");
 363             if (!HeapShared::is_string_too_large_to_archive(obj)) {
 364               scratch_rr->obj_at_put(i, obj);
 365             }
 366             continue;
 367           }
 368         }
 369 
 370         if (keep_resolved_refs.at(i)) {
 371           scratch_rr->obj_at_put(i, obj);
 372         }
 373       }
 374     }
 375     return scratch_rr;
 376   }
 377   return rr;
 378 }
 379 #endif
 380 
 381 #if INCLUDE_CDS
 382 // CDS support. Create a new resolved_references array.
 383 void ConstantPool::restore_unshareable_info(TRAPS) {
 384   if (!_pool_holder->is_linked() && !_pool_holder->is_rewritten()) {
 385     return;
 386   }
 387   assert(is_constantPool(), "ensure C++ vtable is restored");
 388   assert(on_stack(), "should always be set for constant pools in AOT cache");
 389   assert(in_aot_cache(), "should always be set for constant pools in AOT cache");
 390   if (is_for_method_handle_intrinsic()) {
 391     // See the same check in remove_unshareable_info() below.
 392     assert(cache() == nullptr, "must not have cpCache");
 393     return;
 394   }
 395   assert(_cache != nullptr, "constant pool _cache should not be null");
 396 
 397   // Only create the new resolved references array if it hasn't been attempted before
 398   if (resolved_references() != nullptr) return;
 399 
 400   if (vmClasses::Object_klass_is_loaded()) {
 401     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
 402 #if INCLUDE_CDS_JAVA_HEAP
 403     if (HeapShared::is_archived_heap_in_use() &&
 404         _cache->archived_references() != nullptr) {
 405       oop archived = _cache->archived_references();
 406       // Create handle for the archived resolved reference array object
 407       HandleMark hm(THREAD);
 408       Handle refs_handle(THREAD, archived);
 409       set_resolved_references(loader_data->add_handle(refs_handle));
 410       _cache->clear_archived_references();
 411     } else
 412 #endif
 413     {
 414       // No mapped archived resolved reference array
 415       // Recreate the object array and add to ClassLoaderData.
 416       int map_length = resolved_reference_length();
 417       if (map_length > 0) {
 418         objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 419         HandleMark hm(THREAD);
 420         Handle refs_handle(THREAD, stom);  // must handleize.
 421         set_resolved_references(loader_data->add_handle(refs_handle));
 422       }
 423     }
 424   }
 425 
 426   if (CDSConfig::is_dumping_final_static_archive() && CDSConfig::is_dumping_heap() && resolved_references() != nullptr) {
 427     objArrayOop scratch_references = oopFactory::new_objArray(vmClasses::Object_klass(), resolved_references()->length(), CHECK);
 428     HeapShared::add_scratch_resolved_references(this, scratch_references);
 429   }
 430 }
 431 
 432 void ConstantPool::remove_unshareable_info() {
 433   // ConstantPools in AOT cache are in the RO region, so the _flags cannot be modified.
 434   // The _on_stack flag is used to prevent ConstantPools from deallocation during
 435   // class redefinition. Since such ConstantPools cannot be deallocated anyway,
 436   // we always set _on_stack to true to avoid having to change _flags during runtime.
 437   _flags |= (_on_stack | _in_aot_cache);
 438 
 439   if (is_for_method_handle_intrinsic()) {
 440     // This CP was created by Method::make_method_handle_intrinsic() and has nothing
 441     // that need to be removed/restored. It has no cpCache since the intrinsic methods
 442     // don't have any bytecodes.
 443     assert(cache() == nullptr, "must not have cpCache");
 444     return;
 445   }
 446 
 447   bool update_resolved_reference = true;
 448   if (CDSConfig::is_dumping_final_static_archive()) {
 449     ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 450     InstanceKlass* src_holder = src_cp->pool_holder();
 451     if (src_holder->defined_by_other_loaders()) {
 452       // Unregistered classes are not loaded in the AOT assembly phase. The resolved reference length
 453       // is already saved during the training run.
 454       precond(!src_holder->is_loaded());
 455       precond(resolved_reference_length() >= 0);
 456       precond(resolved_references() == nullptr);
 457       update_resolved_reference = false;
 458     }
 459   }
 460 
 461   // resolved_references(): remember its length. If it cannot be restored
 462   // from the archived heap objects at run time, we need to dynamically allocate it.
 463   if (update_resolved_reference && cache() != nullptr) {
 464     set_resolved_reference_length(
 465         resolved_references() != nullptr ? resolved_references()->length() : 0);
 466     set_resolved_references(OopHandle());
 467   }
 468   remove_unshareable_entries();
 469 }
 470 
 471 static const char* get_type(Klass* k) {
 472   const char* type;
 473   Klass* src_k;
 474   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(k)) {
 475     src_k = ArchiveBuilder::current()->get_source_addr(k);
 476   } else {
 477     src_k = k;
 478   }
 479 
 480   if (src_k->is_objArray_klass()) {
 481     src_k = ObjArrayKlass::cast(src_k)->bottom_klass();
 482     assert(!src_k->is_objArray_klass(), "sanity");
 483     assert(src_k->is_instance_klass() || src_k->is_typeArray_klass(), "Sanity check");
 484   }
 485 
 486   if (src_k->is_typeArray_klass()) {
 487     type = "prim";
 488   } else {
 489     InstanceKlass* src_ik = InstanceKlass::cast(src_k);
 490     if (src_ik->defined_by_boot_loader()) {
 491       return "boot";
 492     } else if (src_ik->defined_by_platform_loader()) {
 493       return "plat";
 494     } else if (src_ik->defined_by_app_loader()) {
 495       return "app";
 496     } else {
 497       return "unreg";
 498     }
 499   }
 500 
 501   return type;
 502 }
 503 
 504 void ConstantPool::remove_unshareable_entries() {
 505   ResourceMark rm;
 506   log_info(aot, resolve)("Archiving CP entries for %s", pool_holder()->name()->as_C_string());
 507   for (int cp_index = 1; cp_index < length(); cp_index++) { // cp_index 0 is unused
 508     int cp_tag = tag_at(cp_index).value();
 509     switch (cp_tag) {
 510     case JVM_CONSTANT_UnresolvedClass:
 511       ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false, false);
 512       break;
 513     case JVM_CONSTANT_UnresolvedClassInError:
 514       tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
 515       ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false, true);
 516       break;
 517     case JVM_CONSTANT_MethodHandleInError:
 518       tag_at_put(cp_index, JVM_CONSTANT_MethodHandle);
 519       break;
 520     case JVM_CONSTANT_MethodTypeInError:
 521       tag_at_put(cp_index, JVM_CONSTANT_MethodType);
 522       break;
 523     case JVM_CONSTANT_DynamicInError:
 524       tag_at_put(cp_index, JVM_CONSTANT_Dynamic);
 525       break;
 526     case JVM_CONSTANT_Class:
 527       remove_resolved_klass_if_non_deterministic(cp_index);
 528       break;
 529     default:
 530       break;
 531     }
 532   }
 533 
 534   if (cache() != nullptr) {
 535     // cache() is null if this class is not yet linked.
 536     cache()->remove_unshareable_info();
 537   }
 538 }
 539 
 540 void ConstantPool::remove_resolved_klass_if_non_deterministic(int cp_index) {
 541   assert(ArchiveBuilder::current()->is_in_buffer_space(this), "must be");
 542   assert(tag_at(cp_index).is_klass(), "must be resolved");
 543 
 544   bool can_archive;
 545   Klass* k = nullptr;
 546 
 547   if (CDSConfig::is_dumping_preimage_static_archive()) {
 548     can_archive = false;
 549   } else {
 550     k = resolved_klass_at(cp_index);
 551     if (k == nullptr) {
 552       // We'd come here if the referenced class has been excluded via
 553       // SystemDictionaryShared::is_excluded_class(). As a result, ArchiveBuilder
 554       // has cleared the resolved_klasses()->at(...) pointer to null. Thus, we
 555       // need to revert the tag to JVM_CONSTANT_UnresolvedClass.
 556       can_archive = false;
 557     } else {
 558       ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 559       can_archive = AOTConstantPoolResolver::is_resolution_deterministic(src_cp, cp_index);
 560     }
 561   }
 562 
 563   if (!can_archive) {
 564     int resolved_klass_index = klass_slot_at(cp_index).resolved_klass_index();
 565     // This might be at a safepoint but do this in the right order.
 566     tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
 567     resolved_klasses()->at_put(resolved_klass_index, nullptr);
 568   }
 569 
 570   LogStreamHandle(Trace, aot, resolve) log;
 571   if (log.is_enabled()) {
 572     ResourceMark rm;
 573     log.print("%s klass  CP entry [%3d]: %s %s",
 574               (can_archive ? "archived" : "reverted"),
 575               cp_index, pool_holder()->name()->as_C_string(), get_type(pool_holder()));
 576     if (can_archive) {
 577       log.print(" => %s %s%s", k->name()->as_C_string(), get_type(k),
 578                 (!k->is_instance_klass() || pool_holder()->is_subtype_of(k)) ? "" : " (not supertype)");
 579     } else {
 580       Symbol* name = klass_name_at(cp_index);
 581       log.print(" => %s", name->as_C_string());
 582     }
 583   }
 584 
 585   ArchiveBuilder::alloc_stats()->record_klass_cp_entry(can_archive, /*reverted=*/!can_archive);
 586 }
 587 #endif // INCLUDE_CDS
 588 
 589 int ConstantPool::cp_to_object_index(int cp_index) {
 590   // this is harder don't do this so much.
 591   int i = reference_map()->find(checked_cast<u2>(cp_index));
 592   // We might not find the index for jsr292 call.
 593   return (i < 0) ? _no_index_sentinel : i;
 594 }
 595 
 596 void ConstantPool::string_at_put(int obj_index, oop str) {
 597   oop result = set_resolved_reference_at(obj_index, str);
 598   assert(result == nullptr || result == str, "Only set once or to the same string.");
 599 }
 600 
 601 void ConstantPool::trace_class_resolution(const constantPoolHandle& this_cp, Klass* k) {
 602   ResourceMark rm;
 603   int line_number = -1;
 604   const char * source_file = nullptr;
 605   if (JavaThread::current()->has_last_Java_frame()) {
 606     // try to identify the method which called this function.
 607     vframeStream vfst(JavaThread::current());
 608     if (!vfst.at_end()) {
 609       line_number = vfst.method()->line_number_from_bci(vfst.bci());
 610       Symbol* s = vfst.method()->method_holder()->source_file_name();
 611       if (s != nullptr) {
 612         source_file = s->as_C_string();
 613       }
 614     }
 615   }
 616   if (k != this_cp->pool_holder()) {
 617     // only print something if the classes are different
 618     if (source_file != nullptr) {
 619       log_debug(class, resolve)("%s %s %s:%d",
 620                  this_cp->pool_holder()->external_name(),
 621                  k->external_name(), source_file, line_number);
 622     } else {
 623       log_debug(class, resolve)("%s %s",
 624                  this_cp->pool_holder()->external_name(),
 625                  k->external_name());
 626     }
 627   }
 628 }
 629 
 630 Klass* ConstantPool::klass_at_impl(const constantPoolHandle& this_cp, int cp_index,
 631                                    TRAPS) {
 632   JavaThread* javaThread = THREAD;
 633 
 634   // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
 635   // It is not safe to rely on the tag bit's here, since we don't have a lock, and
 636   // the entry and tag is not updated atomically.
 637   CPKlassSlot kslot = this_cp->klass_slot_at(cp_index);
 638   int resolved_klass_index = kslot.resolved_klass_index();
 639   int name_index = kslot.name_index();
 640   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 641 
 642   // The tag must be JVM_CONSTANT_Class in order to read the correct value from
 643   // the unresolved_klasses() array.
 644   if (this_cp->tag_at(cp_index).is_klass()) {
 645     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 646     assert(klass != nullptr, "must be resolved");
 647     return klass;
 648   }
 649 
 650   // This tag doesn't change back to unresolved class unless at a safepoint.
 651   if (this_cp->tag_at(cp_index).is_unresolved_klass_in_error()) {
 652     // The original attempt to resolve this constant pool entry failed so find the
 653     // class of the original error and throw another error of the same class
 654     // (JVMS 5.4.3).
 655     // If there is a detail message, pass that detail message to the error.
 656     // The JVMS does not strictly require us to duplicate the same detail message,
 657     // or any internal exception fields such as cause or stacktrace.  But since the
 658     // detail message is often a class name or other literal string, we will repeat it
 659     // if we can find it in the symbol table.
 660     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
 661     ShouldNotReachHere();
 662   }
 663 
 664   HandleMark hm(THREAD);
 665   Handle mirror_handle;
 666   Symbol* name = this_cp->symbol_at(name_index);
 667   Handle loader (THREAD, this_cp->pool_holder()->class_loader());
 668 
 669   Klass* k;
 670   {
 671     // Turn off the single stepping while doing class resolution
 672     JvmtiHideSingleStepping jhss(javaThread);
 673     k = SystemDictionary::resolve_or_fail(name, loader, true, THREAD);
 674   } //  JvmtiHideSingleStepping jhss(javaThread);
 675 
 676   if (!HAS_PENDING_EXCEPTION) {
 677     // preserve the resolved klass from unloading
 678     mirror_handle = Handle(THREAD, k->java_mirror());
 679     // Do access check for klasses
 680     verify_constant_pool_resolve(this_cp, k, THREAD);
 681   }
 682 
 683 #ifdef DEBUG
 684   if (!HAS_PENDING_EXCEPTION && k->is_objArray_klass()) {
 685     Klass* bottom_klass = ObjArrayKlass::cast(k)->bottom_klass();
 686     assert(bottom_klass != nullptr, "Should be set");
 687     assert(bottom_klass->is_instance_klass() || bottom_klass->is_typeArray_klass(), "Sanity check");
 688   }
 689 #endif
 690 
 691   // Failed to resolve class. We must record the errors so that subsequent attempts
 692   // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
 693   if (HAS_PENDING_EXCEPTION) {
 694     save_and_throw_exception(this_cp, cp_index, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_NULL);
 695     // If CHECK_NULL above doesn't return the exception, that means that
 696     // some other thread has beaten us and has resolved the class.
 697     // To preserve old behavior, we return the resolved class.
 698     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 699     assert(klass != nullptr, "must be resolved if exception was cleared");
 700     return klass;
 701   }
 702 
 703   // logging for class+resolve.
 704   if (log_is_enabled(Debug, class, resolve)){
 705     trace_class_resolution(this_cp, k);
 706   }
 707 
 708   // The interpreter assumes when the tag is stored, the klass is resolved
 709   // and the Klass* stored in _resolved_klasses is non-null, so we need
 710   // hardware store ordering here.
 711   // We also need to CAS to not overwrite an error from a racing thread.
 712   Klass** adr = this_cp->resolved_klasses()->adr_at(resolved_klass_index);
 713   AtomicAccess::release_store(adr, k);
 714 
 715   jbyte old_tag = AtomicAccess::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
 716                                         (jbyte)JVM_CONSTANT_UnresolvedClass,
 717                                         (jbyte)JVM_CONSTANT_Class);
 718 
 719   // We need to recheck exceptions from racing thread and return the same.
 720   if (old_tag == JVM_CONSTANT_UnresolvedClassInError) {
 721     // Remove klass.
 722     AtomicAccess::store(adr, (Klass*)nullptr);
 723     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
 724   }
 725 
 726   return k;
 727 }
 728 
 729 
 730 // Does not update ConstantPool* - to avoid any exception throwing. Used
 731 // by compiler and exception handling.  Also used to avoid classloads for
 732 // instanceof operations. Returns null if the class has not been loaded or
 733 // if the verification of constant pool failed
 734 Klass* ConstantPool::klass_at_if_loaded(const constantPoolHandle& this_cp, int which) {
 735   CPKlassSlot kslot = this_cp->klass_slot_at(which);
 736   int resolved_klass_index = kslot.resolved_klass_index();
 737   int name_index = kslot.name_index();
 738   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 739 
 740   if (this_cp->tag_at(which).is_klass()) {
 741     Klass* k = this_cp->resolved_klasses()->at(resolved_klass_index);
 742     assert(k != nullptr, "must be resolved");
 743     return k;
 744   } else if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
 745     return nullptr;
 746   } else {
 747     Thread* current = Thread::current();
 748     HandleMark hm(current);
 749     Symbol* name = this_cp->symbol_at(name_index);
 750     oop loader = this_cp->pool_holder()->class_loader();
 751     Handle h_loader (current, loader);
 752     Klass* k = SystemDictionary::find_instance_klass(current, name, h_loader);
 753 
 754     // Avoid constant pool verification at a safepoint, as it takes the Module_lock.
 755     if (k != nullptr && current->is_Java_thread()) {
 756       // Make sure that resolving is legal
 757       JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 758       ExceptionMark em(THREAD);
 759       // return null if verification fails
 760       verify_constant_pool_resolve(this_cp, k, THREAD);
 761       if (HAS_PENDING_EXCEPTION) {
 762         CLEAR_PENDING_EXCEPTION;
 763         return nullptr;
 764       }
 765       return k;
 766     } else {
 767       return k;
 768     }
 769   }
 770 }
 771 
 772 Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,
 773                                                    int which) {
 774   if (cpool->cache() == nullptr)  return nullptr;  // nothing to load yet
 775   if (!(which >= 0 && which < cpool->resolved_method_entries_length())) {
 776     // FIXME: should be an assert
 777     log_debug(class, resolve)("bad BSM %d in:", which); cpool->print();
 778     return nullptr;
 779   }
 780   return cpool->cache()->method_if_resolved(which);
 781 }
 782 
 783 
 784 bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 785   if (cpool->cache() == nullptr)  return false;  // nothing to load yet
 786   if (code == Bytecodes::_invokedynamic) {
 787     return cpool->resolved_indy_entry_at(which)->has_appendix();
 788   } else {
 789     return cpool->resolved_method_entry_at(which)->has_appendix();
 790   }
 791 }
 792 
 793 oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 794   if (cpool->cache() == nullptr)  return nullptr;  // nothing to load yet
 795   if (code == Bytecodes::_invokedynamic) {
 796     return cpool->resolved_reference_from_indy(which);
 797   } else {
 798     return cpool->cache()->appendix_if_resolved(which);
 799   }
 800 }
 801 
 802 
 803 bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
 804   if (cpool->cache() == nullptr)  return false;  // nothing to load yet
 805   if (code == Bytecodes::_invokedynamic) {
 806     return cpool->resolved_indy_entry_at(which)->has_local_signature();
 807   } else {
 808     return cpool->resolved_method_entry_at(which)->has_local_signature();
 809   }
 810 }
 811 
 812 // Translate index, which could be CPCache index or Indy index, to a constant pool index
 813 int ConstantPool::to_cp_index(int index, Bytecodes::Code code) {
 814   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
 815   switch(code) {
 816     case Bytecodes::_invokedynamic:
 817       return invokedynamic_bootstrap_ref_index_at(index);
 818     case Bytecodes::_getfield:
 819     case Bytecodes::_getstatic:
 820     case Bytecodes::_putfield:
 821     case Bytecodes::_putstatic:
 822       return resolved_field_entry_at(index)->constant_pool_index();
 823     case Bytecodes::_invokeinterface:
 824     case Bytecodes::_invokehandle:
 825     case Bytecodes::_invokespecial:
 826     case Bytecodes::_invokestatic:
 827     case Bytecodes::_invokevirtual:
 828     case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
 829       return resolved_method_entry_at(index)->constant_pool_index();
 830     default:
 831       fatal("Unexpected bytecode: %s", Bytecodes::name(code));
 832   }
 833 }
 834 
 835 bool ConstantPool::is_resolved(int index, Bytecodes::Code code) {
 836   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
 837   switch(code) {
 838     case Bytecodes::_invokedynamic:
 839       return resolved_indy_entry_at(index)->is_resolved();
 840 
 841     case Bytecodes::_getfield:
 842     case Bytecodes::_getstatic:
 843     case Bytecodes::_putfield:
 844     case Bytecodes::_putstatic:
 845       return resolved_field_entry_at(index)->is_resolved(code);
 846 
 847     case Bytecodes::_invokeinterface:
 848     case Bytecodes::_invokehandle:
 849     case Bytecodes::_invokespecial:
 850     case Bytecodes::_invokestatic:
 851     case Bytecodes::_invokevirtual:
 852     case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
 853       return resolved_method_entry_at(index)->is_resolved(code);
 854 
 855     default:
 856       fatal("Unexpected bytecode: %s", Bytecodes::name(code));
 857   }
 858 }
 859 
 860 u2 ConstantPool::uncached_name_and_type_ref_index_at(int cp_index)  {
 861   if (tag_at(cp_index).has_bootstrap()) {
 862     u2 pool_index = bootstrap_name_and_type_ref_index_at(cp_index);
 863     assert(tag_at(pool_index).is_name_and_type(), "");
 864     return pool_index;
 865   }
 866   assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
 867   assert(!tag_at(cp_index).has_bootstrap(), "Must be handled above");
 868   jint ref_index = *int_at_addr(cp_index);
 869   return extract_high_short_from_int(ref_index);
 870 }
 871 
 872 u2 ConstantPool::name_and_type_ref_index_at(int index, Bytecodes::Code code) {
 873   return uncached_name_and_type_ref_index_at(to_cp_index(index, code));
 874 }
 875 
 876 constantTag ConstantPool::tag_ref_at(int which, Bytecodes::Code code) {
 877   // which may be either a Constant Pool index or a rewritten index
 878   int pool_index = which;
 879   assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
 880   pool_index = to_cp_index(which, code);
 881   return tag_at(pool_index);
 882 }
 883 
 884 u2 ConstantPool::uncached_klass_ref_index_at(int cp_index) {
 885   assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
 886   jint ref_index = *int_at_addr(cp_index);
 887   return extract_low_short_from_int(ref_index);
 888 }
 889 
 890 u2 ConstantPool::klass_ref_index_at(int index, Bytecodes::Code code) {
 891   assert(code != Bytecodes::_invokedynamic,
 892             "an invokedynamic instruction does not have a klass");
 893   return uncached_klass_ref_index_at(to_cp_index(index, code));
 894 }
 895 
 896 void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {
 897   if (!(k->is_instance_klass() || k->is_objArray_klass())) {
 898     return;  // short cut, typeArray klass is always accessible
 899   }
 900   Klass* holder = this_cp->pool_holder();
 901   LinkResolver::check_klass_accessibility(holder, k, CHECK);
 902 }
 903 
 904 
 905 u2 ConstantPool::name_ref_index_at(int cp_index) {
 906   jint ref_index = name_and_type_at(cp_index);
 907   return extract_low_short_from_int(ref_index);
 908 }
 909 
 910 
 911 u2 ConstantPool::signature_ref_index_at(int cp_index) {
 912   jint ref_index = name_and_type_at(cp_index);
 913   return extract_high_short_from_int(ref_index);
 914 }
 915 
 916 
 917 Klass* ConstantPool::klass_ref_at(int which, Bytecodes::Code code, TRAPS) {
 918   return klass_at(klass_ref_index_at(which, code), THREAD);
 919 }
 920 
 921 Symbol* ConstantPool::klass_name_at(int cp_index) const {
 922   return symbol_at(klass_slot_at(cp_index).name_index());
 923 }
 924 
 925 Symbol* ConstantPool::klass_ref_at_noresolve(int which, Bytecodes::Code code) {
 926   jint ref_index = klass_ref_index_at(which, code);
 927   return klass_at_noresolve(ref_index);
 928 }
 929 
 930 Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int cp_index) {
 931   jint ref_index = uncached_klass_ref_index_at(cp_index);
 932   return klass_at_noresolve(ref_index);
 933 }
 934 
 935 char* ConstantPool::string_at_noresolve(int cp_index) {
 936   return unresolved_string_at(cp_index)->as_C_string();
 937 }
 938 
 939 BasicType ConstantPool::basic_type_for_signature_at(int cp_index) const {
 940   return Signature::basic_type(symbol_at(cp_index));
 941 }
 942 
 943 
 944 void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {
 945   for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused
 946     if (this_cp->tag_at(index).is_string()) {
 947       this_cp->string_at(index, CHECK);
 948     }
 949   }
 950 }
 951 
 952 static const char* exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {
 953   // Note: caller needs ResourceMark
 954 
 955   // Dig out the detailed message to reuse if possible
 956   const char* msg = java_lang_Throwable::message_as_utf8(pending_exception);
 957   if (msg != nullptr) {
 958     return msg;
 959   }
 960 
 961   Symbol* message = nullptr;
 962   // Return specific message for the tag
 963   switch (tag.value()) {
 964   case JVM_CONSTANT_UnresolvedClass:
 965     // return the class name in the error message
 966     message = this_cp->klass_name_at(which);
 967     break;
 968   case JVM_CONSTANT_MethodHandle:
 969     // return the method handle name in the error message
 970     message = this_cp->method_handle_name_ref_at(which);
 971     break;
 972   case JVM_CONSTANT_MethodType:
 973     // return the method type signature in the error message
 974     message = this_cp->method_type_signature_at(which);
 975     break;
 976   case JVM_CONSTANT_Dynamic:
 977     // return the name of the condy in the error message
 978     message = this_cp->uncached_name_ref_at(which);
 979     break;
 980   default:
 981     ShouldNotReachHere();
 982   }
 983 
 984   return message != nullptr ? message->as_C_string() : nullptr;
 985 }
 986 
 987 static void add_resolution_error(JavaThread* current, const constantPoolHandle& this_cp, int which,
 988                                  constantTag tag, oop pending_exception) {
 989 
 990   ResourceMark rm(current);
 991   Symbol* error = pending_exception->klass()->name();
 992   oop cause = java_lang_Throwable::cause(pending_exception);
 993 
 994   // Also dig out the exception cause, if present.
 995   Symbol* cause_sym = nullptr;
 996   const char* cause_msg = nullptr;
 997   if (cause != nullptr && cause != pending_exception) {
 998     cause_sym = cause->klass()->name();
 999     cause_msg = java_lang_Throwable::message_as_utf8(cause);
1000   }
1001 
1002   const char* message = exception_message(this_cp, which, tag, pending_exception);
1003   SystemDictionary::add_resolution_error(this_cp, which, error, message, cause_sym, cause_msg);
1004 }
1005 
1006 
1007 void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {
1008   ResourceMark rm(THREAD);
1009   const char* message = nullptr;
1010   Symbol* cause = nullptr;
1011   const char* cause_msg = nullptr;
1012   Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message, &cause, &cause_msg);
1013   assert(error != nullptr, "checking");
1014 
1015   CLEAR_PENDING_EXCEPTION;
1016   if (message != nullptr) {
1017     if (cause != nullptr) {
1018       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1019       THROW_MSG_CAUSE(error, message, h_cause);
1020     } else {
1021       THROW_MSG(error, message);
1022     }
1023   } else {
1024     if (cause != nullptr) {
1025       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1026       THROW_CAUSE(error, h_cause);
1027     } else {
1028       THROW(error);
1029     }
1030   }
1031 }
1032 
1033 // If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the
1034 // exception in the resolution error table, so that the same exception is thrown again.
1035 void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int cp_index,
1036                                             constantTag tag, TRAPS) {
1037 
1038   int error_tag = tag.error_value();
1039 
1040   if (!PENDING_EXCEPTION->
1041     is_a(vmClasses::LinkageError_klass())) {
1042     // Just throw the exception and don't prevent these classes from
1043     // being loaded due to virtual machine errors like StackOverflow
1044     // and OutOfMemoryError, etc, or if the thread was hit by stop()
1045     // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
1046   } else if (this_cp->tag_at(cp_index).value() != error_tag) {
1047     add_resolution_error(THREAD, this_cp, cp_index, tag, PENDING_EXCEPTION);
1048     // CAS in the tag.  If a thread beat us to registering this error that's fine.
1049     // If another thread resolved the reference, this is a race condition. This
1050     // thread may have had a security manager or something temporary.
1051     // This doesn't deterministically get an error.   So why do we save this?
1052     // We save this because jvmti can add classes to the bootclass path after
1053     // this error, so it needs to get the same error if the error is first.
1054     jbyte old_tag = AtomicAccess::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
1055                                           (jbyte)tag.value(),
1056                                           (jbyte)error_tag);
1057     if (old_tag != error_tag && old_tag != tag.value()) {
1058       // MethodHandles and MethodType doesn't change to resolved version.
1059       assert(this_cp->tag_at(cp_index).is_klass(), "Wrong tag value");
1060       // Forget the exception and use the resolved class.
1061       CLEAR_PENDING_EXCEPTION;
1062     }
1063   } else {
1064     // some other thread put this in error state
1065     throw_resolution_error(this_cp, cp_index, CHECK);
1066   }
1067 }
1068 
1069 constantTag ConstantPool::constant_tag_at(int cp_index) {
1070   constantTag tag = tag_at(cp_index);
1071   if (tag.is_dynamic_constant()) {
1072     BasicType bt = basic_type_for_constant_at(cp_index);
1073     return constantTag(constantTag::type2tag(bt));
1074   }
1075   return tag;
1076 }
1077 
1078 BasicType ConstantPool::basic_type_for_constant_at(int cp_index) {
1079   constantTag tag = tag_at(cp_index);
1080   if (tag.is_dynamic_constant() ||
1081       tag.is_dynamic_constant_in_error()) {
1082     // have to look at the signature for this one
1083     Symbol* constant_type = uncached_signature_ref_at(cp_index);
1084     return Signature::basic_type(constant_type);
1085   }
1086   return tag.basic_type();
1087 }
1088 
1089 // Called to resolve constants in the constant pool and return an oop.
1090 // Some constant pool entries cache their resolved oop. This is also
1091 // called to create oops from constants to use in arguments for invokedynamic
1092 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
1093                                            int cp_index, int cache_index,
1094                                            bool* status_return, TRAPS) {
1095   oop result_oop = nullptr;
1096 
1097   if (cache_index == _possible_index_sentinel) {
1098     // It is possible that this constant is one which is cached in the objects.
1099     // We'll do a linear search.  This should be OK because this usage is rare.
1100     // FIXME: If bootstrap specifiers stress this code, consider putting in
1101     // a reverse index.  Binary search over a short array should do it.
1102     assert(cp_index > 0, "valid constant pool index");
1103     cache_index = this_cp->cp_to_object_index(cp_index);
1104   }
1105   assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
1106   assert(cp_index == _no_index_sentinel || cp_index >= 0, "");
1107 
1108   if (cache_index >= 0) {
1109     result_oop = this_cp->resolved_reference_at(cache_index);
1110     if (result_oop != nullptr) {
1111       if (result_oop == Universe::the_null_sentinel()) {
1112         DEBUG_ONLY(int temp_index = (cp_index >= 0 ? cp_index : this_cp->object_to_cp_index(cache_index)));
1113         assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
1114         result_oop = nullptr;
1115       }
1116       if (status_return != nullptr)  (*status_return) = true;
1117       return result_oop;
1118       // That was easy...
1119     }
1120     cp_index = this_cp->object_to_cp_index(cache_index);
1121   }
1122 
1123   jvalue prim_value;  // temp used only in a few cases below
1124 
1125   constantTag tag = this_cp->tag_at(cp_index);
1126 
1127   if (status_return != nullptr) {
1128     // don't trigger resolution if the constant might need it
1129     switch (tag.value()) {
1130     case JVM_CONSTANT_Class:
1131       assert(this_cp->resolved_klass_at(cp_index) != nullptr, "must be resolved");
1132       break;
1133     case JVM_CONSTANT_String:
1134     case JVM_CONSTANT_Integer:
1135     case JVM_CONSTANT_Float:
1136     case JVM_CONSTANT_Long:
1137     case JVM_CONSTANT_Double:
1138       // these guys trigger OOM at worst
1139       break;
1140     default:
1141       (*status_return) = false;
1142       return nullptr;
1143     }
1144     // from now on there is either success or an OOME
1145     (*status_return) = true;
1146   }
1147 
1148   switch (tag.value()) {
1149 
1150   case JVM_CONSTANT_UnresolvedClass:
1151   case JVM_CONSTANT_Class:
1152     {
1153       assert(cache_index == _no_index_sentinel, "should not have been set");
1154       Klass* resolved = klass_at_impl(this_cp, cp_index, CHECK_NULL);
1155       // ldc wants the java mirror.
1156       result_oop = resolved->java_mirror();
1157       break;
1158     }
1159 
1160   case JVM_CONSTANT_Dynamic:
1161     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_invokedynamic_time(),
1162                                 ClassLoader::perf_resolve_invokedynamic_count());
1163 
1164       // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
1165       BootstrapInfo bootstrap_specifier(this_cp, cp_index);
1166 
1167       // The initial step in resolving an unresolved symbolic reference to a
1168       // dynamically-computed constant is to resolve the symbolic reference to a
1169       // method handle which will be the bootstrap method for the dynamically-computed
1170       // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
1171       // method fails, then a MethodHandleInError is stored at the corresponding
1172       // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
1173       // set a DynamicConstantInError here since any subsequent use of this
1174       // bootstrap method will encounter the resolution of MethodHandleInError.
1175       // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
1176       // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
1177       // for the bootstrap_specifier created above.
1178       SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1179       Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);
1180       if (HAS_PENDING_EXCEPTION) {
1181         // Resolution failure of the dynamically-computed constant, save_and_throw_exception
1182         // will check for a LinkageError and store a DynamicConstantInError.
1183         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1184       }
1185       result_oop = bootstrap_specifier.resolved_value()();
1186       BasicType type = Signature::basic_type(bootstrap_specifier.signature());
1187       if (!is_reference_type(type)) {
1188         // Make sure the primitive value is properly boxed.
1189         // This is a JDK responsibility.
1190         const char* fail = nullptr;
1191         if (result_oop == nullptr) {
1192           fail = "null result instead of box";
1193         } else if (!is_java_primitive(type)) {
1194           // FIXME: support value types via unboxing
1195           fail = "can only handle references and primitives";
1196         } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
1197           fail = "primitive is not properly boxed";
1198         }
1199         if (fail != nullptr) {
1200           // Since this exception is not a LinkageError, throw exception
1201           // but do not save a DynamicInError resolution result.
1202           // See section 5.4.3 of the VM spec.
1203           THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
1204         }
1205       }
1206 
1207       LogTarget(Debug, methodhandles, condy) lt_condy;
1208       if (lt_condy.is_enabled()) {
1209         LogStream ls(lt_condy);
1210         bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");
1211       }
1212       break;
1213     }
1214 
1215   case JVM_CONSTANT_String:
1216     assert(cache_index != _no_index_sentinel, "should have been set");
1217     result_oop = string_at_impl(this_cp, cp_index, cache_index, CHECK_NULL);
1218     break;
1219 
1220   case JVM_CONSTANT_MethodHandle:
1221     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_handle_time(),
1222                                 ClassLoader::perf_resolve_method_handle_count());
1223 
1224       int ref_kind                 = this_cp->method_handle_ref_kind_at(cp_index);
1225       int callee_index             = this_cp->method_handle_klass_index_at(cp_index);
1226       Symbol*  name =      this_cp->method_handle_name_ref_at(cp_index);
1227       Symbol*  signature = this_cp->method_handle_signature_ref_at(cp_index);
1228       constantTag m_tag  = this_cp->tag_at(this_cp->method_handle_index_at(cp_index));
1229       { ResourceMark rm(THREAD);
1230         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1231                               ref_kind, cp_index, this_cp->method_handle_index_at(cp_index),
1232                               callee_index, name->as_C_string(), signature->as_C_string());
1233       }
1234 
1235       Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);
1236       if (HAS_PENDING_EXCEPTION) {
1237         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1238       }
1239 
1240       // Check constant pool method consistency
1241       if ((callee->is_interface() && m_tag.is_method()) ||
1242           (!callee->is_interface() && m_tag.is_interface_method())) {
1243         ResourceMark rm(THREAD);
1244         stringStream ss;
1245         ss.print("Inconsistent constant pool data in classfile for class %s. "
1246                  "Method '", callee->name()->as_C_string());
1247         signature->print_as_signature_external_return_type(&ss);
1248         ss.print(" %s(", name->as_C_string());
1249         signature->print_as_signature_external_parameters(&ss);
1250         ss.print(")' at index %d is %s and should be %s",
1251                  cp_index,
1252                  callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1253                  callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1254         // Names are all known to be < 64k so we know this formatted message is not excessively large.
1255         Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());
1256         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1257       }
1258 
1259       Klass* klass = this_cp->pool_holder();
1260       HandleMark hm(THREAD);
1261       Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1262                                                                    callee, name, signature,
1263                                                                    THREAD);
1264       if (HAS_PENDING_EXCEPTION) {
1265         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1266       }
1267       result_oop = value();
1268       break;
1269     }
1270 
1271   case JVM_CONSTANT_MethodType:
1272     { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_type_time(),
1273                                 ClassLoader::perf_resolve_method_type_count());
1274 
1275       Symbol*  signature = this_cp->method_type_signature_at(cp_index);
1276       { ResourceMark rm(THREAD);
1277         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1278                               cp_index, this_cp->method_type_index_at(cp_index),
1279                               signature->as_C_string());
1280       }
1281       Klass* klass = this_cp->pool_holder();
1282       HandleMark hm(THREAD);
1283       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1284       result_oop = value();
1285       if (HAS_PENDING_EXCEPTION) {
1286         save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1287       }
1288       break;
1289     }
1290 
1291   case JVM_CONSTANT_Integer:
1292     assert(cache_index == _no_index_sentinel, "should not have been set");
1293     prim_value.i = this_cp->int_at(cp_index);
1294     result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1295     break;
1296 
1297   case JVM_CONSTANT_Float:
1298     assert(cache_index == _no_index_sentinel, "should not have been set");
1299     prim_value.f = this_cp->float_at(cp_index);
1300     result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1301     break;
1302 
1303   case JVM_CONSTANT_Long:
1304     assert(cache_index == _no_index_sentinel, "should not have been set");
1305     prim_value.j = this_cp->long_at(cp_index);
1306     result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1307     break;
1308 
1309   case JVM_CONSTANT_Double:
1310     assert(cache_index == _no_index_sentinel, "should not have been set");
1311     prim_value.d = this_cp->double_at(cp_index);
1312     result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1313     break;
1314 
1315   case JVM_CONSTANT_UnresolvedClassInError:
1316   case JVM_CONSTANT_DynamicInError:
1317   case JVM_CONSTANT_MethodHandleInError:
1318   case JVM_CONSTANT_MethodTypeInError:
1319     throw_resolution_error(this_cp, cp_index, CHECK_NULL);
1320     break;
1321 
1322   default:
1323     fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), cp_index, cache_index, tag.value());
1324     break;
1325   }
1326 
1327   if (cache_index >= 0) {
1328     // Benign race condition:  resolved_references may already be filled in.
1329     // The important thing here is that all threads pick up the same result.
1330     // It doesn't matter which racing thread wins, as long as only one
1331     // result is used by all threads, and all future queries.
1332     oop new_result = (result_oop == nullptr ? Universe::the_null_sentinel() : result_oop);
1333     oop old_result = this_cp->set_resolved_reference_at(cache_index, new_result);
1334     if (old_result == nullptr) {
1335       return result_oop;  // was installed
1336     } else {
1337       // Return the winning thread's result.  This can be different than
1338       // the result here for MethodHandles.
1339       if (old_result == Universe::the_null_sentinel())
1340         old_result = nullptr;
1341       return old_result;
1342     }
1343   } else {
1344     assert(result_oop != Universe::the_null_sentinel(), "");
1345     return result_oop;
1346   }
1347 }
1348 
1349 oop ConstantPool::uncached_string_at(int cp_index, TRAPS) {
1350   Symbol* sym = unresolved_string_at(cp_index);
1351   oop str = StringTable::intern(sym, CHECK_(nullptr));
1352   assert(java_lang_String::is_instance(str), "must be string");
1353   return str;
1354 }
1355 
1356 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int cp_index,
1357                                                     int start_arg, int end_arg,
1358                                                     refArrayHandle info, int pos,
1359                                                     bool must_resolve, Handle if_not_available,
1360                                                     TRAPS) {
1361   int limit = pos + end_arg - start_arg;
1362   // checks: cp_index in range [0..this_cp->length),
1363   // tag at cp_index, start..end in range [0..this_cp->bootstrap_argument_count],
1364   // info array non-null, pos..limit in [0..info.length]
1365   if ((0 >= cp_index    || cp_index >= this_cp->length())  ||
1366       !(this_cp->tag_at(cp_index).is_invoke_dynamic()    ||
1367         this_cp->tag_at(cp_index).is_dynamic_constant()) ||
1368       (0 > start_arg || start_arg > end_arg) ||
1369       (end_arg > this_cp->bootstrap_argument_count_at(cp_index)) ||
1370       (0 > pos       || pos > limit)         ||
1371       (info.is_null() || limit > info->length())) {
1372     // An index or something else went wrong; throw an error.
1373     // Since this is an internal API, we don't expect this,
1374     // so we don't bother to craft a nice message.
1375     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1376   }
1377   // now we can loop safely
1378   int info_i = pos;
1379   for (int i = start_arg; i < end_arg; i++) {
1380     int arg_index = this_cp->bootstrap_argument_index_at(cp_index, i);
1381     oop arg_oop;
1382     if (must_resolve) {
1383       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1384     } else {
1385       bool found_it = false;
1386       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1387       if (!found_it)  arg_oop = if_not_available();
1388     }
1389     info->obj_at_put(info_i++, arg_oop);
1390   }
1391 }
1392 
1393 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int cp_index, int obj_index, TRAPS) {
1394   // If the string has already been interned, this entry will be non-null
1395   oop str = this_cp->resolved_reference_at(obj_index);
1396   assert(str != Universe::the_null_sentinel(), "");
1397   if (str != nullptr) return str;
1398   Symbol* sym = this_cp->unresolved_string_at(cp_index);
1399   str = StringTable::intern(sym, CHECK_(nullptr));
1400   this_cp->string_at_put(obj_index, str);
1401   assert(java_lang_String::is_instance(str), "must be string");
1402   return str;
1403 }
1404 
1405 
1406 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int cp_index) {
1407   // Names are interned, so we can compare Symbol*s directly
1408   Symbol* cp_name = klass_name_at(cp_index);
1409   return (cp_name == k->name());
1410 }
1411 
1412 
1413 // Iterate over symbols and decrement ones which are Symbol*s
1414 // This is done during GC.
1415 // Only decrement the UTF8 symbols. Strings point to
1416 // these symbols but didn't increment the reference count.
1417 void ConstantPool::unreference_symbols() {
1418   for (int index = 1; index < length(); index++) { // Index 0 is unused
1419     constantTag tag = tag_at(index);
1420     if (tag.is_symbol()) {
1421       symbol_at(index)->decrement_refcount();
1422     }
1423   }
1424 }
1425 
1426 
1427 // Compare this constant pool's entry at index1 to the constant pool
1428 // cp2's entry at index2.
1429 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1430        int index2) {
1431 
1432   // The error tags are equivalent to non-error tags when comparing
1433   jbyte t1 = tag_at(index1).non_error_value();
1434   jbyte t2 = cp2->tag_at(index2).non_error_value();
1435 
1436   // Some classes are pre-resolved (like Throwable) which may lead to
1437   // consider it as a different entry. We then revert them back temporarily
1438   // to ensure proper comparison.
1439   if (t1 == JVM_CONSTANT_Class) {
1440     t1 = JVM_CONSTANT_UnresolvedClass;
1441   }
1442   if (t2 == JVM_CONSTANT_Class) {
1443     t2 = JVM_CONSTANT_UnresolvedClass;
1444   }
1445 
1446   if (t1 != t2) {
1447     // Not the same entry type so there is nothing else to check. Note
1448     // that this style of checking will consider resolved/unresolved
1449     // class pairs as different.
1450     // From the ConstantPool* API point of view, this is correct
1451     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1452     // plays out in the context of ConstantPool* merging.
1453     return false;
1454   }
1455 
1456   switch (t1) {
1457   case JVM_CONSTANT_ClassIndex:
1458   {
1459     int recur1 = klass_index_at(index1);
1460     int recur2 = cp2->klass_index_at(index2);
1461     if (compare_entry_to(recur1, cp2, recur2)) {
1462       return true;
1463     }
1464   } break;
1465 
1466   case JVM_CONSTANT_Double:
1467   {
1468     jdouble d1 = double_at(index1);
1469     jdouble d2 = cp2->double_at(index2);
1470     if (d1 == d2) {
1471       return true;
1472     }
1473   } break;
1474 
1475   case JVM_CONSTANT_Fieldref:
1476   case JVM_CONSTANT_InterfaceMethodref:
1477   case JVM_CONSTANT_Methodref:
1478   {
1479     int recur1 = uncached_klass_ref_index_at(index1);
1480     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1481     bool match = compare_entry_to(recur1, cp2, recur2);
1482     if (match) {
1483       recur1 = uncached_name_and_type_ref_index_at(index1);
1484       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1485       if (compare_entry_to(recur1, cp2, recur2)) {
1486         return true;
1487       }
1488     }
1489   } break;
1490 
1491   case JVM_CONSTANT_Float:
1492   {
1493     jfloat f1 = float_at(index1);
1494     jfloat f2 = cp2->float_at(index2);
1495     if (f1 == f2) {
1496       return true;
1497     }
1498   } break;
1499 
1500   case JVM_CONSTANT_Integer:
1501   {
1502     jint i1 = int_at(index1);
1503     jint i2 = cp2->int_at(index2);
1504     if (i1 == i2) {
1505       return true;
1506     }
1507   } break;
1508 
1509   case JVM_CONSTANT_Long:
1510   {
1511     jlong l1 = long_at(index1);
1512     jlong l2 = cp2->long_at(index2);
1513     if (l1 == l2) {
1514       return true;
1515     }
1516   } break;
1517 
1518   case JVM_CONSTANT_NameAndType:
1519   {
1520     int recur1 = name_ref_index_at(index1);
1521     int recur2 = cp2->name_ref_index_at(index2);
1522     if (compare_entry_to(recur1, cp2, recur2)) {
1523       recur1 = signature_ref_index_at(index1);
1524       recur2 = cp2->signature_ref_index_at(index2);
1525       if (compare_entry_to(recur1, cp2, recur2)) {
1526         return true;
1527       }
1528     }
1529   } break;
1530 
1531   case JVM_CONSTANT_StringIndex:
1532   {
1533     int recur1 = string_index_at(index1);
1534     int recur2 = cp2->string_index_at(index2);
1535     if (compare_entry_to(recur1, cp2, recur2)) {
1536       return true;
1537     }
1538   } break;
1539 
1540   case JVM_CONSTANT_UnresolvedClass:
1541   {
1542     Symbol* k1 = klass_name_at(index1);
1543     Symbol* k2 = cp2->klass_name_at(index2);
1544     if (k1 == k2) {
1545       return true;
1546     }
1547   } break;
1548 
1549   case JVM_CONSTANT_MethodType:
1550   {
1551     int k1 = method_type_index_at(index1);
1552     int k2 = cp2->method_type_index_at(index2);
1553     if (compare_entry_to(k1, cp2, k2)) {
1554       return true;
1555     }
1556   } break;
1557 
1558   case JVM_CONSTANT_MethodHandle:
1559   {
1560     int k1 = method_handle_ref_kind_at(index1);
1561     int k2 = cp2->method_handle_ref_kind_at(index2);
1562     if (k1 == k2) {
1563       int i1 = method_handle_index_at(index1);
1564       int i2 = cp2->method_handle_index_at(index2);
1565       if (compare_entry_to(i1, cp2, i2)) {
1566         return true;
1567       }
1568     }
1569   } break;
1570 
1571   case JVM_CONSTANT_Dynamic:
1572   {
1573     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1574     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1575     int i1 = bootstrap_methods_attribute_index(index1);
1576     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1577     bool match_entry = compare_entry_to(k1, cp2, k2);
1578     bool match_bsm = compare_bootstrap_entry_to(i1, cp2, i2);
1579     return (match_entry && match_bsm);
1580   } break;
1581 
1582   case JVM_CONSTANT_InvokeDynamic:
1583   {
1584     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1585     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1586     int i1 = bootstrap_methods_attribute_index(index1);
1587     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1588     bool match_entry = compare_entry_to(k1, cp2, k2);
1589     bool match_bsm = compare_bootstrap_entry_to(i1, cp2, i2);
1590     return (match_entry && match_bsm);
1591   } break;
1592 
1593   case JVM_CONSTANT_String:
1594   {
1595     Symbol* s1 = unresolved_string_at(index1);
1596     Symbol* s2 = cp2->unresolved_string_at(index2);
1597     if (s1 == s2) {
1598       return true;
1599     }
1600   } break;
1601 
1602   case JVM_CONSTANT_Utf8:
1603   {
1604     Symbol* s1 = symbol_at(index1);
1605     Symbol* s2 = cp2->symbol_at(index2);
1606     if (s1 == s2) {
1607       return true;
1608     }
1609   } break;
1610 
1611   // Invalid is used as the tag for the second constant pool entry
1612   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1613   // not be seen by itself.
1614   case JVM_CONSTANT_Invalid: // fall through
1615 
1616   default:
1617     ShouldNotReachHere();
1618     break;
1619   }
1620 
1621   return false;
1622 } // end compare_entry_to()
1623 
1624 // Extend the BSMAttributeEntries with the length and size of the ext_cp BSMAttributeEntries.
1625 // Used in RedefineClasses for CP merge.
1626 BSMAttributeEntries::InsertionIterator
1627 ConstantPool::start_extension(const constantPoolHandle& ext_cp, TRAPS) {
1628   BSMAttributeEntries::InsertionIterator iter =
1629     bsm_entries().start_extension(ext_cp->bsm_entries(), pool_holder()->class_loader_data(),
1630                                   CHECK_(BSMAttributeEntries::InsertionIterator()));
1631   return iter;
1632 }
1633 
1634 
1635 void ConstantPool::end_extension(BSMAttributeEntries::InsertionIterator iter, TRAPS) {
1636   bsm_entries().end_extension(iter, pool_holder()->class_loader_data(), THREAD);
1637 }
1638 
1639 
1640 void ConstantPool::copy_bsm_entries(const constantPoolHandle& from_cp,
1641                                     const constantPoolHandle& to_cp,
1642                                     TRAPS) {
1643   to_cp->bsm_entries().append(from_cp->bsm_entries(),
1644                               to_cp->pool_holder()->class_loader_data(),
1645                               THREAD);
1646 }
1647 
1648 
1649 // Copy this constant pool's entries at start_i to end_i (inclusive)
1650 // to the constant pool to_cp's entries starting at to_i. A total of
1651 // (end_i - start_i) + 1 entries are copied.
1652 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1653        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1654 
1655 
1656   int dest_cpi = to_i;  // leave original alone for debug purposes
1657 
1658   for (int src_cpi = start_i; src_cpi <= end_i; /* see loop bottom */ ) {
1659     copy_entry_to(from_cp, src_cpi, to_cp, dest_cpi);
1660 
1661     switch (from_cp->tag_at(src_cpi).value()) {
1662     case JVM_CONSTANT_Double:
1663     case JVM_CONSTANT_Long:
1664       // double and long take two constant pool entries
1665       src_cpi += 2;
1666       dest_cpi += 2;
1667       break;
1668 
1669     default:
1670       // all others take one constant pool entry
1671       src_cpi++;
1672       dest_cpi++;
1673       break;
1674     }
1675   }
1676   copy_bsm_entries(from_cp, to_cp, THREAD);
1677 
1678 } // end copy_cp_to_impl()
1679 
1680 
1681 // Copy this constant pool's entry at from_i to the constant pool
1682 // to_cp's entry at to_i.
1683 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1684                                         const constantPoolHandle& to_cp, int to_i) {
1685 
1686   int tag = from_cp->tag_at(from_i).value();
1687   switch (tag) {
1688   case JVM_CONSTANT_ClassIndex:
1689   {
1690     jint ki = from_cp->klass_index_at(from_i);
1691     to_cp->klass_index_at_put(to_i, ki);
1692   } break;
1693 
1694   case JVM_CONSTANT_Double:
1695   {
1696     jdouble d = from_cp->double_at(from_i);
1697     to_cp->double_at_put(to_i, d);
1698     // double takes two constant pool entries so init second entry's tag
1699     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1700   } break;
1701 
1702   case JVM_CONSTANT_Fieldref:
1703   {
1704     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1705     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1706     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1707   } break;
1708 
1709   case JVM_CONSTANT_Float:
1710   {
1711     jfloat f = from_cp->float_at(from_i);
1712     to_cp->float_at_put(to_i, f);
1713   } break;
1714 
1715   case JVM_CONSTANT_Integer:
1716   {
1717     jint i = from_cp->int_at(from_i);
1718     to_cp->int_at_put(to_i, i);
1719   } break;
1720 
1721   case JVM_CONSTANT_InterfaceMethodref:
1722   {
1723     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1724     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1725     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1726   } break;
1727 
1728   case JVM_CONSTANT_Long:
1729   {
1730     jlong l = from_cp->long_at(from_i);
1731     to_cp->long_at_put(to_i, l);
1732     // long takes two constant pool entries so init second entry's tag
1733     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1734   } break;
1735 
1736   case JVM_CONSTANT_Methodref:
1737   {
1738     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1739     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1740     to_cp->method_at_put(to_i, class_index, name_and_type_index);
1741   } break;
1742 
1743   case JVM_CONSTANT_NameAndType:
1744   {
1745     int name_ref_index = from_cp->name_ref_index_at(from_i);
1746     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1747     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1748   } break;
1749 
1750   case JVM_CONSTANT_StringIndex:
1751   {
1752     jint si = from_cp->string_index_at(from_i);
1753     to_cp->string_index_at_put(to_i, si);
1754   } break;
1755 
1756   case JVM_CONSTANT_Class:
1757   case JVM_CONSTANT_UnresolvedClass:
1758   case JVM_CONSTANT_UnresolvedClassInError:
1759   {
1760     // Revert to JVM_CONSTANT_ClassIndex
1761     int name_index = from_cp->klass_slot_at(from_i).name_index();
1762     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1763     to_cp->klass_index_at_put(to_i, name_index);
1764   } break;
1765 
1766   case JVM_CONSTANT_String:
1767   {
1768     Symbol* s = from_cp->unresolved_string_at(from_i);
1769     to_cp->unresolved_string_at_put(to_i, s);
1770   } break;
1771 
1772   case JVM_CONSTANT_Utf8:
1773   {
1774     Symbol* s = from_cp->symbol_at(from_i);
1775     // Need to increase refcount, the old one will be thrown away and deferenced
1776     s->increment_refcount();
1777     to_cp->symbol_at_put(to_i, s);
1778   } break;
1779 
1780   case JVM_CONSTANT_MethodType:
1781   case JVM_CONSTANT_MethodTypeInError:
1782   {
1783     jint k = from_cp->method_type_index_at(from_i);
1784     to_cp->method_type_index_at_put(to_i, k);
1785   } break;
1786 
1787   case JVM_CONSTANT_MethodHandle:
1788   case JVM_CONSTANT_MethodHandleInError:
1789   {
1790     int k1 = from_cp->method_handle_ref_kind_at(from_i);
1791     int k2 = from_cp->method_handle_index_at(from_i);
1792     to_cp->method_handle_index_at_put(to_i, k1, k2);
1793   } break;
1794 
1795   case JVM_CONSTANT_Dynamic:
1796   case JVM_CONSTANT_DynamicInError:
1797   {
1798     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1799     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1800     k1 += to_cp->bsm_entries().array_length();  // to_cp might already have a BSM attribute
1801     to_cp->dynamic_constant_at_put(to_i, k1, k2);
1802   } break;
1803 
1804   case JVM_CONSTANT_InvokeDynamic:
1805   {
1806     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1807     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1808     k1 += to_cp->bsm_entries().array_length();  // to_cp might already have a BSM attribute
1809     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1810   } break;
1811 
1812   // Invalid is used as the tag for the second constant pool entry
1813   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1814   // not be seen by itself.
1815   case JVM_CONSTANT_Invalid: // fall through
1816 
1817   default:
1818   {
1819     ShouldNotReachHere();
1820   } break;
1821   }
1822 } // end copy_entry_to()
1823 
1824 // Search constant pool search_cp for an entry that matches this
1825 // constant pool's entry at pattern_i. Returns the index of a
1826 // matching entry or zero (0) if there is no matching entry.
1827 int ConstantPool::find_matching_entry(int pattern_i,
1828       const constantPoolHandle& search_cp) {
1829 
1830   // index zero (0) is not used
1831   for (int i = 1; i < search_cp->length(); i++) {
1832     bool found = compare_entry_to(pattern_i, search_cp, i);
1833     if (found) {
1834       return i;
1835     }
1836   }
1837 
1838   return 0;  // entry not found; return unused index zero (0)
1839 } // end find_matching_entry()
1840 
1841 
1842 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1843 // cp2's bootstrap specifier at idx2.
1844 bool ConstantPool::compare_bootstrap_entry_to(int idx1, const constantPoolHandle& cp2, int idx2) {
1845   const BSMAttributeEntry* const e1 = bsm_attribute_entry(idx1);
1846   const BSMAttributeEntry* const e2 = cp2->bsm_attribute_entry(idx2);
1847   int k1 = e1->bootstrap_method_index();
1848   int k2 = e2->bootstrap_method_index();
1849   bool match = compare_entry_to(k1, cp2, k2);
1850 
1851   if (!match) {
1852     return false;
1853   }
1854 
1855   const int argc = e1->argument_count();
1856   if (argc != e2->argument_count()) {
1857     return false;
1858   }
1859 
1860   for (int j = 0; j < argc; j++) {
1861     k1 = e1->argument(j);
1862     k2 = e2->argument(j);
1863     match = compare_entry_to(k1, cp2, k2);
1864     if (!match) {
1865       return false;
1866     }
1867   }
1868 
1869   return true; // got through loop; all elements equal
1870 } // end compare_bootstrap_entry_to()
1871 
1872 // Search constant pool search_cp for a bootstrap specifier that matches
1873 // this constant pool's bootstrap specifier data at pattern_i index.
1874 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1875 int ConstantPool::find_matching_bsm_entry(int pattern_i,
1876                                           const constantPoolHandle& search_cp, int offset_limit) {
1877   for (int i = 0; i < offset_limit; i++) {
1878     bool found = compare_bootstrap_entry_to(pattern_i, search_cp, i);
1879     if (found) {
1880       return i;
1881     }
1882   }
1883   return -1;  // bootstrap specifier data not found; return unused index (-1)
1884 } // end find_matching_bsm_entry()
1885 
1886 
1887 #ifndef PRODUCT
1888 
1889 const char* ConstantPool::printable_name_at(int cp_index) {
1890 
1891   constantTag tag = tag_at(cp_index);
1892 
1893   if (tag.is_string()) {
1894     return string_at_noresolve(cp_index);
1895   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1896     return klass_name_at(cp_index)->as_C_string();
1897   } else if (tag.is_symbol()) {
1898     return symbol_at(cp_index)->as_C_string();
1899   }
1900   return "";
1901 }
1902 
1903 #endif // PRODUCT
1904 
1905 
1906 // Returns size of constant pool entry.
1907 jint ConstantPool::cpool_entry_size(jint idx) {
1908   switch(tag_at(idx).value()) {
1909     case JVM_CONSTANT_Invalid:
1910     case JVM_CONSTANT_Unicode:
1911       return 1;
1912 
1913     case JVM_CONSTANT_Utf8:
1914       return 3 + symbol_at(idx)->utf8_length();
1915 
1916     case JVM_CONSTANT_Class:
1917     case JVM_CONSTANT_String:
1918     case JVM_CONSTANT_ClassIndex:
1919     case JVM_CONSTANT_UnresolvedClass:
1920     case JVM_CONSTANT_UnresolvedClassInError:
1921     case JVM_CONSTANT_StringIndex:
1922     case JVM_CONSTANT_MethodType:
1923     case JVM_CONSTANT_MethodTypeInError:
1924       return 3;
1925 
1926     case JVM_CONSTANT_MethodHandle:
1927     case JVM_CONSTANT_MethodHandleInError:
1928       return 4; //tag, ref_kind, ref_index
1929 
1930     case JVM_CONSTANT_Integer:
1931     case JVM_CONSTANT_Float:
1932     case JVM_CONSTANT_Fieldref:
1933     case JVM_CONSTANT_Methodref:
1934     case JVM_CONSTANT_InterfaceMethodref:
1935     case JVM_CONSTANT_NameAndType:
1936       return 5;
1937 
1938     case JVM_CONSTANT_Dynamic:
1939     case JVM_CONSTANT_DynamicInError:
1940     case JVM_CONSTANT_InvokeDynamic:
1941       // u1 tag, u2 bsm, u2 nt
1942       return 5;
1943 
1944     case JVM_CONSTANT_Long:
1945     case JVM_CONSTANT_Double:
1946       return 9;
1947   }
1948   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
1949   return 1;
1950 } /* end cpool_entry_size */
1951 
1952 
1953 // SymbolHash is used to find a constant pool index from a string.
1954 // This function fills in SymbolHashs, one for utf8s and one for
1955 // class names, returns size of the cpool raw bytes.
1956 jint ConstantPool::hash_entries_to(SymbolHash *symmap,
1957                                    SymbolHash *classmap) {
1958   jint size = 0;
1959 
1960   for (u2 idx = 1; idx < length(); idx++) {
1961     u2 tag = tag_at(idx).value();
1962     size += cpool_entry_size(idx);
1963 
1964     switch(tag) {
1965       case JVM_CONSTANT_Utf8: {
1966         Symbol* sym = symbol_at(idx);
1967         symmap->add_if_absent(sym, idx);
1968         break;
1969       }
1970       case JVM_CONSTANT_Class:
1971       case JVM_CONSTANT_UnresolvedClass:
1972       case JVM_CONSTANT_UnresolvedClassInError: {
1973         Symbol* sym = klass_name_at(idx);
1974         classmap->add_if_absent(sym, idx);
1975         break;
1976       }
1977       case JVM_CONSTANT_Long:
1978       case JVM_CONSTANT_Double: {
1979         idx++; // Both Long and Double take two cpool slots
1980         break;
1981       }
1982     }
1983   }
1984   return size;
1985 } /* end hash_utf8_entries_to */
1986 
1987 
1988 // Copy cpool bytes.
1989 // Returns:
1990 //    0, in case of OutOfMemoryError
1991 //   -1, in case of internal error
1992 //  > 0, count of the raw cpool bytes that have been copied
1993 int ConstantPool::copy_cpool_bytes(int cpool_size,
1994                                    SymbolHash* tbl,
1995                                    unsigned char *bytes) {
1996   u2   idx1, idx2;
1997   jint size  = 0;
1998   jint cnt   = length();
1999   unsigned char *start_bytes = bytes;
2000 
2001   for (jint idx = 1; idx < cnt; idx++) {
2002     u1   tag      = tag_at(idx).value();
2003     jint ent_size = cpool_entry_size(idx);
2004 
2005     assert(size + ent_size <= cpool_size, "Size mismatch");
2006 
2007     *bytes = tag;
2008     switch(tag) {
2009       case JVM_CONSTANT_Invalid: {
2010         break;
2011       }
2012       case JVM_CONSTANT_Unicode: {
2013         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2014         break;
2015       }
2016       case JVM_CONSTANT_Utf8: {
2017         Symbol* sym = symbol_at(idx);
2018         char*     str = sym->as_utf8();
2019         // Warning! It's crashing on x86 with len = sym->utf8_length()
2020         int       len = (int) strlen(str);
2021         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2022         for (int i = 0; i < len; i++) {
2023             bytes[3+i] = (u1) str[i];
2024         }
2025         break;
2026       }
2027       case JVM_CONSTANT_Integer: {
2028         jint val = int_at(idx);
2029         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2030         break;
2031       }
2032       case JVM_CONSTANT_Float: {
2033         jfloat val = float_at(idx);
2034         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2035         break;
2036       }
2037       case JVM_CONSTANT_Long: {
2038         jlong val = long_at(idx);
2039         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2040         idx++;             // Long takes two cpool slots
2041         break;
2042       }
2043       case JVM_CONSTANT_Double: {
2044         jdouble val = double_at(idx);
2045         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2046         idx++;             // Double takes two cpool slots
2047         break;
2048       }
2049       case JVM_CONSTANT_Class:
2050       case JVM_CONSTANT_UnresolvedClass:
2051       case JVM_CONSTANT_UnresolvedClassInError: {
2052         *bytes = JVM_CONSTANT_Class;
2053         Symbol* sym = klass_name_at(idx);
2054         idx1 = tbl->symbol_to_value(sym);
2055         assert(idx1 != 0, "Have not found a hashtable entry");
2056         Bytes::put_Java_u2((address) (bytes+1), idx1);
2057         break;
2058       }
2059       case JVM_CONSTANT_String: {
2060         *bytes = JVM_CONSTANT_String;
2061         Symbol* sym = unresolved_string_at(idx);
2062         idx1 = tbl->symbol_to_value(sym);
2063         assert(idx1 != 0, "Have not found a hashtable entry");
2064         Bytes::put_Java_u2((address) (bytes+1), idx1);
2065         break;
2066       }
2067       case JVM_CONSTANT_Fieldref:
2068       case JVM_CONSTANT_Methodref:
2069       case JVM_CONSTANT_InterfaceMethodref: {
2070         idx1 = uncached_klass_ref_index_at(idx);
2071         idx2 = uncached_name_and_type_ref_index_at(idx);
2072         Bytes::put_Java_u2((address) (bytes+1), idx1);
2073         Bytes::put_Java_u2((address) (bytes+3), idx2);
2074         break;
2075       }
2076       case JVM_CONSTANT_NameAndType: {
2077         idx1 = name_ref_index_at(idx);
2078         idx2 = signature_ref_index_at(idx);
2079         Bytes::put_Java_u2((address) (bytes+1), idx1);
2080         Bytes::put_Java_u2((address) (bytes+3), idx2);
2081         break;
2082       }
2083       case JVM_CONSTANT_ClassIndex: {
2084         *bytes = JVM_CONSTANT_Class;
2085         idx1 = checked_cast<u2>(klass_index_at(idx));
2086         Bytes::put_Java_u2((address) (bytes+1), idx1);
2087         break;
2088       }
2089       case JVM_CONSTANT_StringIndex: {
2090         *bytes = JVM_CONSTANT_String;
2091         idx1 = checked_cast<u2>(string_index_at(idx));
2092         Bytes::put_Java_u2((address) (bytes+1), idx1);
2093         break;
2094       }
2095       case JVM_CONSTANT_MethodHandle:
2096       case JVM_CONSTANT_MethodHandleInError: {
2097         *bytes = JVM_CONSTANT_MethodHandle;
2098         int kind = method_handle_ref_kind_at(idx);
2099         idx1 = checked_cast<u2>(method_handle_index_at(idx));
2100         *(bytes+1) = (unsigned char) kind;
2101         Bytes::put_Java_u2((address) (bytes+2), idx1);
2102         break;
2103       }
2104       case JVM_CONSTANT_MethodType:
2105       case JVM_CONSTANT_MethodTypeInError: {
2106         *bytes = JVM_CONSTANT_MethodType;
2107         idx1 = checked_cast<u2>(method_type_index_at(idx));
2108         Bytes::put_Java_u2((address) (bytes+1), idx1);
2109         break;
2110       }
2111       case JVM_CONSTANT_Dynamic:
2112       case JVM_CONSTANT_DynamicInError: {
2113         *bytes = tag;
2114         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2115         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2116         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2117         Bytes::put_Java_u2((address) (bytes+1), idx1);
2118         Bytes::put_Java_u2((address) (bytes+3), idx2);
2119         break;
2120       }
2121       case JVM_CONSTANT_InvokeDynamic: {
2122         *bytes = tag;
2123         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2124         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2125         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2126         Bytes::put_Java_u2((address) (bytes+1), idx1);
2127         Bytes::put_Java_u2((address) (bytes+3), idx2);
2128         break;
2129       }
2130     }
2131     bytes += ent_size;
2132     size  += ent_size;
2133   }
2134   assert(size == cpool_size, "Size mismatch");
2135 
2136   return (int)(bytes - start_bytes);
2137 } /* end copy_cpool_bytes */
2138 
2139 bool ConstantPool::is_maybe_on_stack() const {
2140   // This method uses the similar logic as nmethod::is_maybe_on_stack()
2141   if (!Continuations::enabled()) {
2142     return false;
2143   }
2144 
2145   // If the condition below is true, it means that the nmethod was found to
2146   // be alive the previous completed marking cycle.
2147   return cache()->gc_epoch() >= CodeCache::previous_completed_gc_marking_cycle();
2148 }
2149 
2150 // For redefinition, if any methods found in loom stack chunks, the gc_epoch is
2151 // recorded in their constant pool cache. The on_stack-ness of the constant pool controls whether
2152 // memory for the method is reclaimed.
2153 bool ConstantPool::on_stack() const {
2154   if ((_flags &_on_stack) != 0) {
2155     return true;
2156   }
2157 
2158   if (_cache == nullptr) {
2159     return false;
2160   }
2161 
2162   return is_maybe_on_stack();
2163 }
2164 
2165 void ConstantPool::set_on_stack(const bool value) {
2166   if (value) {
2167     // Only record if it's not already set.
2168     if (!on_stack()) {
2169       assert(!in_aot_cache(), "should always be set for constant pools in AOT cache");
2170       _flags |= _on_stack;
2171       MetadataOnStackMark::record(this);
2172     }
2173   } else {
2174     // Clearing is done single-threadedly.
2175     if (!in_aot_cache()) {
2176       _flags &= (u2)(~_on_stack);
2177     }
2178   }
2179 }
2180 
2181 // Printing
2182 
2183 void ConstantPool::print_on(outputStream* st) const {
2184   assert(is_constantPool(), "must be constantPool");
2185   st->print_cr("%s", internal_name());
2186   if (flags() != 0) {
2187     st->print(" - flags: 0x%x", flags());
2188     if (has_preresolution()) st->print(" has_preresolution");
2189     if (on_stack()) st->print(" on_stack");
2190     st->cr();
2191   }
2192   if (pool_holder() != nullptr) {
2193     st->print_cr(" - holder: " PTR_FORMAT, p2i(pool_holder()));
2194   }
2195   st->print_cr(" - cache: " PTR_FORMAT, p2i(cache()));
2196   st->print_cr(" - resolved_references: " PTR_FORMAT, p2i(resolved_references_or_null()));
2197   st->print_cr(" - reference_map: " PTR_FORMAT, p2i(reference_map()));
2198   st->print_cr(" - resolved_klasses: " PTR_FORMAT, p2i(resolved_klasses()));
2199   st->print_cr(" - cp length: %d", length());
2200 
2201   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2202     ((ConstantPool*)this)->print_entry_on(index, st);
2203     switch (tag_at(index).value()) {
2204       case JVM_CONSTANT_Long :
2205       case JVM_CONSTANT_Double :
2206         index++;   // Skip entry following eigth-byte constant
2207     }
2208 
2209   }
2210   st->cr();
2211 }
2212 
2213 // Print one constant pool entry
2214 void ConstantPool::print_entry_on(const int cp_index, outputStream* st) {
2215   EXCEPTION_MARK;
2216   st->print(" - %3d : ", cp_index);
2217   tag_at(cp_index).print_on(st);
2218   st->print(" : ");
2219   switch (tag_at(cp_index).value()) {
2220     case JVM_CONSTANT_Class :
2221       { Klass* k = klass_at(cp_index, CATCH);
2222         guarantee(k != nullptr, "need klass");
2223         k->print_value_on(st);
2224         st->print(" {" PTR_FORMAT "}", p2i(k));
2225       }
2226       break;
2227     case JVM_CONSTANT_Fieldref :
2228     case JVM_CONSTANT_Methodref :
2229     case JVM_CONSTANT_InterfaceMethodref :
2230       st->print("klass_index=%d", uncached_klass_ref_index_at(cp_index));
2231       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(cp_index));
2232       break;
2233     case JVM_CONSTANT_String :
2234       unresolved_string_at(cp_index)->print_value_on(st);
2235       break;
2236     case JVM_CONSTANT_Integer :
2237       st->print("%d", int_at(cp_index));
2238       break;
2239     case JVM_CONSTANT_Float :
2240       st->print("%f", float_at(cp_index));
2241       break;
2242     case JVM_CONSTANT_Long :
2243       st->print_jlong(long_at(cp_index));
2244       break;
2245     case JVM_CONSTANT_Double :
2246       st->print("%lf", double_at(cp_index));
2247       break;
2248     case JVM_CONSTANT_NameAndType :
2249       st->print("name_index=%d", name_ref_index_at(cp_index));
2250       st->print(" signature_index=%d", signature_ref_index_at(cp_index));
2251       break;
2252     case JVM_CONSTANT_Utf8 :
2253       symbol_at(cp_index)->print_value_on(st);
2254       break;
2255     case JVM_CONSTANT_ClassIndex: {
2256         int name_index = *int_at_addr(cp_index);
2257         st->print("klass_index=%d ", name_index);
2258         symbol_at(name_index)->print_value_on(st);
2259       }
2260       break;
2261     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2262     case JVM_CONSTANT_UnresolvedClassInError: {
2263         CPKlassSlot kslot = klass_slot_at(cp_index);
2264         int resolved_klass_index = kslot.resolved_klass_index();
2265         int name_index = kslot.name_index();
2266         assert(tag_at(name_index).is_symbol(), "sanity");
2267         symbol_at(name_index)->print_value_on(st);
2268       }
2269       break;
2270     case JVM_CONSTANT_MethodHandle :
2271     case JVM_CONSTANT_MethodHandleInError :
2272       st->print("ref_kind=%d", method_handle_ref_kind_at(cp_index));
2273       st->print(" ref_index=%d", method_handle_index_at(cp_index));
2274       break;
2275     case JVM_CONSTANT_MethodType :
2276     case JVM_CONSTANT_MethodTypeInError :
2277       st->print("signature_index=%d", method_type_index_at(cp_index));
2278       break;
2279     case JVM_CONSTANT_Dynamic :
2280     case JVM_CONSTANT_DynamicInError :
2281       {
2282         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2283         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2284         int argc = bootstrap_argument_count_at(cp_index);
2285         if (argc > 0) {
2286           for (int arg_i = 0; arg_i < argc; arg_i++) {
2287             int arg = bootstrap_argument_index_at(cp_index, arg_i);
2288             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2289           }
2290           st->print("}");
2291         }
2292       }
2293       break;
2294     case JVM_CONSTANT_InvokeDynamic :
2295       {
2296         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2297         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2298         int argc = bootstrap_argument_count_at(cp_index);
2299         if (argc > 0) {
2300           for (int arg_i = 0; arg_i < argc; arg_i++) {
2301             int arg = bootstrap_argument_index_at(cp_index, arg_i);
2302             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2303           }
2304           st->print("}");
2305         }
2306       }
2307       break;
2308     default:
2309       ShouldNotReachHere();
2310       break;
2311   }
2312   st->cr();
2313 }
2314 
2315 void ConstantPool::print_value_on(outputStream* st) const {
2316   assert(is_constantPool(), "must be constantPool");
2317   st->print("constant pool [%d]", length());
2318   if (has_preresolution()) st->print("/preresolution");
2319   if (!bsm_entries().is_empty())  st->print("/BSMs[%d]", bsm_entries().bootstrap_methods()->length());
2320   print_address_on(st);
2321   if (pool_holder() != nullptr) {
2322     st->print(" for ");
2323     pool_holder()->print_value_on(st);
2324     bool extra = (pool_holder()->constants() != this);
2325     if (extra)  st->print(" (extra)");
2326   }
2327   if (cache() != nullptr) {
2328     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2329   }
2330 }
2331 
2332 // Verification
2333 
2334 void ConstantPool::verify_on(outputStream* st) {
2335   guarantee(is_constantPool(), "object must be constant pool");
2336   for (int i = 0; i< length();  i++) {
2337     constantTag tag = tag_at(i);
2338     if (tag.is_klass() || tag.is_unresolved_klass()) {
2339       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2340     } else if (tag.is_symbol()) {
2341       Symbol* entry = symbol_at(i);
2342       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2343     } else if (tag.is_string()) {
2344       Symbol* entry = unresolved_string_at(i);
2345       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2346     }
2347   }
2348   if (pool_holder() != nullptr) {
2349     // Note: pool_holder() can be null in temporary constant pools
2350     // used during constant pool merging
2351     guarantee(pool_holder()->is_klass(),    "should be klass");
2352   }
2353 }
2354 
2355 void BSMAttributeEntries::deallocate_contents(ClassLoaderData* loader_data) {
2356   MetadataFactory::free_array<u4>(loader_data, this->_offsets);
2357   MetadataFactory::free_array<u2>(loader_data, this->_bootstrap_methods);
2358   this->_offsets = nullptr;
2359   this->_bootstrap_methods = nullptr;
2360 }
2361 
2362 void BSMAttributeEntries::copy_into(InsertionIterator& iter, int num_entries) const {
2363   assert(num_entries + iter._cur_offset <= iter._insert_into->_offsets->length(), "must");
2364   for (int i = 0; i < num_entries; i++) {
2365     const BSMAttributeEntry* e = entry(i);
2366     BSMAttributeEntry* e_new = iter.reserve_new_entry(e->bootstrap_method_index(), e->argument_count());
2367     assert(e_new != nullptr, "must be");
2368     e->copy_args_into(e_new);
2369   }
2370 }
2371 
2372 BSMAttributeEntries::InsertionIterator
2373 BSMAttributeEntries::start_extension(const BSMAttributeEntries& other, ClassLoaderData* loader_data, TRAPS) {
2374   InsertionIterator iter = start_extension(other.number_of_entries(), other.array_length(),
2375                                            loader_data, CHECK_(BSMAttributeEntries::InsertionIterator()));
2376   return iter;
2377 }
2378 
2379 BSMAttributeEntries::InsertionIterator
2380 BSMAttributeEntries::start_extension(int number_of_entries, int array_length,
2381                                      ClassLoaderData* loader_data, TRAPS) {
2382   InsertionIterator extension_iterator(this, this->number_of_entries(), this->array_length());
2383   int new_number_of_entries = this->number_of_entries() + number_of_entries;
2384   int new_array_length = this->array_length() + array_length;
2385   int invalid_index = new_array_length;
2386 
2387   Array<u4>* new_offsets =
2388     MetadataFactory::new_array<u4>(loader_data, new_number_of_entries, invalid_index, CHECK_(InsertionIterator()));
2389   Array<u2>* new_array = MetadataFactory::new_array<u2>(loader_data, new_array_length, CHECK_(InsertionIterator()));
2390   { // Copy over all the old BSMAEntry's and their respective offsets
2391     BSMAttributeEntries carrier(new_offsets, new_array);
2392     InsertionIterator copy_iter(&carrier, 0, 0);
2393     copy_into(copy_iter, this->number_of_entries());
2394   }
2395   // Replace content
2396   deallocate_contents(loader_data);
2397   _offsets = new_offsets;
2398   _bootstrap_methods = new_array;
2399   return extension_iterator;
2400 }
2401 
2402 
2403 void BSMAttributeEntries::append(const BSMAttributeEntries& other, ClassLoaderData* loader_data, TRAPS) {
2404   if (other.number_of_entries() == 0) {
2405     return; // Done!
2406   }
2407   InsertionIterator iter = start_extension(other, loader_data, CHECK);
2408   other.copy_into(iter, other.number_of_entries());
2409   end_extension(iter, loader_data, THREAD);
2410 }
2411 
2412 void BSMAttributeEntries::end_extension(InsertionIterator& iter, ClassLoaderData* loader_data, TRAPS) {
2413   assert(iter._insert_into == this, "must be");
2414   assert(iter._cur_offset <= this->_offsets->length(), "must be");
2415   assert(iter._cur_array <= this->_bootstrap_methods->length(), "must be");
2416 
2417   // Did we fill up all of the available space? If so, do nothing.
2418   if (iter._cur_offset == this->_offsets->length() &&
2419       iter._cur_array == this->_bootstrap_methods->length()) {
2420     return;
2421   }
2422 
2423   // We used less, truncate by allocating new arrays
2424   Array<u4>* new_offsets =
2425       MetadataFactory::new_array<u4>(loader_data, iter._cur_offset, 0, CHECK);
2426   Array<u2>* new_array =
2427     MetadataFactory::new_array<u2>(loader_data, iter._cur_array, CHECK);
2428   { // Copy over the constructed BSMAEntry's
2429     BSMAttributeEntries carrier(new_offsets, new_array);
2430     InsertionIterator copy_iter(&carrier, 0, 0);
2431     copy_into(copy_iter, iter._cur_offset);
2432   }
2433 
2434   deallocate_contents(loader_data);
2435   _offsets = new_offsets;
2436   _bootstrap_methods = new_array;
2437 }