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