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