1 /*
   2  * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/parallel/parallelArguments.hpp"
  34 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  35 #include "gc/parallel/parMarkBitMap.inline.hpp"
  36 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  37 #include "gc/parallel/psCompactionManager.inline.hpp"
  38 #include "gc/parallel/psOldGen.hpp"
  39 #include "gc/parallel/psParallelCompact.inline.hpp"
  40 #include "gc/parallel/psPromotionManager.inline.hpp"
  41 #include "gc/parallel/psRootType.hpp"
  42 #include "gc/parallel/psScavenge.hpp"
  43 #include "gc/parallel/psStringDedup.hpp"
  44 #include "gc/parallel/psYoungGen.hpp"
  45 #include "gc/shared/classUnloadingContext.hpp"
  46 #include "gc/shared/gcCause.hpp"
  47 #include "gc/shared/gcHeapSummary.hpp"
  48 #include "gc/shared/gcId.hpp"
  49 #include "gc/shared/gcLocker.hpp"
  50 #include "gc/shared/gcTimer.hpp"
  51 #include "gc/shared/gcTrace.hpp"
  52 #include "gc/shared/gcTraceTime.inline.hpp"
  53 #include "gc/shared/isGCActiveMark.hpp"
  54 #include "gc/shared/oopStorage.inline.hpp"
  55 #include "gc/shared/oopStorageSet.inline.hpp"
  56 #include "gc/shared/oopStorageSetParState.inline.hpp"
  57 #include "gc/shared/referencePolicy.hpp"
  58 #include "gc/shared/referenceProcessor.hpp"
  59 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  60 #include "gc/shared/spaceDecorator.inline.hpp"
  61 #include "gc/shared/taskTerminator.hpp"
  62 #include "gc/shared/weakProcessor.inline.hpp"
  63 #include "gc/shared/workerPolicy.hpp"
  64 #include "gc/shared/workerThread.hpp"
  65 #include "gc/shared/workerUtils.hpp"
  66 #include "logging/log.hpp"
  67 #include "memory/iterator.inline.hpp"
  68 #include "memory/metaspaceUtils.hpp"
  69 #include "memory/resourceArea.hpp"
  70 #include "memory/universe.hpp"
  71 #include "nmt/memTracker.hpp"
  72 #include "oops/access.inline.hpp"
  73 #include "oops/instanceClassLoaderKlass.inline.hpp"
  74 #include "oops/instanceKlass.inline.hpp"
  75 #include "oops/instanceMirrorKlass.inline.hpp"
  76 #include "oops/methodData.hpp"
  77 #include "oops/objArrayKlass.inline.hpp"
  78 #include "oops/oop.inline.hpp"
  79 #include "runtime/atomic.hpp"
  80 #include "runtime/handles.inline.hpp"
  81 #include "runtime/java.hpp"
  82 #include "runtime/safepoint.hpp"
  83 #include "runtime/threads.hpp"
  84 #include "runtime/vmThread.hpp"
  85 #include "services/memoryService.hpp"
  86 #include "utilities/align.hpp"
  87 #include "utilities/debug.hpp"
  88 #include "utilities/events.hpp"
  89 #include "utilities/formatBuffer.hpp"
  90 #include "utilities/macros.hpp"
  91 #include "utilities/stack.inline.hpp"
  92 #if INCLUDE_JVMCI
  93 #include "jvmci/jvmci.hpp"
  94 #endif
  95 
  96 #include <math.h>
  97 
  98 // All sizes are in HeapWords.
  99 const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
 100 const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
 101 const size_t ParallelCompactData::RegionSizeBytes =
 102   RegionSize << LogHeapWordSize;
 103 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
 104 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
 105 const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;
 106 
 107 const size_t ParallelCompactData::Log2BlockSize   = 7; // 128 words
 108 const size_t ParallelCompactData::BlockSize       = (size_t)1 << Log2BlockSize;
 109 const size_t ParallelCompactData::BlockSizeBytes  =
 110   BlockSize << LogHeapWordSize;
 111 const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;
 112 const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;
 113 const size_t ParallelCompactData::BlockAddrMask       = ~BlockAddrOffsetMask;
 114 
 115 const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;
 116 const size_t ParallelCompactData::Log2BlocksPerRegion =
 117   Log2RegionSize - Log2BlockSize;
 118 
 119 const ParallelCompactData::RegionData::region_sz_t
 120 ParallelCompactData::RegionData::dc_shift = 27;
 121 
 122 const ParallelCompactData::RegionData::region_sz_t
 123 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
 124 
 125 const ParallelCompactData::RegionData::region_sz_t
 126 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
 127 
 128 const ParallelCompactData::RegionData::region_sz_t
 129 ParallelCompactData::RegionData::los_mask = ~dc_mask;
 130 
 131 const ParallelCompactData::RegionData::region_sz_t
 132 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
 133 
 134 const ParallelCompactData::RegionData::region_sz_t
 135 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
 136 
 137 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
 138 
 139 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
 140 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
 141 
 142 double PSParallelCompact::_dwl_mean;
 143 double PSParallelCompact::_dwl_std_dev;
 144 double PSParallelCompact::_dwl_first_term;
 145 double PSParallelCompact::_dwl_adjustment;
 146 #ifdef  ASSERT
 147 bool   PSParallelCompact::_dwl_initialized = false;
 148 #endif  // #ifdef ASSERT
 149 
 150 void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
 151                        HeapWord* destination)
 152 {
 153   assert(src_region_idx != 0, "invalid src_region_idx");
 154   assert(partial_obj_size != 0, "invalid partial_obj_size argument");
 155   assert(destination != nullptr, "invalid destination argument");
 156 
 157   _src_region_idx = src_region_idx;
 158   _partial_obj_size = partial_obj_size;
 159   _destination = destination;
 160 
 161   // These fields may not be updated below, so make sure they're clear.
 162   assert(_dest_region_addr == nullptr, "should have been cleared");
 163   assert(_first_src_addr == nullptr, "should have been cleared");
 164 
 165   // Determine the number of destination regions for the partial object.
 166   HeapWord* const last_word = destination + partial_obj_size - 1;
 167   const ParallelCompactData& sd = PSParallelCompact::summary_data();
 168   HeapWord* const beg_region_addr = sd.region_align_down(destination);
 169   HeapWord* const end_region_addr = sd.region_align_down(last_word);
 170 
 171   if (beg_region_addr == end_region_addr) {
 172     // One destination region.
 173     _destination_count = 1;
 174     if (end_region_addr == destination) {
 175       // The destination falls on a region boundary, thus the first word of the
 176       // partial object will be the first word copied to the destination region.
 177       _dest_region_addr = end_region_addr;
 178       _first_src_addr = sd.region_to_addr(src_region_idx);
 179     }
 180   } else {
 181     // Two destination regions.  When copied, the partial object will cross a
 182     // destination region boundary, so a word somewhere within the partial
 183     // object will be the first word copied to the second destination region.
 184     _destination_count = 2;
 185     _dest_region_addr = end_region_addr;
 186     const size_t ofs = pointer_delta(end_region_addr, destination);
 187     assert(ofs < _partial_obj_size, "sanity");
 188     _first_src_addr = sd.region_to_addr(src_region_idx) + ofs;
 189   }
 190 }
 191 
 192 void SplitInfo::clear()
 193 {
 194   _src_region_idx = 0;
 195   _partial_obj_size = 0;
 196   _destination = nullptr;
 197   _destination_count = 0;
 198   _dest_region_addr = nullptr;
 199   _first_src_addr = nullptr;
 200   assert(!is_valid(), "sanity");
 201 }
 202 
 203 #ifdef  ASSERT
 204 void SplitInfo::verify_clear()
 205 {
 206   assert(_src_region_idx == 0, "not clear");
 207   assert(_partial_obj_size == 0, "not clear");
 208   assert(_destination == nullptr, "not clear");
 209   assert(_destination_count == 0, "not clear");
 210   assert(_dest_region_addr == nullptr, "not clear");
 211   assert(_first_src_addr == nullptr, "not clear");
 212 }
 213 #endif  // #ifdef ASSERT
 214 
 215 
 216 void PSParallelCompact::print_on_error(outputStream* st) {
 217   _mark_bitmap.print_on_error(st);
 218 }
 219 
 220 #ifndef PRODUCT
 221 const char* PSParallelCompact::space_names[] = {
 222   "old ", "eden", "from", "to  "
 223 };
 224 
 225 void PSParallelCompact::print_region_ranges() {
 226   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 227     return;
 228   }
 229   Log(gc, compaction) log;
 230   ResourceMark rm;
 231   LogStream ls(log.trace());
 232   Universe::print_on(&ls);
 233   log.trace("space  bottom     top        end        new_top");
 234   log.trace("------ ---------- ---------- ---------- ----------");
 235 
 236   for (unsigned int id = 0; id < last_space_id; ++id) {
 237     const MutableSpace* space = _space_info[id].space();
 238     log.trace("%u %s "
 239               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
 240               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
 241               id, space_names[id],
 242               summary_data().addr_to_region_idx(space->bottom()),
 243               summary_data().addr_to_region_idx(space->top()),
 244               summary_data().addr_to_region_idx(space->end()),
 245               summary_data().addr_to_region_idx(_space_info[id].new_top()));
 246   }
 247 }
 248 
 249 static void
 250 print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)
 251 {
 252 #define REGION_IDX_FORMAT        SIZE_FORMAT_W(7)
 253 #define REGION_DATA_FORMAT       SIZE_FORMAT_W(5)
 254 
 255   ParallelCompactData& sd = PSParallelCompact::summary_data();
 256   size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;
 257   log_develop_trace(gc, compaction)(
 258       REGION_IDX_FORMAT " " PTR_FORMAT " "
 259       REGION_IDX_FORMAT " " PTR_FORMAT " "
 260       REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "
 261       REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",
 262       i, p2i(c->data_location()), dci, p2i(c->destination()),
 263       c->partial_obj_size(), c->live_obj_size(),
 264       c->data_size(), c->source_region(), c->destination_count());
 265 
 266 #undef  REGION_IDX_FORMAT
 267 #undef  REGION_DATA_FORMAT
 268 }
 269 
 270 void
 271 print_generic_summary_data(ParallelCompactData& summary_data,
 272                            HeapWord* const beg_addr,
 273                            HeapWord* const end_addr)
 274 {
 275   size_t total_words = 0;
 276   size_t i = summary_data.addr_to_region_idx(beg_addr);
 277   const size_t last = summary_data.addr_to_region_idx(end_addr);
 278   HeapWord* pdest = 0;
 279 
 280   while (i < last) {
 281     ParallelCompactData::RegionData* c = summary_data.region(i);
 282     if (c->data_size() != 0 || c->destination() != pdest) {
 283       print_generic_summary_region(i, c);
 284       total_words += c->data_size();
 285       pdest = c->destination();
 286     }
 287     ++i;
 288   }
 289 
 290   log_develop_trace(gc, compaction)("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
 291 }
 292 
 293 void
 294 PSParallelCompact::print_generic_summary_data(ParallelCompactData& summary_data,
 295                                               HeapWord* const beg_addr,
 296                                               HeapWord* const end_addr) {
 297   ::print_generic_summary_data(summary_data,beg_addr, end_addr);
 298 }
 299 
 300 void
 301 print_generic_summary_data(ParallelCompactData& summary_data,
 302                            SpaceInfo* space_info)
 303 {
 304   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 305     return;
 306   }
 307 
 308   for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
 309     const MutableSpace* space = space_info[id].space();
 310     print_generic_summary_data(summary_data, space->bottom(),
 311                                MAX2(space->top(), space_info[id].new_top()));
 312   }
 313 }
 314 
 315 static void
 316 print_initial_summary_data(ParallelCompactData& summary_data,
 317                            const MutableSpace* space) {
 318   if (space->top() == space->bottom()) {
 319     return;
 320   }
 321 
 322   const size_t region_size = ParallelCompactData::RegionSize;
 323   typedef ParallelCompactData::RegionData RegionData;
 324   HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());
 325   const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);
 326   const RegionData* c = summary_data.region(end_region - 1);
 327   HeapWord* end_addr = c->destination() + c->data_size();
 328   const size_t live_in_space = pointer_delta(end_addr, space->bottom());
 329 
 330   // Print (and count) the full regions at the beginning of the space.
 331   size_t full_region_count = 0;
 332   size_t i = summary_data.addr_to_region_idx(space->bottom());
 333   while (i < end_region && summary_data.region(i)->data_size() == region_size) {
 334     ParallelCompactData::RegionData* c = summary_data.region(i);
 335     log_develop_trace(gc, compaction)(
 336         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 337         i, p2i(c->destination()),
 338         c->partial_obj_size(), c->live_obj_size(),
 339         c->data_size(), c->source_region(), c->destination_count());
 340     ++full_region_count;
 341     ++i;
 342   }
 343 
 344   size_t live_to_right = live_in_space - full_region_count * region_size;
 345 
 346   double max_reclaimed_ratio = 0.0;
 347   size_t max_reclaimed_ratio_region = 0;
 348   size_t max_dead_to_right = 0;
 349   size_t max_live_to_right = 0;
 350 
 351   // Print the 'reclaimed ratio' for regions while there is something live in
 352   // the region or to the right of it.  The remaining regions are empty (and
 353   // uninteresting), and computing the ratio will result in division by 0.
 354   while (i < end_region && live_to_right > 0) {
 355     c = summary_data.region(i);
 356     HeapWord* const region_addr = summary_data.region_to_addr(i);
 357     const size_t used_to_right = pointer_delta(space->top(), region_addr);
 358     const size_t dead_to_right = used_to_right - live_to_right;
 359     const double reclaimed_ratio = double(dead_to_right) / live_to_right;
 360 
 361     if (reclaimed_ratio > max_reclaimed_ratio) {
 362             max_reclaimed_ratio = reclaimed_ratio;
 363             max_reclaimed_ratio_region = i;
 364             max_dead_to_right = dead_to_right;
 365             max_live_to_right = live_to_right;
 366     }
 367 
 368     ParallelCompactData::RegionData* c = summary_data.region(i);
 369     log_develop_trace(gc, compaction)(
 370         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d"
 371         "%12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
 372         i, p2i(c->destination()),
 373         c->partial_obj_size(), c->live_obj_size(),
 374         c->data_size(), c->source_region(), c->destination_count(),
 375         reclaimed_ratio, dead_to_right, live_to_right);
 376 
 377 
 378     live_to_right -= c->data_size();
 379     ++i;
 380   }
 381 
 382   // Any remaining regions are empty.  Print one more if there is one.
 383   if (i < end_region) {
 384     ParallelCompactData::RegionData* c = summary_data.region(i);
 385     log_develop_trace(gc, compaction)(
 386         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 387          i, p2i(c->destination()),
 388          c->partial_obj_size(), c->live_obj_size(),
 389          c->data_size(), c->source_region(), c->destination_count());
 390   }
 391 
 392   log_develop_trace(gc, compaction)("max:  " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
 393                                     max_reclaimed_ratio_region, max_dead_to_right, max_live_to_right, max_reclaimed_ratio);
 394 }
 395 
 396 static void
 397 print_initial_summary_data(ParallelCompactData& summary_data,
 398                            SpaceInfo* space_info) {
 399   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 400     return;
 401   }
 402 
 403   unsigned int id = PSParallelCompact::old_space_id;
 404   const MutableSpace* space;
 405   do {
 406     space = space_info[id].space();
 407     print_initial_summary_data(summary_data, space);
 408   } while (++id < PSParallelCompact::eden_space_id);
 409 
 410   do {
 411     space = space_info[id].space();
 412     print_generic_summary_data(summary_data, space->bottom(), space->top());
 413   } while (++id < PSParallelCompact::last_space_id);
 414 }
 415 #endif  // #ifndef PRODUCT
 416 
 417 ParallelCompactData::ParallelCompactData() :
 418   _heap_start(nullptr),
 419   DEBUG_ONLY(_heap_end(nullptr) COMMA)
 420   _region_vspace(nullptr),
 421   _reserved_byte_size(0),
 422   _region_data(nullptr),
 423   _region_count(0),
 424   _block_vspace(nullptr),
 425   _block_data(nullptr),
 426   _block_count(0) {}
 427 
 428 bool ParallelCompactData::initialize(MemRegion reserved_heap)
 429 {
 430   _heap_start = reserved_heap.start();
 431   const size_t heap_size = reserved_heap.word_size();
 432   DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
 433 
 434   assert(region_align_down(_heap_start) == _heap_start,
 435          "region start not aligned");
 436 
 437   bool result = initialize_region_data(heap_size) && initialize_block_data();
 438   return result;
 439 }
 440 
 441 PSVirtualSpace*
 442 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 443 {
 444   const size_t raw_bytes = count * element_size;
 445   const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
 446   const size_t granularity = os::vm_allocation_granularity();
 447   _reserved_byte_size = align_up(raw_bytes, MAX2(page_sz, granularity));
 448 
 449   const size_t rs_align = page_sz == os::vm_page_size() ? 0 :
 450     MAX2(page_sz, granularity);
 451   ReservedSpace rs(_reserved_byte_size, rs_align, page_sz);
 452   os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
 453                        rs.size(), page_sz);
 454 
 455   MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
 456 
 457   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
 458   if (vspace != 0) {
 459     if (vspace->expand_by(_reserved_byte_size)) {
 460       return vspace;
 461     }
 462     delete vspace;
 463     // Release memory reserved in the space.
 464     rs.release();
 465   }
 466 
 467   return 0;
 468 }
 469 
 470 bool ParallelCompactData::initialize_region_data(size_t heap_size)
 471 {
 472   assert(is_aligned(heap_size, RegionSize), "precondition");
 473 
 474   const size_t count = heap_size >> Log2RegionSize;
 475   _region_vspace = create_vspace(count, sizeof(RegionData));
 476   if (_region_vspace != 0) {
 477     _region_data = (RegionData*)_region_vspace->reserved_low_addr();
 478     _region_count = count;
 479     return true;
 480   }
 481   return false;
 482 }
 483 
 484 bool ParallelCompactData::initialize_block_data()
 485 {
 486   assert(_region_count != 0, "region data must be initialized first");
 487   const size_t count = _region_count << Log2BlocksPerRegion;
 488   _block_vspace = create_vspace(count, sizeof(BlockData));
 489   if (_block_vspace != 0) {
 490     _block_data = (BlockData*)_block_vspace->reserved_low_addr();
 491     _block_count = count;
 492     return true;
 493   }
 494   return false;
 495 }
 496 
 497 void ParallelCompactData::clear()
 498 {
 499   memset(_region_data, 0, _region_vspace->committed_size());
 500   memset(_block_data, 0, _block_vspace->committed_size());
 501 }
 502 
 503 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
 504   assert(beg_region <= _region_count, "beg_region out of range");
 505   assert(end_region <= _region_count, "end_region out of range");
 506   assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");
 507 
 508   const size_t region_cnt = end_region - beg_region;
 509   memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
 510 
 511   const size_t beg_block = beg_region * BlocksPerRegion;
 512   const size_t block_cnt = region_cnt * BlocksPerRegion;
 513   memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
 514 }
 515 
 516 HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const
 517 {
 518   const RegionData* cur_cp = region(region_idx);
 519   const RegionData* const end_cp = region(region_count() - 1);
 520 
 521   HeapWord* result = region_to_addr(region_idx);
 522   if (cur_cp < end_cp) {
 523     do {
 524       result += cur_cp->partial_obj_size();
 525     } while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);
 526   }
 527   return result;
 528 }
 529 
 530 void ParallelCompactData::add_obj(HeapWord* addr, size_t len)
 531 {
 532   const size_t obj_ofs = pointer_delta(addr, _heap_start);
 533   const size_t beg_region = obj_ofs >> Log2RegionSize;
 534   // end_region is inclusive
 535   const size_t end_region = (obj_ofs + len - 1) >> Log2RegionSize;
 536 
 537   if (beg_region == end_region) {
 538     // All in one region.
 539     _region_data[beg_region].add_live_obj(len);
 540     return;
 541   }
 542 
 543   // First region.
 544   const size_t beg_ofs = region_offset(addr);
 545   _region_data[beg_region].add_live_obj(RegionSize - beg_ofs);
 546 
 547   // Middle regions--completely spanned by this object.
 548   for (size_t region = beg_region + 1; region < end_region; ++region) {
 549     _region_data[region].set_partial_obj_size(RegionSize);
 550     _region_data[region].set_partial_obj_addr(addr);
 551   }
 552 
 553   // Last region.
 554   const size_t end_ofs = region_offset(addr + len - 1);
 555   _region_data[end_region].set_partial_obj_size(end_ofs + 1);
 556   _region_data[end_region].set_partial_obj_addr(addr);
 557 }
 558 
 559 void
 560 ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
 561 {
 562   assert(is_region_aligned(beg), "not RegionSize aligned");
 563   assert(is_region_aligned(end), "not RegionSize aligned");
 564 
 565   size_t cur_region = addr_to_region_idx(beg);
 566   const size_t end_region = addr_to_region_idx(end);
 567   HeapWord* addr = beg;
 568   while (cur_region < end_region) {
 569     _region_data[cur_region].set_destination(addr);
 570     _region_data[cur_region].set_destination_count(0);
 571     _region_data[cur_region].set_source_region(cur_region);
 572     _region_data[cur_region].set_data_location(addr);
 573 
 574     // Update live_obj_size so the region appears completely full.
 575     size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();
 576     _region_data[cur_region].set_live_obj_size(live_size);
 577 
 578     ++cur_region;
 579     addr += RegionSize;
 580   }
 581 }
 582 
 583 // Find the point at which a space can be split and, if necessary, record the
 584 // split point.
 585 //
 586 // If the current src region (which overflowed the destination space) doesn't
 587 // have a partial object, the split point is at the beginning of the current src
 588 // region (an "easy" split, no extra bookkeeping required).
 589 //
 590 // If the current src region has a partial object, the split point is in the
 591 // region where that partial object starts (call it the split_region).  If
 592 // split_region has a partial object, then the split point is just after that
 593 // partial object (a "hard" split where we have to record the split data and
 594 // zero the partial_obj_size field).  With a "hard" split, we know that the
 595 // partial_obj ends within split_region because the partial object that caused
 596 // the overflow starts in split_region.  If split_region doesn't have a partial
 597 // obj, then the split is at the beginning of split_region (another "easy"
 598 // split).
 599 HeapWord*
 600 ParallelCompactData::summarize_split_space(size_t src_region,
 601                                            SplitInfo& split_info,
 602                                            HeapWord* destination,
 603                                            HeapWord* target_end,
 604                                            HeapWord** target_next)
 605 {
 606   assert(destination <= target_end, "sanity");
 607   assert(destination + _region_data[src_region].data_size() > target_end,
 608     "region should not fit into target space");
 609   assert(is_region_aligned(target_end), "sanity");
 610 
 611   size_t split_region = src_region;
 612   HeapWord* split_destination = destination;
 613   size_t partial_obj_size = _region_data[src_region].partial_obj_size();
 614 
 615   if (destination + partial_obj_size > target_end) {
 616     // The split point is just after the partial object (if any) in the
 617     // src_region that contains the start of the object that overflowed the
 618     // destination space.
 619     //
 620     // Find the start of the "overflow" object and set split_region to the
 621     // region containing it.
 622     HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();
 623     split_region = addr_to_region_idx(overflow_obj);
 624 
 625     // Clear the source_region field of all destination regions whose first word
 626     // came from data after the split point (a non-null source_region field
 627     // implies a region must be filled).
 628     //
 629     // An alternative to the simple loop below:  clear during post_compact(),
 630     // which uses memcpy instead of individual stores, and is easy to
 631     // parallelize.  (The downside is that it clears the entire RegionData
 632     // object as opposed to just one field.)
 633     //
 634     // post_compact() would have to clear the summary data up to the highest
 635     // address that was written during the summary phase, which would be
 636     //
 637     //         max(top, max(new_top, clear_top))
 638     //
 639     // where clear_top is a new field in SpaceInfo.  Would have to set clear_top
 640     // to target_end.
 641     const RegionData* const sr = region(split_region);
 642     const size_t beg_idx =
 643       addr_to_region_idx(region_align_up(sr->destination() +
 644                                          sr->partial_obj_size()));
 645     const size_t end_idx = addr_to_region_idx(target_end);
 646 
 647     log_develop_trace(gc, compaction)("split:  clearing source_region field in [" SIZE_FORMAT ", " SIZE_FORMAT ")", beg_idx, end_idx);
 648     for (size_t idx = beg_idx; idx < end_idx; ++idx) {
 649       _region_data[idx].set_source_region(0);
 650     }
 651 
 652     // Set split_destination and partial_obj_size to reflect the split region.
 653     split_destination = sr->destination();
 654     partial_obj_size = sr->partial_obj_size();
 655   }
 656 
 657   // The split is recorded only if a partial object extends onto the region.
 658   if (partial_obj_size != 0) {
 659     _region_data[split_region].set_partial_obj_size(0);
 660     split_info.record(split_region, partial_obj_size, split_destination);
 661   }
 662 
 663   // Setup the continuation addresses.
 664   *target_next = split_destination + partial_obj_size;
 665   HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;
 666 
 667   if (log_develop_is_enabled(Trace, gc, compaction)) {
 668     const char * split_type = partial_obj_size == 0 ? "easy" : "hard";
 669     log_develop_trace(gc, compaction)("%s split:  src=" PTR_FORMAT " src_c=" SIZE_FORMAT " pos=" SIZE_FORMAT,
 670                                       split_type, p2i(source_next), split_region, partial_obj_size);
 671     log_develop_trace(gc, compaction)("%s split:  dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT " tn=" PTR_FORMAT,
 672                                       split_type, p2i(split_destination),
 673                                       addr_to_region_idx(split_destination),
 674                                       p2i(*target_next));
 675 
 676     if (partial_obj_size != 0) {
 677       HeapWord* const po_beg = split_info.destination();
 678       HeapWord* const po_end = po_beg + split_info.partial_obj_size();
 679       log_develop_trace(gc, compaction)("%s split:  po_beg=" PTR_FORMAT " " SIZE_FORMAT " po_end=" PTR_FORMAT " " SIZE_FORMAT,
 680                                         split_type,
 681                                         p2i(po_beg), addr_to_region_idx(po_beg),
 682                                         p2i(po_end), addr_to_region_idx(po_end));
 683     }
 684   }
 685 
 686   return source_next;
 687 }
 688 
 689 bool ParallelCompactData::summarize(SplitInfo& split_info,
 690                                     HeapWord* source_beg, HeapWord* source_end,
 691                                     HeapWord** source_next,
 692                                     HeapWord* target_beg, HeapWord* target_end,
 693                                     HeapWord** target_next)
 694 {
 695   HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
 696   log_develop_trace(gc, compaction)(
 697       "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
 698       "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
 699       p2i(source_beg), p2i(source_end), p2i(source_next_val),
 700       p2i(target_beg), p2i(target_end), p2i(*target_next));
 701 
 702   size_t cur_region = addr_to_region_idx(source_beg);
 703   const size_t end_region = addr_to_region_idx(region_align_up(source_end));
 704 
 705   HeapWord *dest_addr = target_beg;
 706   while (cur_region < end_region) {
 707     // The destination must be set even if the region has no data.
 708     _region_data[cur_region].set_destination(dest_addr);
 709 
 710     size_t words = _region_data[cur_region].data_size();
 711     if (words > 0) {
 712       // If cur_region does not fit entirely into the target space, find a point
 713       // at which the source space can be 'split' so that part is copied to the
 714       // target space and the rest is copied elsewhere.
 715       if (dest_addr + words > target_end) {
 716         assert(source_next != nullptr, "source_next is null when splitting");
 717         *source_next = summarize_split_space(cur_region, split_info, dest_addr,
 718                                              target_end, target_next);
 719         return false;
 720       }
 721 
 722       // Compute the destination_count for cur_region, and if necessary, update
 723       // source_region for a destination region.  The source_region field is
 724       // updated if cur_region is the first (left-most) region to be copied to a
 725       // destination region.
 726       //
 727       // The destination_count calculation is a bit subtle.  A region that has
 728       // data that compacts into itself does not count itself as a destination.
 729       // This maintains the invariant that a zero count means the region is
 730       // available and can be claimed and then filled.
 731       uint destination_count = 0;
 732       if (split_info.is_split(cur_region)) {
 733         // The current region has been split:  the partial object will be copied
 734         // to one destination space and the remaining data will be copied to
 735         // another destination space.  Adjust the initial destination_count and,
 736         // if necessary, set the source_region field if the partial object will
 737         // cross a destination region boundary.
 738         destination_count = split_info.destination_count();
 739         if (destination_count == 2) {
 740           size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());
 741           _region_data[dest_idx].set_source_region(cur_region);
 742         }
 743       }
 744 
 745       HeapWord* const last_addr = dest_addr + words - 1;
 746       const size_t dest_region_1 = addr_to_region_idx(dest_addr);
 747       const size_t dest_region_2 = addr_to_region_idx(last_addr);
 748 
 749       // Initially assume that the destination regions will be the same and
 750       // adjust the value below if necessary.  Under this assumption, if
 751       // cur_region == dest_region_2, then cur_region will be compacted
 752       // completely into itself.
 753       destination_count += cur_region == dest_region_2 ? 0 : 1;
 754       if (dest_region_1 != dest_region_2) {
 755         // Destination regions differ; adjust destination_count.
 756         destination_count += 1;
 757         // Data from cur_region will be copied to the start of dest_region_2.
 758         _region_data[dest_region_2].set_source_region(cur_region);
 759       } else if (is_region_aligned(dest_addr)) {
 760         // Data from cur_region will be copied to the start of the destination
 761         // region.
 762         _region_data[dest_region_1].set_source_region(cur_region);
 763       }
 764 
 765       _region_data[cur_region].set_destination_count(destination_count);
 766       _region_data[cur_region].set_data_location(region_to_addr(cur_region));
 767       dest_addr += words;
 768     }
 769 
 770     ++cur_region;
 771   }
 772 
 773   *target_next = dest_addr;
 774   return true;
 775 }
 776 
 777 HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr, ParCompactionManager* cm) const {
 778   assert(addr != nullptr, "Should detect null oop earlier");
 779   assert(ParallelScavengeHeap::heap()->is_in(addr), "not in heap");
 780   assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");
 781 
 782   // Region covering the object.
 783   RegionData* const region_ptr = addr_to_region_ptr(addr);
 784   HeapWord* result = region_ptr->destination();
 785 
 786   // If the entire Region is live, the new location is region->destination + the
 787   // offset of the object within in the Region.
 788 
 789   // Run some performance tests to determine if this special case pays off.  It
 790   // is worth it for pointers into the dense prefix.  If the optimization to
 791   // avoid pointer updates in regions that only point to the dense prefix is
 792   // ever implemented, this should be revisited.
 793   if (region_ptr->data_size() == RegionSize) {
 794     result += region_offset(addr);
 795     return result;
 796   }
 797 
 798   // Otherwise, the new location is region->destination + block offset + the
 799   // number of live words in the Block that are (a) to the left of addr and (b)
 800   // due to objects that start in the Block.
 801 
 802   // Fill in the block table if necessary.  This is unsynchronized, so multiple
 803   // threads may fill the block table for a region (harmless, since it is
 804   // idempotent).
 805   if (!region_ptr->blocks_filled()) {
 806     PSParallelCompact::fill_blocks(addr_to_region_idx(addr));
 807     region_ptr->set_blocks_filled();
 808   }
 809 
 810   HeapWord* const search_start = block_align_down(addr);
 811   const size_t block_offset = addr_to_block_ptr(addr)->offset();
 812 
 813   const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
 814   const size_t live = bitmap->live_words_in_range(cm, search_start, cast_to_oop(addr));
 815   result += block_offset + live;
 816   DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));
 817   return result;
 818 }
 819 
 820 #ifdef ASSERT
 821 void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
 822 {
 823   const size_t* const beg = (const size_t*)vspace->committed_low_addr();
 824   const size_t* const end = (const size_t*)vspace->committed_high_addr();
 825   for (const size_t* p = beg; p < end; ++p) {
 826     assert(*p == 0, "not zero");
 827   }
 828 }
 829 
 830 void ParallelCompactData::verify_clear()
 831 {
 832   verify_clear(_region_vspace);
 833   verify_clear(_block_vspace);
 834 }
 835 #endif  // #ifdef ASSERT
 836 
 837 STWGCTimer          PSParallelCompact::_gc_timer;
 838 ParallelOldTracer   PSParallelCompact::_gc_tracer;
 839 elapsedTimer        PSParallelCompact::_accumulated_time;
 840 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
 841 CollectorCounters*  PSParallelCompact::_counters = nullptr;
 842 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
 843 ParallelCompactData PSParallelCompact::_summary_data;
 844 
 845 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
 846 
 847 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
 848 
 849 void PSParallelCompact::post_initialize() {
 850   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 851   _span_based_discoverer.set_span(heap->reserved_region());
 852   _ref_processor =
 853     new ReferenceProcessor(&_span_based_discoverer,
 854                            ParallelGCThreads,   // mt processing degree
 855                            ParallelGCThreads,   // mt discovery degree
 856                            false,               // concurrent_discovery
 857                            &_is_alive_closure); // non-header is alive closure
 858 
 859   _counters = new CollectorCounters("Parallel full collection pauses", 1);
 860 
 861   // Initialize static fields in ParCompactionManager.
 862   ParCompactionManager::initialize(mark_bitmap());
 863 }
 864 
 865 bool PSParallelCompact::initialize() {
 866   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 867   MemRegion mr = heap->reserved_region();
 868 
 869   // Was the old gen get allocated successfully?
 870   if (!heap->old_gen()->is_allocated()) {
 871     return false;
 872   }
 873 
 874   initialize_space_info();
 875   initialize_dead_wood_limiter();
 876 
 877   if (!_mark_bitmap.initialize(mr)) {
 878     vm_shutdown_during_initialization(
 879       err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "
 880       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 881       _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
 882     return false;
 883   }
 884 
 885   if (!_summary_data.initialize(mr)) {
 886     vm_shutdown_during_initialization(
 887       err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "
 888       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 889       _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
 890     return false;
 891   }
 892 
 893   return true;
 894 }
 895 
 896 void PSParallelCompact::initialize_space_info()
 897 {
 898   memset(&_space_info, 0, sizeof(_space_info));
 899 
 900   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 901   PSYoungGen* young_gen = heap->young_gen();
 902 
 903   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
 904   _space_info[eden_space_id].set_space(young_gen->eden_space());
 905   _space_info[from_space_id].set_space(young_gen->from_space());
 906   _space_info[to_space_id].set_space(young_gen->to_space());
 907 
 908   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
 909 }
 910 
 911 void PSParallelCompact::initialize_dead_wood_limiter()
 912 {
 913   const size_t max = 100;
 914   _dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;
 915   _dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;
 916   _dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);
 917   DEBUG_ONLY(_dwl_initialized = true;)
 918   _dwl_adjustment = normal_distribution(1.0);
 919 }
 920 
 921 void
 922 PSParallelCompact::clear_data_covering_space(SpaceId id)
 923 {
 924   // At this point, top is the value before GC, new_top() is the value that will
 925   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
 926   // should be marked above top.  The summary data is cleared to the larger of
 927   // top & new_top.
 928   MutableSpace* const space = _space_info[id].space();
 929   HeapWord* const bot = space->bottom();
 930   HeapWord* const top = space->top();
 931   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
 932 
 933   const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
 934   const idx_t end_bit = _mark_bitmap.align_range_end(_mark_bitmap.addr_to_bit(top));
 935   _mark_bitmap.clear_range(beg_bit, end_bit);
 936 
 937   const size_t beg_region = _summary_data.addr_to_region_idx(bot);
 938   const size_t end_region =
 939     _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
 940   _summary_data.clear_range(beg_region, end_region);
 941 
 942   // Clear the data used to 'split' regions.
 943   SplitInfo& split_info = _space_info[id].split_info();
 944   if (split_info.is_valid()) {
 945     split_info.clear();
 946   }
 947   DEBUG_ONLY(split_info.verify_clear();)
 948 }
 949 
 950 void PSParallelCompact::pre_compact()
 951 {
 952   // Update the from & to space pointers in space_info, since they are swapped
 953   // at each young gen gc.  Do the update unconditionally (even though a
 954   // promotion failure does not swap spaces) because an unknown number of young
 955   // collections will have swapped the spaces an unknown number of times.
 956   GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
 957   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 958   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
 959   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
 960 
 961   // Increment the invocation count
 962   heap->increment_total_collections(true);
 963 
 964   CodeCache::on_gc_marking_cycle_start();
 965 
 966   heap->print_heap_before_gc();
 967   heap->trace_heap_before_gc(&_gc_tracer);
 968 
 969   // Fill in TLABs
 970   heap->ensure_parsability(true);  // retire TLABs
 971 
 972   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 973     Universe::verify("Before GC");
 974   }
 975 
 976   // Verify object start arrays
 977   if (VerifyObjectStartArray &&
 978       VerifyBeforeGC) {
 979     heap->old_gen()->verify_object_start_array();
 980   }
 981 
 982   DEBUG_ONLY(mark_bitmap()->verify_clear();)
 983   DEBUG_ONLY(summary_data().verify_clear();)
 984 
 985   ParCompactionManager::reset_all_bitmap_query_caches();
 986 }
 987 
 988 void PSParallelCompact::post_compact()
 989 {
 990   GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
 991   ParCompactionManager::remove_all_shadow_regions();
 992 
 993   CodeCache::on_gc_marking_cycle_finish();
 994   CodeCache::arm_all_nmethods();
 995 
 996   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
 997     // Clear the marking bitmap, summary data and split info.
 998     clear_data_covering_space(SpaceId(id));
 999     // Update top().  Must be done after clearing the bitmap and summary data.
1000     _space_info[id].publish_new_top();
1001   }
1002 
1003   ParCompactionManager::flush_all_string_dedup_requests();
1004 
1005   MutableSpace* const eden_space = _space_info[eden_space_id].space();
1006   MutableSpace* const from_space = _space_info[from_space_id].space();
1007   MutableSpace* const to_space   = _space_info[to_space_id].space();
1008 
1009   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1010   bool eden_empty = eden_space->is_empty();
1011 
1012   // Update heap occupancy information which is used as input to the soft ref
1013   // clearing policy at the next gc.
1014   Universe::heap()->update_capacity_and_used_at_gc();
1015 
1016   bool young_gen_empty = eden_empty && from_space->is_empty() &&
1017     to_space->is_empty();
1018 
1019   PSCardTable* ct = heap->card_table();
1020   MemRegion old_mr = heap->old_gen()->committed();
1021   if (young_gen_empty) {
1022     ct->clear_MemRegion(old_mr);
1023   } else {
1024     ct->dirty_MemRegion(old_mr);
1025   }
1026 
1027   {
1028     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1029     GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
1030     ClassLoaderDataGraph::purge(true /* at_safepoint */);
1031     DEBUG_ONLY(MetaspaceUtils::verify();)
1032   }
1033 
1034   // Need to clear claim bits for the next mark.
1035   ClassLoaderDataGraph::clear_claimed_marks();
1036 
1037   heap->prune_scavengable_nmethods();
1038 
1039 #if COMPILER2_OR_JVMCI
1040   DerivedPointerTable::update_pointers();
1041 #endif
1042 
1043   if (ZapUnusedHeapArea) {
1044     heap->gen_mangle_unused_area();
1045   }
1046 
1047   // Signal that we have completed a visit to all live objects.
1048   Universe::heap()->record_whole_heap_examined_timestamp();
1049 }
1050 
1051 HeapWord*
1052 PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,
1053                                                     bool maximum_compaction)
1054 {
1055   const size_t region_size = ParallelCompactData::RegionSize;
1056   const ParallelCompactData& sd = summary_data();
1057 
1058   const MutableSpace* const space = _space_info[id].space();
1059   HeapWord* const top_aligned_up = sd.region_align_up(space->top());
1060   const RegionData* const beg_cp = sd.addr_to_region_ptr(space->bottom());
1061   const RegionData* const end_cp = sd.addr_to_region_ptr(top_aligned_up);
1062 
1063   // Skip full regions at the beginning of the space--they are necessarily part
1064   // of the dense prefix.
1065   size_t full_count = 0;
1066   const RegionData* cp;
1067   for (cp = beg_cp; cp < end_cp && cp->data_size() == region_size; ++cp) {
1068     ++full_count;
1069   }
1070 
1071   const uint total_invocations = ParallelScavengeHeap::heap()->total_full_collections();
1072   assert(total_invocations >= _maximum_compaction_gc_num, "sanity");
1073   const size_t gcs_since_max = total_invocations - _maximum_compaction_gc_num;
1074   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;
1075   if (maximum_compaction || cp == end_cp || interval_ended) {
1076     _maximum_compaction_gc_num = total_invocations;
1077     return sd.region_to_addr(cp);
1078   }
1079 
1080   HeapWord* const new_top = _space_info[id].new_top();
1081   const size_t space_live = pointer_delta(new_top, space->bottom());
1082   const size_t space_used = space->used_in_words();
1083   const size_t space_capacity = space->capacity_in_words();
1084 
1085   const double cur_density = double(space_live) / space_capacity;
1086   const double deadwood_density =
1087     (1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;
1088   const size_t deadwood_goal = size_t(space_capacity * deadwood_density);
1089 
1090   log_develop_debug(gc, compaction)(
1091       "cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,
1092       cur_density, deadwood_density, deadwood_goal);
1093   log_develop_debug(gc, compaction)(
1094       "space_live=" SIZE_FORMAT " space_used=" SIZE_FORMAT " "
1095       "space_cap=" SIZE_FORMAT,
1096       space_live, space_used,
1097       space_capacity);
1098 
1099   // XXX - Use binary search?
1100   HeapWord* dense_prefix = sd.region_to_addr(cp);
1101   const RegionData* full_cp = cp;
1102   const RegionData* const top_cp = sd.addr_to_region_ptr(space->top() - 1);
1103   while (cp < end_cp) {
1104     HeapWord* region_destination = cp->destination();
1105     const size_t cur_deadwood = pointer_delta(dense_prefix, region_destination);
1106 
1107     log_develop_trace(gc, compaction)(
1108         "c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "
1109         "dp=" PTR_FORMAT " cdw=" SIZE_FORMAT_W(8),
1110         sd.region(cp), p2i(region_destination),
1111         p2i(dense_prefix), cur_deadwood);
1112 
1113     if (cur_deadwood >= deadwood_goal) {
1114       // Found the region that has the correct amount of deadwood to the left.
1115       // This typically occurs after crossing a fairly sparse set of regions, so
1116       // iterate backwards over those sparse regions, looking for the region
1117       // that has the lowest density of live objects 'to the right.'
1118       size_t space_to_left = sd.region(cp) * region_size;
1119       size_t live_to_left = space_to_left - cur_deadwood;
1120       size_t space_to_right = space_capacity - space_to_left;
1121       size_t live_to_right = space_live - live_to_left;
1122       double density_to_right = double(live_to_right) / space_to_right;
1123       while (cp > full_cp) {
1124         --cp;
1125         const size_t prev_region_live_to_right = live_to_right -
1126           cp->data_size();
1127         const size_t prev_region_space_to_right = space_to_right + region_size;
1128         double prev_region_density_to_right =
1129           double(prev_region_live_to_right) / prev_region_space_to_right;
1130         if (density_to_right <= prev_region_density_to_right) {
1131           return dense_prefix;
1132         }
1133 
1134         log_develop_trace(gc, compaction)(
1135             "backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "
1136             "pc_d2r=%10.8f",
1137             sd.region(cp), density_to_right,
1138             prev_region_density_to_right);
1139 
1140         dense_prefix -= region_size;
1141         live_to_right = prev_region_live_to_right;
1142         space_to_right = prev_region_space_to_right;
1143         density_to_right = prev_region_density_to_right;
1144       }
1145       return dense_prefix;
1146     }
1147 
1148     dense_prefix += region_size;
1149     ++cp;
1150   }
1151 
1152   return dense_prefix;
1153 }
1154 
1155 #ifndef PRODUCT
1156 void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,
1157                                                  const SpaceId id,
1158                                                  const bool maximum_compaction,
1159                                                  HeapWord* const addr)
1160 {
1161   const size_t region_idx = summary_data().addr_to_region_idx(addr);
1162   RegionData* const cp = summary_data().region(region_idx);
1163   const MutableSpace* const space = _space_info[id].space();
1164   HeapWord* const new_top = _space_info[id].new_top();
1165 
1166   const size_t space_live = pointer_delta(new_top, space->bottom());
1167   const size_t dead_to_left = pointer_delta(addr, cp->destination());
1168   const size_t space_cap = space->capacity_in_words();
1169   const double dead_to_left_pct = double(dead_to_left) / space_cap;
1170   const size_t live_to_right = new_top - cp->destination();
1171   const size_t dead_to_right = space->top() - addr - live_to_right;
1172 
1173   log_develop_debug(gc, compaction)(
1174       "%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "
1175       "spl=" SIZE_FORMAT " "
1176       "d2l=" SIZE_FORMAT " d2l%%=%6.4f "
1177       "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT " "
1178       "ratio=%10.8f",
1179       algorithm, p2i(addr), region_idx,
1180       space_live,
1181       dead_to_left, dead_to_left_pct,
1182       dead_to_right, live_to_right,
1183       double(dead_to_right) / live_to_right);
1184 }
1185 #endif  // #ifndef PRODUCT
1186 
1187 // Return a fraction indicating how much of the generation can be treated as
1188 // "dead wood" (i.e., not reclaimed).  The function uses a normal distribution
1189 // based on the density of live objects in the generation to determine a limit,
1190 // which is then adjusted so the return value is min_percent when the density is
1191 // 1.
1192 //
1193 // The following table shows some return values for a different values of the
1194 // standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and
1195 // min_percent is 1.
1196 //
1197 //                          fraction allowed as dead wood
1198 //         -----------------------------------------------------------------
1199 // density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=95
1200 // ------- ---------- ---------- ---------- ---------- ---------- ----------
1201 // 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1202 // 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1203 // 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1204 // 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1205 // 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1206 // 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1207 // 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1208 // 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1209 // 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1210 // 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1211 // 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.06431510
1212 // 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1213 // 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1214 // 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1215 // 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1216 // 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1217 // 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1218 // 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1219 // 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1220 // 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1221 // 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1222 
1223 double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)
1224 {
1225   assert(_dwl_initialized, "uninitialized");
1226 
1227   // The raw limit is the value of the normal distribution at x = density.
1228   const double raw_limit = normal_distribution(density);
1229 
1230   // Adjust the raw limit so it becomes the minimum when the density is 1.
1231   //
1232   // First subtract the adjustment value (which is simply the precomputed value
1233   // normal_distribution(1.0)); this yields a value of 0 when the density is 1.
1234   // Then add the minimum value, so the minimum is returned when the density is
1235   // 1.  Finally, prevent negative values, which occur when the mean is not 0.5.
1236   const double min = double(min_percent) / 100.0;
1237   const double limit = raw_limit - _dwl_adjustment + min;
1238   return MAX2(limit, 0.0);
1239 }
1240 
1241 ParallelCompactData::RegionData*
1242 PSParallelCompact::first_dead_space_region(const RegionData* beg,
1243                                            const RegionData* end)
1244 {
1245   const size_t region_size = ParallelCompactData::RegionSize;
1246   ParallelCompactData& sd = summary_data();
1247   size_t left = sd.region(beg);
1248   size_t right = end > beg ? sd.region(end) - 1 : left;
1249 
1250   // Binary search.
1251   while (left < right) {
1252     // Equivalent to (left + right) / 2, but does not overflow.
1253     const size_t middle = left + (right - left) / 2;
1254     RegionData* const middle_ptr = sd.region(middle);
1255     HeapWord* const dest = middle_ptr->destination();
1256     HeapWord* const addr = sd.region_to_addr(middle);
1257     assert(dest != nullptr, "sanity");
1258     assert(dest <= addr, "must move left");
1259 
1260     if (middle > left && dest < addr) {
1261       right = middle - 1;
1262     } else if (middle < right && middle_ptr->data_size() == region_size) {
1263       left = middle + 1;
1264     } else {
1265       return middle_ptr;
1266     }
1267   }
1268   return sd.region(left);
1269 }
1270 
1271 ParallelCompactData::RegionData*
1272 PSParallelCompact::dead_wood_limit_region(const RegionData* beg,
1273                                           const RegionData* end,
1274                                           size_t dead_words)
1275 {
1276   ParallelCompactData& sd = summary_data();
1277   size_t left = sd.region(beg);
1278   size_t right = end > beg ? sd.region(end) - 1 : left;
1279 
1280   // Binary search.
1281   while (left < right) {
1282     // Equivalent to (left + right) / 2, but does not overflow.
1283     const size_t middle = left + (right - left) / 2;
1284     RegionData* const middle_ptr = sd.region(middle);
1285     HeapWord* const dest = middle_ptr->destination();
1286     HeapWord* const addr = sd.region_to_addr(middle);
1287     assert(dest != nullptr, "sanity");
1288     assert(dest <= addr, "must move left");
1289 
1290     const size_t dead_to_left = pointer_delta(addr, dest);
1291     if (middle > left && dead_to_left > dead_words) {
1292       right = middle - 1;
1293     } else if (middle < right && dead_to_left < dead_words) {
1294       left = middle + 1;
1295     } else {
1296       return middle_ptr;
1297     }
1298   }
1299   return sd.region(left);
1300 }
1301 
1302 // The result is valid during the summary phase, after the initial summarization
1303 // of each space into itself, and before final summarization.
1304 inline double
1305 PSParallelCompact::reclaimed_ratio(const RegionData* const cp,
1306                                    HeapWord* const bottom,
1307                                    HeapWord* const top,
1308                                    HeapWord* const new_top)
1309 {
1310   ParallelCompactData& sd = summary_data();
1311 
1312   assert(cp != nullptr, "sanity");
1313   assert(bottom != nullptr, "sanity");
1314   assert(top != nullptr, "sanity");
1315   assert(new_top != nullptr, "sanity");
1316   assert(top >= new_top, "summary data problem?");
1317   assert(new_top > bottom, "space is empty; should not be here");
1318   assert(new_top >= cp->destination(), "sanity");
1319   assert(top >= sd.region_to_addr(cp), "sanity");
1320 
1321   HeapWord* const destination = cp->destination();
1322   const size_t dense_prefix_live  = pointer_delta(destination, bottom);
1323   const size_t compacted_region_live = pointer_delta(new_top, destination);
1324   const size_t compacted_region_used = pointer_delta(top,
1325                                                      sd.region_to_addr(cp));
1326   const size_t reclaimable = compacted_region_used - compacted_region_live;
1327 
1328   const double divisor = dense_prefix_live + 1.25 * compacted_region_live;
1329   return double(reclaimable) / divisor;
1330 }
1331 
1332 // Return the address of the end of the dense prefix, a.k.a. the start of the
1333 // compacted region.  The address is always on a region boundary.
1334 //
1335 // Completely full regions at the left are skipped, since no compaction can
1336 // occur in those regions.  Then the maximum amount of dead wood to allow is
1337 // computed, based on the density (amount live / capacity) of the generation;
1338 // the region with approximately that amount of dead space to the left is
1339 // identified as the limit region.  Regions between the last completely full
1340 // region and the limit region are scanned and the one that has the best
1341 // (maximum) reclaimed_ratio() is selected.
1342 HeapWord*
1343 PSParallelCompact::compute_dense_prefix(const SpaceId id,
1344                                         bool maximum_compaction)
1345 {
1346   const size_t region_size = ParallelCompactData::RegionSize;
1347   const ParallelCompactData& sd = summary_data();
1348 
1349   const MutableSpace* const space = _space_info[id].space();
1350   HeapWord* const top = space->top();
1351   HeapWord* const top_aligned_up = sd.region_align_up(top);
1352   HeapWord* const new_top = _space_info[id].new_top();
1353   HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);
1354   HeapWord* const bottom = space->bottom();
1355   const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);
1356   const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
1357   const RegionData* const new_top_cp =
1358     sd.addr_to_region_ptr(new_top_aligned_up);
1359 
1360   // Skip full regions at the beginning of the space--they are necessarily part
1361   // of the dense prefix.
1362   const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);
1363   assert(full_cp->destination() == sd.region_to_addr(full_cp) ||
1364          space->is_empty(), "no dead space allowed to the left");
1365   assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,
1366          "region must have dead space");
1367 
1368   // The gc number is saved whenever a maximum compaction is done, and used to
1369   // determine when the maximum compaction interval has expired.  This avoids
1370   // successive max compactions for different reasons.
1371   const uint total_invocations = ParallelScavengeHeap::heap()->total_full_collections();
1372   assert(total_invocations >= _maximum_compaction_gc_num, "sanity");
1373   const size_t gcs_since_max = total_invocations - _maximum_compaction_gc_num;
1374   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
1375     total_invocations == HeapFirstMaximumCompactionCount;
1376   if (maximum_compaction || full_cp == top_cp || interval_ended) {
1377     _maximum_compaction_gc_num = total_invocations;
1378     return sd.region_to_addr(full_cp);
1379   }
1380 
1381   const size_t space_live = pointer_delta(new_top, bottom);
1382   const size_t space_used = space->used_in_words();
1383   const size_t space_capacity = space->capacity_in_words();
1384 
1385   const double density = double(space_live) / double(space_capacity);
1386   const size_t min_percent_free = MarkSweepDeadRatio;
1387   const double limiter = dead_wood_limiter(density, min_percent_free);
1388   const size_t dead_wood_max = space_used - space_live;
1389   const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),
1390                                       dead_wood_max);
1391 
1392   log_develop_debug(gc, compaction)(
1393       "space_live=" SIZE_FORMAT " space_used=" SIZE_FORMAT " "
1394       "space_cap=" SIZE_FORMAT,
1395       space_live, space_used,
1396       space_capacity);
1397   log_develop_debug(gc, compaction)(
1398       "dead_wood_limiter(%6.4f, " SIZE_FORMAT ")=%6.4f "
1399       "dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
1400       density, min_percent_free, limiter,
1401       dead_wood_max, dead_wood_limit);
1402 
1403   // Locate the region with the desired amount of dead space to the left.
1404   const RegionData* const limit_cp =
1405     dead_wood_limit_region(full_cp, top_cp, dead_wood_limit);
1406 
1407   // Scan from the first region with dead space to the limit region and find the
1408   // one with the best (largest) reclaimed ratio.
1409   double best_ratio = 0.0;
1410   const RegionData* best_cp = full_cp;
1411   for (const RegionData* cp = full_cp; cp < limit_cp; ++cp) {
1412     double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);
1413     if (tmp_ratio > best_ratio) {
1414       best_cp = cp;
1415       best_ratio = tmp_ratio;
1416     }
1417   }
1418 
1419   return sd.region_to_addr(best_cp);
1420 }
1421 
1422 void PSParallelCompact::summarize_spaces_quick()
1423 {
1424   for (unsigned int i = 0; i < last_space_id; ++i) {
1425     const MutableSpace* space = _space_info[i].space();
1426     HeapWord** nta = _space_info[i].new_top_addr();
1427     bool result = _summary_data.summarize(_space_info[i].split_info(),
1428                                           space->bottom(), space->top(), nullptr,
1429                                           space->bottom(), space->end(), nta);
1430     assert(result, "space must fit into itself");
1431     _space_info[i].set_dense_prefix(space->bottom());
1432   }
1433 }
1434 
1435 void PSParallelCompact::fill_dense_prefix_end(SpaceId id)
1436 {
1437   HeapWord* const dense_prefix_end = dense_prefix(id);
1438   const RegionData* region = _summary_data.addr_to_region_ptr(dense_prefix_end);
1439   const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
1440   if (dead_space_crosses_boundary(region, dense_prefix_bit)) {
1441     // Only enough dead space is filled so that any remaining dead space to the
1442     // left is larger than the minimum filler object.  (The remainder is filled
1443     // during the copy/update phase.)
1444     //
1445     // The size of the dead space to the right of the boundary is not a
1446     // concern, since compaction will be able to use whatever space is
1447     // available.
1448     //
1449     // Here '||' is the boundary, 'x' represents a don't care bit and a box
1450     // surrounds the space to be filled with an object.
1451     //
1452     // In the 32-bit VM, each bit represents two 32-bit words:
1453     //                              +---+
1454     // a) beg_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
1455     //    end_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
1456     //                              +---+
1457     //
1458     // In the 64-bit VM, each bit represents one 64-bit word:
1459     //                              +------------+
1460     // b) beg_bits:  ...  x   x   x | 0   ||   0 | x  x  ...
1461     //    end_bits:  ...  x   x   1 | 0   ||   0 | x  x  ...
1462     //                              +------------+
1463     //                          +-------+
1464     // c) beg_bits:  ...  x   x | 0   0 | ||   0   x  x  ...
1465     //    end_bits:  ...  x   1 | 0   0 | ||   0   x  x  ...
1466     //                          +-------+
1467     //                      +-----------+
1468     // d) beg_bits:  ...  x | 0   0   0 | ||   0   x  x  ...
1469     //    end_bits:  ...  1 | 0   0   0 | ||   0   x  x  ...
1470     //                      +-----------+
1471     //                          +-------+
1472     // e) beg_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
1473     //    end_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
1474     //                          +-------+
1475 
1476     // Initially assume case a, c or e will apply.
1477     size_t obj_len = CollectedHeap::min_fill_size();
1478     HeapWord* obj_beg = dense_prefix_end - obj_len;
1479 
1480 #ifdef  _LP64
1481     if (MinObjAlignment > 1) { // object alignment > heap word size
1482       // Cases a, c or e.
1483     } else if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
1484       // Case b above.
1485       obj_beg = dense_prefix_end - 1;
1486     } else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&
1487                _mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {
1488       // Case d above.
1489       obj_beg = dense_prefix_end - 3;
1490       obj_len = 3;
1491     }
1492 #endif  // #ifdef _LP64
1493 
1494     CollectedHeap::fill_with_object(obj_beg, obj_len);
1495     _mark_bitmap.mark_obj(obj_beg, obj_len);
1496     _summary_data.add_obj(obj_beg, obj_len);
1497     assert(start_array(id) != nullptr, "sanity");
1498     start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
1499   }
1500 }
1501 
1502 void
1503 PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
1504 {
1505   assert(id < last_space_id, "id out of range");
1506   assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(),
1507          "should have been reset in summarize_spaces_quick()");
1508 
1509   const MutableSpace* space = _space_info[id].space();
1510   if (_space_info[id].new_top() != space->bottom()) {
1511     HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
1512     _space_info[id].set_dense_prefix(dense_prefix_end);
1513 
1514 #ifndef PRODUCT
1515     if (log_is_enabled(Debug, gc, compaction)) {
1516       print_dense_prefix_stats("ratio", id, maximum_compaction,
1517                                dense_prefix_end);
1518       HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);
1519       print_dense_prefix_stats("density", id, maximum_compaction, addr);
1520     }
1521 #endif  // #ifndef PRODUCT
1522 
1523     // Recompute the summary data, taking into account the dense prefix.  If
1524     // every last byte will be reclaimed, then the existing summary data which
1525     // compacts everything can be left in place.
1526     if (!maximum_compaction && dense_prefix_end != space->bottom()) {
1527       // If dead space crosses the dense prefix boundary, it is (at least
1528       // partially) filled with a dummy object, marked live and added to the
1529       // summary data.  This simplifies the copy/update phase and must be done
1530       // before the final locations of objects are determined, to prevent
1531       // leaving a fragment of dead space that is too small to fill.
1532       fill_dense_prefix_end(id);
1533 
1534       // Compute the destination of each Region, and thus each object.
1535       _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
1536       _summary_data.summarize(_space_info[id].split_info(),
1537                               dense_prefix_end, space->top(), nullptr,
1538                               dense_prefix_end, space->end(),
1539                               _space_info[id].new_top_addr());
1540     }
1541   }
1542 
1543   if (log_develop_is_enabled(Trace, gc, compaction)) {
1544     const size_t region_size = ParallelCompactData::RegionSize;
1545     HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
1546     const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);
1547     const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
1548     HeapWord* const new_top = _space_info[id].new_top();
1549     const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);
1550     const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
1551     log_develop_trace(gc, compaction)(
1552         "id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
1553         "dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
1554         "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
1555         id, space->capacity_in_words(), p2i(dense_prefix_end),
1556         dp_region, dp_words / region_size,
1557         cr_words / region_size, p2i(new_top));
1558   }
1559 }
1560 
1561 #ifndef PRODUCT
1562 void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
1563                                           HeapWord* dst_beg, HeapWord* dst_end,
1564                                           SpaceId src_space_id,
1565                                           HeapWord* src_beg, HeapWord* src_end)
1566 {
1567   log_develop_trace(gc, compaction)(
1568       "Summarizing %d [%s] into %d [%s]:  "
1569       "src=" PTR_FORMAT "-" PTR_FORMAT " "
1570       SIZE_FORMAT "-" SIZE_FORMAT " "
1571       "dst=" PTR_FORMAT "-" PTR_FORMAT " "
1572       SIZE_FORMAT "-" SIZE_FORMAT,
1573       src_space_id, space_names[src_space_id],
1574       dst_space_id, space_names[dst_space_id],
1575       p2i(src_beg), p2i(src_end),
1576       _summary_data.addr_to_region_idx(src_beg),
1577       _summary_data.addr_to_region_idx(src_end),
1578       p2i(dst_beg), p2i(dst_end),
1579       _summary_data.addr_to_region_idx(dst_beg),
1580       _summary_data.addr_to_region_idx(dst_end));
1581 }
1582 #endif  // #ifndef PRODUCT
1583 
1584 void PSParallelCompact::summary_phase(bool maximum_compaction)
1585 {
1586   GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
1587 
1588   // Quick summarization of each space into itself, to see how much is live.
1589   summarize_spaces_quick();
1590 
1591   log_develop_trace(gc, compaction)("summary phase:  after summarizing each space to self");
1592   NOT_PRODUCT(print_region_ranges());
1593   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1594 
1595   // The amount of live data that will end up in old space (assuming it fits).
1596   size_t old_space_total_live = 0;
1597   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1598     old_space_total_live += pointer_delta(_space_info[id].new_top(),
1599                                           _space_info[id].space()->bottom());
1600   }
1601 
1602   MutableSpace* const old_space = _space_info[old_space_id].space();
1603   const size_t old_capacity = old_space->capacity_in_words();
1604   if (old_space_total_live > old_capacity) {
1605     // XXX - should also try to expand
1606     maximum_compaction = true;
1607   }
1608 
1609   // Old generations.
1610   summarize_space(old_space_id, maximum_compaction);
1611 
1612   // Summarize the remaining spaces in the young gen.  The initial target space
1613   // is the old gen.  If a space does not fit entirely into the target, then the
1614   // remainder is compacted into the space itself and that space becomes the new
1615   // target.
1616   SpaceId dst_space_id = old_space_id;
1617   HeapWord* dst_space_end = old_space->end();
1618   HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
1619   for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
1620     const MutableSpace* space = _space_info[id].space();
1621     const size_t live = pointer_delta(_space_info[id].new_top(),
1622                                       space->bottom());
1623     const size_t available = pointer_delta(dst_space_end, *new_top_addr);
1624 
1625     NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,
1626                                   SpaceId(id), space->bottom(), space->top());)
1627     if (live > 0 && live <= available) {
1628       // All the live data will fit.
1629       bool done = _summary_data.summarize(_space_info[id].split_info(),
1630                                           space->bottom(), space->top(),
1631                                           nullptr,
1632                                           *new_top_addr, dst_space_end,
1633                                           new_top_addr);
1634       assert(done, "space must fit into old gen");
1635 
1636       // Reset the new_top value for the space.
1637       _space_info[id].set_new_top(space->bottom());
1638     } else if (live > 0) {
1639       // Attempt to fit part of the source space into the target space.
1640       HeapWord* next_src_addr = nullptr;
1641       bool done = _summary_data.summarize(_space_info[id].split_info(),
1642                                           space->bottom(), space->top(),
1643                                           &next_src_addr,
1644                                           *new_top_addr, dst_space_end,
1645                                           new_top_addr);
1646       assert(!done, "space should not fit into old gen");
1647       assert(next_src_addr != nullptr, "sanity");
1648 
1649       // The source space becomes the new target, so the remainder is compacted
1650       // within the space itself.
1651       dst_space_id = SpaceId(id);
1652       dst_space_end = space->end();
1653       new_top_addr = _space_info[id].new_top_addr();
1654       NOT_PRODUCT(summary_phase_msg(dst_space_id,
1655                                     space->bottom(), dst_space_end,
1656                                     SpaceId(id), next_src_addr, space->top());)
1657       done = _summary_data.summarize(_space_info[id].split_info(),
1658                                      next_src_addr, space->top(),
1659                                      nullptr,
1660                                      space->bottom(), dst_space_end,
1661                                      new_top_addr);
1662       assert(done, "space must fit when compacted into itself");
1663       assert(*new_top_addr <= space->top(), "usage should not grow");
1664     }
1665   }
1666 
1667   log_develop_trace(gc, compaction)("Summary_phase:  after final summarization");
1668   NOT_PRODUCT(print_region_ranges());
1669   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1670 }
1671 
1672 // This method should contain all heap-specific policy for invoking a full
1673 // collection.  invoke_no_policy() will only attempt to compact the heap; it
1674 // will do nothing further.  If we need to bail out for policy reasons, scavenge
1675 // before full gc, or any other specialized behavior, it needs to be added here.
1676 //
1677 // Note that this method should only be called from the vm_thread while at a
1678 // safepoint.
1679 //
1680 // Note that the all_soft_refs_clear flag in the soft ref policy
1681 // may be true because this method can be called without intervening
1682 // activity.  For example when the heap space is tight and full measure
1683 // are being taken to free space.
1684 bool PSParallelCompact::invoke(bool maximum_heap_compaction) {
1685   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
1686   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
1687          "should be in vm thread");
1688 
1689   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1690   assert(!heap->is_gc_active(), "not reentrant");
1691 
1692   IsGCActiveMark mark;
1693 
1694   if (ScavengeBeforeFullGC) {
1695     PSScavenge::invoke_no_policy();
1696   }
1697 
1698   const bool clear_all_soft_refs =
1699     heap->soft_ref_policy()->should_clear_all_soft_refs();
1700 
1701   return PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||
1702                                              maximum_heap_compaction);
1703 }
1704 
1705 // This method contains no policy. You should probably
1706 // be calling invoke() instead.
1707 bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
1708   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
1709   assert(ref_processor() != nullptr, "Sanity");
1710 
1711   if (GCLocker::check_active_before_gc()) {
1712     return false;
1713   }
1714 
1715   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1716 
1717   GCIdMark gc_id_mark;
1718   _gc_timer.register_gc_start();
1719   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
1720 
1721   GCCause::Cause gc_cause = heap->gc_cause();
1722   PSYoungGen* young_gen = heap->young_gen();
1723   PSOldGen* old_gen = heap->old_gen();
1724   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
1725 
1726   // The scope of casr should end after code that can change
1727   // SoftRefPolicy::_should_clear_all_soft_refs.
1728   ClearedAllSoftRefs casr(maximum_heap_compaction,
1729                           heap->soft_ref_policy());
1730 
1731   if (ZapUnusedHeapArea) {
1732     // Save information needed to minimize mangling
1733     heap->record_gen_tops_before_GC();
1734   }
1735 
1736   // Make sure data structures are sane, make the heap parsable, and do other
1737   // miscellaneous bookkeeping.
1738   pre_compact();
1739 
1740   const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
1741 
1742   {
1743     const uint active_workers =
1744       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
1745                                         ParallelScavengeHeap::heap()->workers().active_workers(),
1746                                         Threads::number_of_non_daemon_threads());
1747     ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
1748 
1749     GCTraceCPUTime tcpu(&_gc_tracer);
1750     GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
1751 
1752     heap->pre_full_gc_dump(&_gc_timer);
1753 
1754     TraceCollectorStats tcs(counters());
1755     TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
1756 
1757     if (log_is_enabled(Debug, gc, heap, exit)) {
1758       accumulated_time()->start();
1759     }
1760 
1761     // Let the size policy know we're starting
1762     size_policy->major_collection_begin();
1763 
1764 #if COMPILER2_OR_JVMCI
1765     DerivedPointerTable::clear();
1766 #endif
1767 
1768     ref_processor()->start_discovery(maximum_heap_compaction);
1769 
1770     ClassUnloadingContext ctx(1 /* num_nmethod_unlink_workers */,
1771                               false /* unregister_nmethods_during_purge */,
1772                               false /* lock_codeblob_free_separately */);
1773 
1774     marking_phase(&_gc_tracer);
1775 
1776     bool max_on_system_gc = UseMaximumCompactionOnSystemGC
1777       && GCCause::is_user_requested_gc(gc_cause);
1778     summary_phase(maximum_heap_compaction || max_on_system_gc);
1779 
1780 #if COMPILER2_OR_JVMCI
1781     assert(DerivedPointerTable::is_active(), "Sanity");
1782     DerivedPointerTable::set_active(false);
1783 #endif
1784 
1785     // adjust_roots() updates Universe::_intArrayKlassObj which is
1786     // needed by the compaction for filling holes in the dense prefix.
1787     adjust_roots();
1788 
1789     compact();
1790 
1791     ParCompactionManager::verify_all_region_stack_empty();
1792 
1793     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
1794     // done before resizing.
1795     post_compact();
1796 
1797     // Let the size policy know we're done
1798     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
1799 
1800     if (UseAdaptiveSizePolicy) {
1801       log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
1802       log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
1803                           old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
1804 
1805       // Don't check if the size_policy is ready here.  Let
1806       // the size_policy check that internally.
1807       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
1808           AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
1809         // Swap the survivor spaces if from_space is empty. The
1810         // resize_young_gen() called below is normally used after
1811         // a successful young GC and swapping of survivor spaces;
1812         // otherwise, it will fail to resize the young gen with
1813         // the current implementation.
1814         if (young_gen->from_space()->is_empty()) {
1815           young_gen->from_space()->clear(SpaceDecorator::Mangle);
1816           young_gen->swap_spaces();
1817         }
1818 
1819         // Calculate optimal free space amounts
1820         assert(young_gen->max_gen_size() >
1821           young_gen->from_space()->capacity_in_bytes() +
1822           young_gen->to_space()->capacity_in_bytes(),
1823           "Sizes of space in young gen are out-of-bounds");
1824 
1825         size_t young_live = young_gen->used_in_bytes();
1826         size_t eden_live = young_gen->eden_space()->used_in_bytes();
1827         size_t old_live = old_gen->used_in_bytes();
1828         size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
1829         size_t max_old_gen_size = old_gen->max_gen_size();
1830         size_t max_eden_size = young_gen->max_gen_size() -
1831           young_gen->from_space()->capacity_in_bytes() -
1832           young_gen->to_space()->capacity_in_bytes();
1833 
1834         // Used for diagnostics
1835         size_policy->clear_generation_free_space_flags();
1836 
1837         size_policy->compute_generations_free_space(young_live,
1838                                                     eden_live,
1839                                                     old_live,
1840                                                     cur_eden,
1841                                                     max_old_gen_size,
1842                                                     max_eden_size,
1843                                                     true /* full gc*/);
1844 
1845         size_policy->check_gc_overhead_limit(eden_live,
1846                                              max_old_gen_size,
1847                                              max_eden_size,
1848                                              true /* full gc*/,
1849                                              gc_cause,
1850                                              heap->soft_ref_policy());
1851 
1852         size_policy->decay_supplemental_growth(true /* full gc*/);
1853 
1854         heap->resize_old_gen(
1855           size_policy->calculated_old_free_size_in_bytes());
1856 
1857         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
1858                                size_policy->calculated_survivor_size_in_bytes());
1859       }
1860 
1861       log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
1862     }
1863 
1864     if (UsePerfData) {
1865       PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
1866       counters->update_counters();
1867       counters->update_old_capacity(old_gen->capacity_in_bytes());
1868       counters->update_young_capacity(young_gen->capacity_in_bytes());
1869     }
1870 
1871     heap->resize_all_tlabs();
1872 
1873     // Resize the metaspace capacity after a collection
1874     MetaspaceGC::compute_new_size();
1875 
1876     if (log_is_enabled(Debug, gc, heap, exit)) {
1877       accumulated_time()->stop();
1878     }
1879 
1880     heap->print_heap_change(pre_gc_values);
1881 
1882     // Track memory usage and detect low memory
1883     MemoryService::track_memory_usage();
1884     heap->update_counters();
1885 
1886     heap->post_full_gc_dump(&_gc_timer);
1887   }
1888 
1889   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1890     Universe::verify("After GC");
1891   }
1892 
1893   // Re-verify object start arrays
1894   if (VerifyObjectStartArray &&
1895       VerifyAfterGC) {
1896     old_gen->verify_object_start_array();
1897   }
1898 
1899   if (ZapUnusedHeapArea) {
1900     old_gen->object_space()->check_mangled_unused_area_complete();
1901   }
1902 
1903   heap->print_heap_after_gc();
1904   heap->trace_heap_after_gc(&_gc_tracer);
1905 
1906   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
1907 
1908   _gc_timer.register_gc_end();
1909 
1910   _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1911   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1912 
1913   return true;
1914 }
1915 
1916 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1917 private:
1918   uint _worker_id;
1919 
1920 public:
1921   PCAddThreadRootsMarkingTaskClosure(uint worker_id) : _worker_id(worker_id) { }
1922   void do_thread(Thread* thread) {
1923     assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1924 
1925     ResourceMark rm;
1926 
1927     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(_worker_id);
1928 
1929     PCMarkAndPushClosure mark_and_push_closure(cm);
1930     MarkingCodeBlobClosure mark_and_push_in_blobs(&mark_and_push_closure, !CodeBlobToOopClosure::FixRelocations, true /* keepalive nmethods */);
1931 
1932     thread->oops_do(&mark_and_push_closure, &mark_and_push_in_blobs);
1933 
1934     // Do the real work
1935     cm->follow_marking_stacks();
1936   }
1937 };
1938 
1939 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1940   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1941 
1942   ParCompactionManager* cm =
1943     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1944 
1945   do {
1946     oop obj = nullptr;
1947     ObjArrayTask task;
1948     if (ParCompactionManager::steal_objarray(worker_id,  task)) {
1949       cm->follow_array((objArrayOop)task.obj(), task.index());
1950     } else if (ParCompactionManager::steal(worker_id, obj)) {
1951       cm->follow_contents(obj);
1952     }
1953     cm->follow_marking_stacks();
1954   } while (!terminator.offer_termination());
1955 }
1956 
1957 class MarkFromRootsTask : public WorkerTask {
1958   StrongRootsScope _strong_roots_scope; // needed for Threads::possibly_parallel_threads_do
1959   OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1960   TaskTerminator _terminator;
1961   uint _active_workers;
1962 
1963 public:
1964   MarkFromRootsTask(uint active_workers) :
1965       WorkerTask("MarkFromRootsTask"),
1966       _strong_roots_scope(active_workers),
1967       _terminator(active_workers, ParCompactionManager::oop_task_queues()),
1968       _active_workers(active_workers) {}
1969 
1970   virtual void work(uint worker_id) {
1971     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1972     PCMarkAndPushClosure mark_and_push_closure(cm);
1973 
1974     {
1975       CLDToOopClosure cld_closure(&mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1976       ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1977 
1978       // Do the real work
1979       cm->follow_marking_stacks();
1980     }
1981 
1982     PCAddThreadRootsMarkingTaskClosure closure(worker_id);
1983     Threads::possibly_parallel_threads_do(true /* is_par */, &closure);
1984 
1985     // Mark from OopStorages
1986     {
1987       _oop_storage_set_par_state.oops_do(&mark_and_push_closure);
1988       // Do the real work
1989       cm->follow_marking_stacks();
1990     }
1991 
1992     if (_active_workers > 1) {
1993       steal_marking_work(_terminator, worker_id);
1994     }
1995   }
1996 };
1997 
1998 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
1999   TaskTerminator _terminator;
2000 
2001 public:
2002   ParallelCompactRefProcProxyTask(uint max_workers)
2003     : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
2004       _terminator(_max_workers, ParCompactionManager::oop_task_queues()) {}
2005 
2006   void work(uint worker_id) override {
2007     assert(worker_id < _max_workers, "sanity");
2008     ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
2009     PCMarkAndPushClosure keep_alive(cm);
2010     BarrierEnqueueDiscoveredFieldClosure enqueue;
2011     ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
2012     _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &keep_alive, &enqueue, &complete_gc);
2013   }
2014 
2015   void prepare_run_task_hook() override {
2016     _terminator.reset_for_reuse(_queue_count);
2017   }
2018 };
2019 
2020 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
2021   // Recursively traverse all live objects and mark them
2022   GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
2023 
2024   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2025 
2026   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
2027   {
2028     GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
2029 
2030     MarkFromRootsTask task(active_gc_threads);
2031     ParallelScavengeHeap::heap()->workers().run_task(&task);
2032   }
2033 
2034   // Process reference objects found during marking
2035   {
2036     GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
2037 
2038     ReferenceProcessorStats stats;
2039     ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
2040 
2041     ref_processor()->set_active_mt_degree(active_gc_threads);
2042     ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
2043     stats = ref_processor()->process_discovered_references(task, pt);
2044 
2045     gc_tracer->report_gc_reference_stats(stats);
2046     pt.print_all_references();
2047   }
2048 
2049   // This is the point where the entire marking should have completed.
2050   ParCompactionManager::verify_all_marking_stack_empty();
2051 
2052   {
2053     GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
2054     WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
2055                                 is_alive_closure(),
2056                                 &do_nothing_cl,
2057                                 1);
2058   }
2059 
2060   {
2061     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
2062 
2063     ClassUnloadingContext* ctx = ClassUnloadingContext::context();
2064 
2065     bool unloading_occurred;
2066     {
2067       CodeCache::UnlinkingScope scope(is_alive_closure());
2068 
2069       // Follow system dictionary roots and unload classes.
2070       unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
2071 
2072       // Unload nmethods.
2073       CodeCache::do_unloading(unloading_occurred);
2074     }
2075 
2076     {
2077       GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
2078       // Release unloaded nmethod's memory.
2079       ctx->purge_nmethods();
2080     }
2081     {
2082       GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
2083       ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
2084     }
2085     {
2086       GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
2087       ctx->free_code_blobs();
2088     }
2089 
2090     // Prune dead klasses from subklass/sibling/implementor lists.
2091     Klass::clean_weak_klass_links(unloading_occurred);
2092 
2093     // Clean JVMCI metadata handles.
2094     JVMCI_ONLY(JVMCI::do_unloading(unloading_occurred));
2095   }
2096 
2097   {
2098     GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
2099     _gc_tracer.report_object_count_after_gc(is_alive_closure(), &ParallelScavengeHeap::heap()->workers());
2100   }
2101 #if TASKQUEUE_STATS
2102   ParCompactionManager::oop_task_queues()->print_and_reset_taskqueue_stats("Oop Queue");
2103   ParCompactionManager::_objarray_task_queues->print_and_reset_taskqueue_stats("ObjArrayOop Queue");
2104 #endif
2105 }
2106 
2107 class PSAdjustTask final : public WorkerTask {
2108   SubTasksDone                               _sub_tasks;
2109   WeakProcessor::Task                        _weak_proc_task;
2110   OopStorageSetStrongParState<false, false>  _oop_storage_iter;
2111   uint                                       _nworkers;
2112 
2113   enum PSAdjustSubTask {
2114     PSAdjustSubTask_code_cache,
2115 
2116     PSAdjustSubTask_num_elements
2117   };
2118 
2119 public:
2120   PSAdjustTask(uint nworkers) :
2121     WorkerTask("PSAdjust task"),
2122     _sub_tasks(PSAdjustSubTask_num_elements),
2123     _weak_proc_task(nworkers),
2124     _nworkers(nworkers) {
2125 
2126     ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
2127     if (nworkers > 1) {
2128       Threads::change_thread_claim_token();
2129     }
2130   }
2131 
2132   ~PSAdjustTask() {
2133     Threads::assert_all_threads_claimed();
2134   }
2135 
2136   void work(uint worker_id) {
2137     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2138     PCAdjustPointerClosure adjust(cm);
2139     {
2140       ResourceMark rm;
2141       Threads::possibly_parallel_oops_do(_nworkers > 1, &adjust, nullptr);
2142     }
2143     _oop_storage_iter.oops_do(&adjust);
2144     {
2145       CLDToOopClosure cld_closure(&adjust, ClassLoaderData::_claim_stw_fullgc_adjust);
2146       ClassLoaderDataGraph::cld_do(&cld_closure);
2147     }
2148     {
2149       AlwaysTrueClosure always_alive;
2150       _weak_proc_task.work(worker_id, &always_alive, &adjust);
2151     }
2152     if (_sub_tasks.try_claim_task(PSAdjustSubTask_code_cache)) {
2153       CodeBlobToOopClosure adjust_code(&adjust, CodeBlobToOopClosure::FixRelocations);
2154       CodeCache::blobs_do(&adjust_code);
2155     }
2156     _sub_tasks.all_tasks_claimed();
2157   }
2158 };
2159 
2160 void PSParallelCompact::adjust_roots() {
2161   // Adjust the pointers to reflect the new locations
2162   GCTraceTime(Info, gc, phases) tm("Adjust Roots", &_gc_timer);
2163   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
2164   PSAdjustTask task(nworkers);
2165   ParallelScavengeHeap::heap()->workers().run_task(&task);
2166 }
2167 
2168 // Helper class to print 8 region numbers per line and then print the total at the end.
2169 class FillableRegionLogger : public StackObj {
2170 private:
2171   Log(gc, compaction) log;
2172   static const int LineLength = 8;
2173   size_t _regions[LineLength];
2174   int _next_index;
2175   bool _enabled;
2176   size_t _total_regions;
2177 public:
2178   FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
2179   ~FillableRegionLogger() {
2180     log.trace(SIZE_FORMAT " initially fillable regions", _total_regions);
2181   }
2182 
2183   void print_line() {
2184     if (!_enabled || _next_index == 0) {
2185       return;
2186     }
2187     FormatBuffer<> line("Fillable: ");
2188     for (int i = 0; i < _next_index; i++) {
2189       line.append(" " SIZE_FORMAT_W(7), _regions[i]);
2190     }
2191     log.trace("%s", line.buffer());
2192     _next_index = 0;
2193   }
2194 
2195   void handle(size_t region) {
2196     if (!_enabled) {
2197       return;
2198     }
2199     _regions[_next_index++] = region;
2200     if (_next_index == LineLength) {
2201       print_line();
2202     }
2203     _total_regions++;
2204   }
2205 };
2206 
2207 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
2208 {
2209   GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
2210 
2211   // Find the threads that are active
2212   uint worker_id = 0;
2213 
2214   // Find all regions that are available (can be filled immediately) and
2215   // distribute them to the thread stacks.  The iteration is done in reverse
2216   // order (high to low) so the regions will be removed in ascending order.
2217 
2218   const ParallelCompactData& sd = PSParallelCompact::summary_data();
2219 
2220   // id + 1 is used to test termination so unsigned  can
2221   // be used with an old_space_id == 0.
2222   FillableRegionLogger region_logger;
2223   for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {
2224     SpaceInfo* const space_info = _space_info + id;
2225     HeapWord* const new_top = space_info->new_top();
2226 
2227     const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
2228     const size_t end_region =
2229       sd.addr_to_region_idx(sd.region_align_up(new_top));
2230 
2231     for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
2232       if (sd.region(cur)->claim_unsafe()) {
2233         ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2234         bool result = sd.region(cur)->mark_normal();
2235         assert(result, "Must succeed at this point.");
2236         cm->region_stack()->push(cur);
2237         region_logger.handle(cur);
2238         // Assign regions to tasks in round-robin fashion.
2239         if (++worker_id == parallel_gc_threads) {
2240           worker_id = 0;
2241         }
2242       }
2243     }
2244     region_logger.print_line();
2245   }
2246 }
2247 
2248 class TaskQueue : StackObj {
2249   volatile uint _counter;
2250   uint _size;
2251   uint _insert_index;
2252   PSParallelCompact::UpdateDensePrefixTask* _backing_array;
2253 public:
2254   explicit TaskQueue(uint size) : _counter(0), _size(size), _insert_index(0), _backing_array(nullptr) {
2255     _backing_array = NEW_C_HEAP_ARRAY(PSParallelCompact::UpdateDensePrefixTask, _size, mtGC);
2256   }
2257   ~TaskQueue() {
2258     assert(_counter >= _insert_index, "not all queue elements were claimed");
2259     FREE_C_HEAP_ARRAY(T, _backing_array);
2260   }
2261 
2262   void push(const PSParallelCompact::UpdateDensePrefixTask& value) {
2263     assert(_insert_index < _size, "too small backing array");
2264     _backing_array[_insert_index++] = value;
2265   }
2266 
2267   bool try_claim(PSParallelCompact::UpdateDensePrefixTask& reference) {
2268     uint claimed = Atomic::fetch_then_add(&_counter, 1u);
2269     if (claimed < _insert_index) {
2270       reference = _backing_array[claimed];
2271       return true;
2272     } else {
2273       return false;
2274     }
2275   }
2276 };
2277 
2278 #define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4
2279 
2280 void PSParallelCompact::enqueue_dense_prefix_tasks(TaskQueue& task_queue,
2281                                                    uint parallel_gc_threads) {
2282   GCTraceTime(Trace, gc, phases) tm("Dense Prefix Task Setup", &_gc_timer);
2283 
2284   ParallelCompactData& sd = PSParallelCompact::summary_data();
2285 
2286   // Iterate over all the spaces adding tasks for updating
2287   // regions in the dense prefix.  Assume that 1 gc thread
2288   // will work on opening the gaps and the remaining gc threads
2289   // will work on the dense prefix.
2290   unsigned int space_id;
2291   for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {
2292     HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
2293     const MutableSpace* const space = _space_info[space_id].space();
2294 
2295     if (dense_prefix_end == space->bottom()) {
2296       // There is no dense prefix for this space.
2297       continue;
2298     }
2299 
2300     // The dense prefix is before this region.
2301     size_t region_index_end_dense_prefix =
2302         sd.addr_to_region_idx(dense_prefix_end);
2303     RegionData* const dense_prefix_cp =
2304       sd.region(region_index_end_dense_prefix);
2305     assert(dense_prefix_end == space->end() ||
2306            dense_prefix_cp->available() ||
2307            dense_prefix_cp->claimed(),
2308            "The region after the dense prefix should always be ready to fill");
2309 
2310     size_t region_index_start = sd.addr_to_region_idx(space->bottom());
2311 
2312     // Is there dense prefix work?
2313     size_t total_dense_prefix_regions =
2314       region_index_end_dense_prefix - region_index_start;
2315     // How many regions of the dense prefix should be given to
2316     // each thread?
2317     if (total_dense_prefix_regions > 0) {
2318       uint tasks_for_dense_prefix = 1;
2319       if (total_dense_prefix_regions <=
2320           (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
2321         // Don't over partition.  This assumes that
2322         // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
2323         // so there are not many regions to process.
2324         tasks_for_dense_prefix = parallel_gc_threads;
2325       } else {
2326         // Over partition
2327         tasks_for_dense_prefix = parallel_gc_threads *
2328           PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
2329       }
2330       size_t regions_per_thread = total_dense_prefix_regions /
2331         tasks_for_dense_prefix;
2332       // Give each thread at least 1 region.
2333       if (regions_per_thread == 0) {
2334         regions_per_thread = 1;
2335       }
2336 
2337       for (uint k = 0; k < tasks_for_dense_prefix; k++) {
2338         if (region_index_start >= region_index_end_dense_prefix) {
2339           break;
2340         }
2341         // region_index_end is not processed
2342         size_t region_index_end = MIN2(region_index_start + regions_per_thread,
2343                                        region_index_end_dense_prefix);
2344         task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
2345                                               region_index_start,
2346                                               region_index_end));
2347         region_index_start = region_index_end;
2348       }
2349     }
2350     // This gets any part of the dense prefix that did not
2351     // fit evenly.
2352     if (region_index_start < region_index_end_dense_prefix) {
2353       task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
2354                                             region_index_start,
2355                                             region_index_end_dense_prefix));
2356     }
2357   }
2358 }
2359 
2360 #ifdef ASSERT
2361 // Write a histogram of the number of times the block table was filled for a
2362 // region.
2363 void PSParallelCompact::write_block_fill_histogram()
2364 {
2365   if (!log_develop_is_enabled(Trace, gc, compaction)) {
2366     return;
2367   }
2368 
2369   Log(gc, compaction) log;
2370   ResourceMark rm;
2371   LogStream ls(log.trace());
2372   outputStream* out = &ls;
2373 
2374   typedef ParallelCompactData::RegionData rd_t;
2375   ParallelCompactData& sd = summary_data();
2376 
2377   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2378     MutableSpace* const spc = _space_info[id].space();
2379     if (spc->bottom() != spc->top()) {
2380       const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());
2381       HeapWord* const top_aligned_up = sd.region_align_up(spc->top());
2382       const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);
2383 
2384       size_t histo[5] = { 0, 0, 0, 0, 0 };
2385       const size_t histo_len = sizeof(histo) / sizeof(size_t);
2386       const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));
2387 
2388       for (const rd_t* cur = beg; cur < end; ++cur) {
2389         ++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];
2390       }
2391       out->print("Block fill histogram: %u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);
2392       for (size_t i = 0; i < histo_len; ++i) {
2393         out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",
2394                    histo[i], 100.0 * histo[i] / region_cnt);
2395       }
2396       out->cr();
2397     }
2398   }
2399 }
2400 #endif // #ifdef ASSERT
2401 
2402 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
2403   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
2404 
2405   ParCompactionManager* cm =
2406     ParCompactionManager::gc_thread_compaction_manager(worker_id);
2407 
2408   // Drain the stacks that have been preloaded with regions
2409   // that are ready to fill.
2410 
2411   cm->drain_region_stacks();
2412 
2413   guarantee(cm->region_stack()->is_empty(), "Not empty");
2414 
2415   size_t region_index = 0;
2416 
2417   while (true) {
2418     if (ParCompactionManager::steal(worker_id, region_index)) {
2419       PSParallelCompact::fill_and_update_region(cm, region_index);
2420       cm->drain_region_stacks();
2421     } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
2422       // Fill and update an unavailable region with the help of a shadow region
2423       PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
2424       cm->drain_region_stacks();
2425     } else {
2426       if (terminator->offer_termination()) {
2427         break;
2428       }
2429       // Go around again.
2430     }
2431   }
2432 }
2433 
2434 class UpdateDensePrefixAndCompactionTask: public WorkerTask {
2435   TaskQueue& _tq;
2436   TaskTerminator _terminator;
2437 
2438 public:
2439   UpdateDensePrefixAndCompactionTask(TaskQueue& tq, uint active_workers) :
2440       WorkerTask("UpdateDensePrefixAndCompactionTask"),
2441       _tq(tq),
2442       _terminator(active_workers, ParCompactionManager::region_task_queues()) {
2443   }
2444   virtual void work(uint worker_id) {
2445     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2446 
2447     for (PSParallelCompact::UpdateDensePrefixTask task; _tq.try_claim(task); /* empty */) {
2448       PSParallelCompact::update_and_deadwood_in_dense_prefix(cm,
2449                                                              task._space_id,
2450                                                              task._region_index_start,
2451                                                              task._region_index_end);
2452     }
2453 
2454     // Once a thread has drained it's stack, it should try to steal regions from
2455     // other threads.
2456     compaction_with_stealing_work(&_terminator, worker_id);
2457 
2458     // At this point all regions have been compacted, so it's now safe
2459     // to update the deferred objects that cross region boundaries.
2460     cm->drain_deferred_objects();
2461   }
2462 };
2463 
2464 void PSParallelCompact::compact() {
2465   GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
2466 
2467   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
2468   PSOldGen* old_gen = heap->old_gen();
2469   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2470 
2471   // for [0..last_space_id)
2472   //     for [0..active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)
2473   //         push
2474   //     push
2475   //
2476   // max push count is thus: last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1)
2477   TaskQueue task_queue(last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1));
2478   initialize_shadow_regions(active_gc_threads);
2479   prepare_region_draining_tasks(active_gc_threads);
2480   enqueue_dense_prefix_tasks(task_queue, active_gc_threads);
2481 
2482   {
2483     GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
2484 
2485     UpdateDensePrefixAndCompactionTask task(task_queue, active_gc_threads);
2486     ParallelScavengeHeap::heap()->workers().run_task(&task);
2487 
2488 #ifdef  ASSERT
2489     // Verify that all regions have been processed.
2490     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2491       verify_complete(SpaceId(id));
2492     }
2493 #endif
2494   }
2495 
2496   DEBUG_ONLY(write_block_fill_histogram());
2497 }
2498 
2499 #ifdef  ASSERT
2500 void PSParallelCompact::verify_complete(SpaceId space_id) {
2501   // All Regions between space bottom() to new_top() should be marked as filled
2502   // and all Regions between new_top() and top() should be available (i.e.,
2503   // should have been emptied).
2504   ParallelCompactData& sd = summary_data();
2505   SpaceInfo si = _space_info[space_id];
2506   HeapWord* new_top_addr = sd.region_align_up(si.new_top());
2507   HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
2508   const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());
2509   const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
2510   const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
2511 
2512   bool issued_a_warning = false;
2513 
2514   size_t cur_region;
2515   for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
2516     const RegionData* const c = sd.region(cur_region);
2517     if (!c->completed()) {
2518       log_warning(gc)("region " SIZE_FORMAT " not filled: destination_count=%u",
2519                       cur_region, c->destination_count());
2520       issued_a_warning = true;
2521     }
2522   }
2523 
2524   for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
2525     const RegionData* const c = sd.region(cur_region);
2526     if (!c->available()) {
2527       log_warning(gc)("region " SIZE_FORMAT " not empty: destination_count=%u",
2528                       cur_region, c->destination_count());
2529       issued_a_warning = true;
2530     }
2531   }
2532 
2533   if (issued_a_warning) {
2534     print_region_ranges();
2535   }
2536 }
2537 #endif  // #ifdef ASSERT
2538 
2539 inline void UpdateOnlyClosure::do_addr(HeapWord* addr) {
2540   _start_array->update_for_block(addr, addr + cast_to_oop(addr)->size());
2541   compaction_manager()->update_contents(cast_to_oop(addr));
2542 }
2543 
2544 // Update interior oops in the ranges of regions [beg_region, end_region).
2545 void
2546 PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
2547                                                        SpaceId space_id,
2548                                                        size_t beg_region,
2549                                                        size_t end_region) {
2550   ParallelCompactData& sd = summary_data();
2551   ParMarkBitMap* const mbm = mark_bitmap();
2552 
2553   HeapWord* beg_addr = sd.region_to_addr(beg_region);
2554   HeapWord* const end_addr = sd.region_to_addr(end_region);
2555   assert(beg_region <= end_region, "bad region range");
2556   assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");
2557 
2558 #ifdef  ASSERT
2559   // Claim the regions to avoid triggering an assert when they are marked as
2560   // filled.
2561   for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {
2562     assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");
2563   }
2564 #endif  // #ifdef ASSERT
2565 
2566   if (beg_addr != space(space_id)->bottom()) {
2567     // Find the first live object or block of dead space that *starts* in this
2568     // range of regions.  If a partial object crosses onto the region, skip it;
2569     // it will be marked for 'deferred update' when the object head is
2570     // processed.  If dead space crosses onto the region, it is also skipped; it
2571     // will be filled when the prior region is processed.  If neither of those
2572     // apply, the first word in the region is the start of a live object or dead
2573     // space.
2574     assert(beg_addr > space(space_id)->bottom(), "sanity");
2575     const RegionData* const cp = sd.region(beg_region);
2576     if (cp->partial_obj_size() != 0) {
2577       beg_addr = sd.partial_obj_end(beg_region);
2578     } else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {
2579       beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
2580     }
2581   }
2582 
2583   if (beg_addr < end_addr) {
2584     // A live object or block of dead space starts in this range of Regions.
2585      HeapWord* const dense_prefix_end = dense_prefix(space_id);
2586 
2587     // Create closures and iterate.
2588     UpdateOnlyClosure update_closure(mbm, cm, space_id);
2589     FillClosure fill_closure(cm, space_id);
2590     ParMarkBitMap::IterationStatus status;
2591     status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,
2592                           dense_prefix_end);
2593     if (status == ParMarkBitMap::incomplete) {
2594       update_closure.do_addr(update_closure.source());
2595     }
2596   }
2597 
2598   // Mark the regions as filled.
2599   RegionData* const beg_cp = sd.region(beg_region);
2600   RegionData* const end_cp = sd.region(end_region);
2601   for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {
2602     cp->set_completed();
2603   }
2604 }
2605 
2606 // Return the SpaceId for the space containing addr.  If addr is not in the
2607 // heap, last_space_id is returned.  In debug mode it expects the address to be
2608 // in the heap and asserts such.
2609 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
2610   assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
2611 
2612   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2613     if (_space_info[id].space()->contains(addr)) {
2614       return SpaceId(id);
2615     }
2616   }
2617 
2618   assert(false, "no space contains the addr");
2619   return last_space_id;
2620 }
2621 
2622 void PSParallelCompact::update_deferred_object(ParCompactionManager* cm, HeapWord *addr) {
2623 #ifdef ASSERT
2624   ParallelCompactData& sd = summary_data();
2625   size_t region_idx = sd.addr_to_region_idx(addr);
2626   assert(sd.region(region_idx)->completed(), "first region must be completed before deferred updates");
2627   assert(sd.region(region_idx + 1)->completed(), "second region must be completed before deferred updates");
2628 #endif
2629 
2630   const SpaceInfo* const space_info = _space_info + space_id(addr);
2631   ObjectStartArray* const start_array = space_info->start_array();
2632   if (start_array != nullptr) {
2633     start_array->update_for_block(addr, addr + cast_to_oop(addr)->size());
2634   }
2635 
2636   cm->update_contents(cast_to_oop(addr));
2637   assert(oopDesc::is_oop(cast_to_oop(addr)), "Expected an oop at " PTR_FORMAT, p2i(cast_to_oop(addr)));
2638 }
2639 
2640 // Skip over count live words starting from beg, and return the address of the
2641 // next live word.  Unless marked, the word corresponding to beg is assumed to
2642 // be dead.  Callers must either ensure beg does not correspond to the middle of
2643 // an object, or account for those live words in some other way.  Callers must
2644 // also ensure that there are enough live words in the range [beg, end) to skip.
2645 HeapWord*
2646 PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
2647 {
2648   assert(count > 0, "sanity");
2649 
2650   ParMarkBitMap* m = mark_bitmap();
2651   idx_t bits_to_skip = m->words_to_bits(count);
2652   idx_t cur_beg = m->addr_to_bit(beg);
2653   const idx_t search_end = m->align_range_end(m->addr_to_bit(end));
2654 
2655   do {
2656     cur_beg = m->find_obj_beg(cur_beg, search_end);
2657     idx_t cur_end = m->find_obj_end(cur_beg, search_end);
2658     const size_t obj_bits = cur_end - cur_beg + 1;
2659     if (obj_bits > bits_to_skip) {
2660       return m->bit_to_addr(cur_beg + bits_to_skip);
2661     }
2662     bits_to_skip -= obj_bits;
2663     cur_beg = cur_end + 1;
2664   } while (bits_to_skip > 0);
2665 
2666   // Skipping the desired number of words landed just past the end of an object.
2667   // Find the start of the next object.
2668   cur_beg = m->find_obj_beg(cur_beg, search_end);
2669   assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
2670   return m->bit_to_addr(cur_beg);
2671 }
2672 
2673 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
2674                                             SpaceId src_space_id,
2675                                             size_t src_region_idx)
2676 {
2677   assert(summary_data().is_region_aligned(dest_addr), "not aligned");
2678 
2679   const SplitInfo& split_info = _space_info[src_space_id].split_info();
2680   if (split_info.dest_region_addr() == dest_addr) {
2681     // The partial object ending at the split point contains the first word to
2682     // be copied to dest_addr.
2683     return split_info.first_src_addr();
2684   }
2685 
2686   const ParallelCompactData& sd = summary_data();
2687   ParMarkBitMap* const bitmap = mark_bitmap();
2688   const size_t RegionSize = ParallelCompactData::RegionSize;
2689 
2690   assert(sd.is_region_aligned(dest_addr), "not aligned");
2691   const RegionData* const src_region_ptr = sd.region(src_region_idx);
2692   const size_t partial_obj_size = src_region_ptr->partial_obj_size();
2693   HeapWord* const src_region_destination = src_region_ptr->destination();
2694 
2695   assert(dest_addr >= src_region_destination, "wrong src region");
2696   assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
2697 
2698   HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);
2699   HeapWord* const src_region_end = src_region_beg + RegionSize;
2700 
2701   HeapWord* addr = src_region_beg;
2702   if (dest_addr == src_region_destination) {
2703     // Return the first live word in the source region.
2704     if (partial_obj_size == 0) {
2705       addr = bitmap->find_obj_beg(addr, src_region_end);
2706       assert(addr < src_region_end, "no objects start in src region");
2707     }
2708     return addr;
2709   }
2710 
2711   // Must skip some live data.
2712   size_t words_to_skip = dest_addr - src_region_destination;
2713   assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");
2714 
2715   if (partial_obj_size >= words_to_skip) {
2716     // All the live words to skip are part of the partial object.
2717     addr += words_to_skip;
2718     if (partial_obj_size == words_to_skip) {
2719       // Find the first live word past the partial object.
2720       addr = bitmap->find_obj_beg(addr, src_region_end);
2721       assert(addr < src_region_end, "wrong src region");
2722     }
2723     return addr;
2724   }
2725 
2726   // Skip over the partial object (if any).
2727   if (partial_obj_size != 0) {
2728     words_to_skip -= partial_obj_size;
2729     addr += partial_obj_size;
2730   }
2731 
2732   // Skip over live words due to objects that start in the region.
2733   addr = skip_live_words(addr, src_region_end, words_to_skip);
2734   assert(addr < src_region_end, "wrong src region");
2735   return addr;
2736 }
2737 
2738 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
2739                                                      SpaceId src_space_id,
2740                                                      size_t beg_region,
2741                                                      HeapWord* end_addr)
2742 {
2743   ParallelCompactData& sd = summary_data();
2744 
2745 #ifdef ASSERT
2746   MutableSpace* const src_space = _space_info[src_space_id].space();
2747   HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2748   assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2749          "src_space_id does not match beg_addr");
2750   assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2751          "src_space_id does not match end_addr");
2752 #endif // #ifdef ASSERT
2753 
2754   RegionData* const beg = sd.region(beg_region);
2755   RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2756 
2757   // Regions up to new_top() are enqueued if they become available.
2758   HeapWord* const new_top = _space_info[src_space_id].new_top();
2759   RegionData* const enqueue_end =
2760     sd.addr_to_region_ptr(sd.region_align_up(new_top));
2761 
2762   for (RegionData* cur = beg; cur < end; ++cur) {
2763     assert(cur->data_size() > 0, "region must have live data");
2764     cur->decrement_destination_count();
2765     if (cur < enqueue_end && cur->available() && cur->claim()) {
2766       if (cur->mark_normal()) {
2767         cm->push_region(sd.region(cur));
2768       } else if (cur->mark_copied()) {
2769         // Try to copy the content of the shadow region back to its corresponding
2770         // heap region if the shadow region is filled. Otherwise, the GC thread
2771         // fills the shadow region will copy the data back (see
2772         // MoveAndUpdateShadowClosure::complete_region).
2773         copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2774         ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2775         cur->set_completed();
2776       }
2777     }
2778   }
2779 }
2780 
2781 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2782                                           SpaceId& src_space_id,
2783                                           HeapWord*& src_space_top,
2784                                           HeapWord* end_addr)
2785 {
2786   typedef ParallelCompactData::RegionData RegionData;
2787 
2788   ParallelCompactData& sd = PSParallelCompact::summary_data();
2789   const size_t region_size = ParallelCompactData::RegionSize;
2790 
2791   size_t src_region_idx = 0;
2792 
2793   // Skip empty regions (if any) up to the top of the space.
2794   HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2795   RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2796   HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2797   const RegionData* const top_region_ptr =
2798     sd.addr_to_region_ptr(top_aligned_up);
2799   while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2800     ++src_region_ptr;
2801   }
2802 
2803   if (src_region_ptr < top_region_ptr) {
2804     // The next source region is in the current space.  Update src_region_idx
2805     // and the source address to match src_region_ptr.
2806     src_region_idx = sd.region(src_region_ptr);
2807     HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);
2808     if (src_region_addr > closure.source()) {
2809       closure.set_source(src_region_addr);
2810     }
2811     return src_region_idx;
2812   }
2813 
2814   // Switch to a new source space and find the first non-empty region.
2815   unsigned int space_id = src_space_id + 1;
2816   assert(space_id < last_space_id, "not enough spaces");
2817 
2818   HeapWord* const destination = closure.destination();
2819 
2820   do {
2821     MutableSpace* space = _space_info[space_id].space();
2822     HeapWord* const bottom = space->bottom();
2823     const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);
2824 
2825     // Iterate over the spaces that do not compact into themselves.
2826     if (bottom_cp->destination() != bottom) {
2827       HeapWord* const top_aligned_up = sd.region_align_up(space->top());
2828       const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
2829 
2830       for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
2831         if (src_cp->live_obj_size() > 0) {
2832           // Found it.
2833           assert(src_cp->destination() == destination,
2834                  "first live obj in the space must match the destination");
2835           assert(src_cp->partial_obj_size() == 0,
2836                  "a space cannot begin with a partial obj");
2837 
2838           src_space_id = SpaceId(space_id);
2839           src_space_top = space->top();
2840           const size_t src_region_idx = sd.region(src_cp);
2841           closure.set_source(sd.region_to_addr(src_region_idx));
2842           return src_region_idx;
2843         } else {
2844           assert(src_cp->data_size() == 0, "sanity");
2845         }
2846       }
2847     }
2848   } while (++space_id < last_space_id);
2849 
2850   assert(false, "no source region was found");
2851   return 0;
2852 }
2853 
2854 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2855 {
2856   typedef ParMarkBitMap::IterationStatus IterationStatus;
2857   ParMarkBitMap* const bitmap = mark_bitmap();
2858   ParallelCompactData& sd = summary_data();
2859   RegionData* const region_ptr = sd.region(region_idx);
2860 
2861   // Get the source region and related info.
2862   size_t src_region_idx = region_ptr->source_region();
2863   SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2864   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2865   HeapWord* dest_addr = sd.region_to_addr(region_idx);
2866 
2867   closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2868 
2869   // Adjust src_region_idx to prepare for decrementing destination counts (the
2870   // destination count is not decremented when a region is copied to itself).
2871   if (src_region_idx == region_idx) {
2872     src_region_idx += 1;
2873   }
2874 
2875   if (bitmap->is_unmarked(closure.source())) {
2876     // The first source word is in the middle of an object; copy the remainder
2877     // of the object or as much as will fit.  The fact that pointer updates were
2878     // deferred will be noted when the object header is processed.
2879     HeapWord* const old_src_addr = closure.source();
2880     closure.copy_partial_obj();
2881     if (closure.is_full()) {
2882       decrement_destination_counts(cm, src_space_id, src_region_idx,
2883                                    closure.source());
2884       closure.complete_region(cm, dest_addr, region_ptr);
2885       return;
2886     }
2887 
2888     HeapWord* const end_addr = sd.region_align_down(closure.source());
2889     if (sd.region_align_down(old_src_addr) != end_addr) {
2890       // The partial object was copied from more than one source region.
2891       decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2892 
2893       // Move to the next source region, possibly switching spaces as well.  All
2894       // args except end_addr may be modified.
2895       src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2896                                        end_addr);
2897     }
2898   }
2899 
2900   do {
2901     HeapWord* const cur_addr = closure.source();
2902     HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2903                                     src_space_top);
2904     IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);
2905 
2906     if (status == ParMarkBitMap::incomplete) {
2907       // The last obj that starts in the source region does not end in the
2908       // region.
2909       assert(closure.source() < end_addr, "sanity");
2910       HeapWord* const obj_beg = closure.source();
2911       HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),
2912                                        src_space_top);
2913       HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);
2914       if (obj_end < range_end) {
2915         // The end was found; the entire object will fit.
2916         status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));
2917         assert(status != ParMarkBitMap::would_overflow, "sanity");
2918       } else {
2919         // The end was not found; the object will not fit.
2920         assert(range_end < src_space_top, "obj cannot cross space boundary");
2921         status = ParMarkBitMap::would_overflow;
2922       }
2923     }
2924 
2925     if (status == ParMarkBitMap::would_overflow) {
2926       // The last object did not fit.  Note that interior oop updates were
2927       // deferred, then copy enough of the object to fill the region.
2928       cm->push_deferred_object(closure.destination());
2929       status = closure.copy_until_full(); // copies from closure.source()
2930 
2931       decrement_destination_counts(cm, src_space_id, src_region_idx,
2932                                    closure.source());
2933       closure.complete_region(cm, dest_addr, region_ptr);
2934       return;
2935     }
2936 
2937     if (status == ParMarkBitMap::full) {
2938       decrement_destination_counts(cm, src_space_id, src_region_idx,
2939                                    closure.source());
2940       closure.complete_region(cm, dest_addr, region_ptr);
2941       return;
2942     }
2943 
2944     decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2945 
2946     // Move to the next source region, possibly switching spaces as well.  All
2947     // args except end_addr may be modified.
2948     src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2949                                      end_addr);
2950   } while (true);
2951 }
2952 
2953 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2954 {
2955   MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2956   fill_region(cm, cl, region_idx);
2957 }
2958 
2959 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2960 {
2961   // Get a shadow region first
2962   ParallelCompactData& sd = summary_data();
2963   RegionData* const region_ptr = sd.region(region_idx);
2964   size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2965   // The InvalidShadow return value indicates the corresponding heap region is available,
2966   // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2967   // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2968   if (shadow_region == ParCompactionManager::InvalidShadow) {
2969     MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2970     region_ptr->shadow_to_normal();
2971     return fill_region(cm, cl, region_idx);
2972   } else {
2973     MoveAndUpdateShadowClosure cl(mark_bitmap(), cm, region_idx, shadow_region);
2974     return fill_region(cm, cl, region_idx);
2975   }
2976 }
2977 
2978 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2979 {
2980   Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2981 }
2982 
2983 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t &region_idx)
2984 {
2985   size_t next = cm->next_shadow_region();
2986   ParallelCompactData& sd = summary_data();
2987   size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2988   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2989 
2990   while (next < old_new_top) {
2991     if (sd.region(next)->mark_shadow()) {
2992       region_idx = next;
2993       return true;
2994     }
2995     next = cm->move_next_shadow_region_by(active_gc_threads);
2996   }
2997 
2998   return false;
2999 }
3000 
3001 // The shadow region is an optimization to address region dependencies in full GC. The basic
3002 // idea is making more regions available by temporally storing their live objects in empty
3003 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
3004 // GC threads need not wait destination regions to be available before processing sources.
3005 //
3006 // A typical workflow would be:
3007 // After draining its own stack and failing to steal from others, a GC worker would pick an
3008 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
3009 // the shadow region by copying live objects from source regions of the unavailable one. Once
3010 // the unavailable region becomes available, the data in the shadow region will be copied back.
3011 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
3012 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
3013 {
3014   const ParallelCompactData& sd = PSParallelCompact::summary_data();
3015 
3016   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
3017     SpaceInfo* const space_info = _space_info + id;
3018     MutableSpace* const space = space_info->space();
3019 
3020     const size_t beg_region =
3021       sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
3022     const size_t end_region =
3023       sd.addr_to_region_idx(sd.region_align_down(space->end()));
3024 
3025     for (size_t cur = beg_region; cur < end_region; ++cur) {
3026       ParCompactionManager::push_shadow_region(cur);
3027     }
3028   }
3029 
3030   size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
3031   for (uint i = 0; i < parallel_gc_threads; i++) {
3032     ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
3033     cm->set_next_shadow_region(beg_region + i);
3034   }
3035 }
3036 
3037 void PSParallelCompact::fill_blocks(size_t region_idx)
3038 {
3039   // Fill in the block table elements for the specified region.  Each block
3040   // table element holds the number of live words in the region that are to the
3041   // left of the first object that starts in the block.  Thus only blocks in
3042   // which an object starts need to be filled.
3043   //
3044   // The algorithm scans the section of the bitmap that corresponds to the
3045   // region, keeping a running total of the live words.  When an object start is
3046   // found, if it's the first to start in the block that contains it, the
3047   // current total is written to the block table element.
3048   const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;
3049   const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;
3050   const size_t RegionSize = ParallelCompactData::RegionSize;
3051 
3052   ParallelCompactData& sd = summary_data();
3053   const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();
3054   if (partial_obj_size >= RegionSize) {
3055     return; // No objects start in this region.
3056   }
3057 
3058   // Ensure the first loop iteration decides that the block has changed.
3059   size_t cur_block = sd.block_count();
3060 
3061   const ParMarkBitMap* const bitmap = mark_bitmap();
3062 
3063   const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;
3064   assert((size_t)1 << Log2BitsPerBlock ==
3065          bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");
3066 
3067   size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);
3068   const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);
3069   size_t live_bits = bitmap->words_to_bits(partial_obj_size);
3070   beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);
3071   while (beg_bit < range_end) {
3072     const size_t new_block = beg_bit >> Log2BitsPerBlock;
3073     if (new_block != cur_block) {
3074       cur_block = new_block;
3075       sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));
3076     }
3077 
3078     const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);
3079     if (end_bit < range_end - 1) {
3080       live_bits += end_bit - beg_bit + 1;
3081       beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);
3082     } else {
3083       return;
3084     }
3085   }
3086 }
3087 
3088 ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
3089 {
3090   if (source() != copy_destination()) {
3091     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3092     Copy::aligned_conjoint_words(source(), copy_destination(), words_remaining());
3093   }
3094   update_state(words_remaining());
3095   assert(is_full(), "sanity");
3096   return ParMarkBitMap::full;
3097 }
3098 
3099 void MoveAndUpdateClosure::copy_partial_obj()
3100 {
3101   size_t words = words_remaining();
3102 
3103   HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
3104   HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
3105   if (end_addr < range_end) {
3106     words = bitmap()->obj_size(source(), end_addr);
3107   }
3108 
3109   // This test is necessary; if omitted, the pointer updates to a partial object
3110   // that crosses the dense prefix boundary could be overwritten.
3111   if (source() != copy_destination()) {
3112     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3113     Copy::aligned_conjoint_words(source(), copy_destination(), words);
3114   }
3115   update_state(words);
3116 }
3117 
3118 void MoveAndUpdateClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
3119                                            PSParallelCompact::RegionData *region_ptr) {
3120   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
3121   region_ptr->set_completed();
3122 }
3123 
3124 ParMarkBitMapClosure::IterationStatus
3125 MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
3126   assert(destination() != nullptr, "sanity");
3127   assert(bitmap()->obj_size(addr) == words, "bad size");
3128 
3129   _source = addr;
3130   assert(PSParallelCompact::summary_data().calc_new_pointer(source(), compaction_manager()) ==
3131          destination(), "wrong destination");
3132 
3133   if (words > words_remaining()) {
3134     return ParMarkBitMap::would_overflow;
3135   }
3136 
3137   // The start_array must be updated even if the object is not moving.
3138   if (_start_array != nullptr) {
3139     _start_array->update_for_block(destination(), destination() + words);
3140   }
3141 
3142   if (copy_destination() != source()) {
3143     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3144     Copy::aligned_conjoint_words(source(), copy_destination(), words);
3145   }
3146 
3147   oop moved_oop = cast_to_oop(copy_destination());
3148   compaction_manager()->update_contents(moved_oop);
3149   assert(oopDesc::is_oop_or_null(moved_oop), "Expected an oop or null at " PTR_FORMAT, p2i(moved_oop));
3150 
3151   update_state(words);
3152   assert(copy_destination() == cast_from_oop<HeapWord*>(moved_oop) + moved_oop->size(), "sanity");
3153   return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
3154 }
3155 
3156 void MoveAndUpdateShadowClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
3157                                                  PSParallelCompact::RegionData *region_ptr) {
3158   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
3159   // Record the shadow region index
3160   region_ptr->set_shadow_region(_shadow);
3161   // Mark the shadow region as filled to indicate the data is ready to be
3162   // copied back
3163   region_ptr->mark_filled();
3164   // Try to copy the content of the shadow region back to its corresponding
3165   // heap region if available; the GC thread that decreases the destination
3166   // count to zero will do the copying otherwise (see
3167   // PSParallelCompact::decrement_destination_counts).
3168   if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
3169     region_ptr->set_completed();
3170     PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
3171     ParCompactionManager::push_shadow_region_mt_safe(_shadow);
3172   }
3173 }
3174 
3175 UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
3176                                      ParCompactionManager* cm,
3177                                      PSParallelCompact::SpaceId space_id) :
3178   ParMarkBitMapClosure(mbm, cm),
3179   _start_array(PSParallelCompact::start_array(space_id))
3180 {
3181 }
3182 
3183 // Updates the references in the object to their new values.
3184 ParMarkBitMapClosure::IterationStatus
3185 UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
3186   do_addr(addr);
3187   return ParMarkBitMap::incomplete;
3188 }
3189 
3190 FillClosure::FillClosure(ParCompactionManager* cm, PSParallelCompact::SpaceId space_id) :
3191   ParMarkBitMapClosure(PSParallelCompact::mark_bitmap(), cm),
3192   _start_array(PSParallelCompact::start_array(space_id))
3193 {
3194   assert(space_id == PSParallelCompact::old_space_id,
3195          "cannot use FillClosure in the young gen");
3196 }
3197 
3198 ParMarkBitMapClosure::IterationStatus
3199 FillClosure::do_addr(HeapWord* addr, size_t size) {
3200   CollectedHeap::fill_with_objects(addr, size);
3201   HeapWord* const end = addr + size;
3202   do {
3203     size_t size = cast_to_oop(addr)->size();
3204     _start_array->update_for_block(addr, addr + size);
3205     addr += size;
3206   } while (addr < end);
3207   return ParMarkBitMap::incomplete;
3208 }