1 /*
   2  * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "classfile/classLoaderDataGraph.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/parallel/objectStartArray.inline.hpp"
  34 #include "gc/parallel/parallelArguments.hpp"
  35 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  36 #include "gc/parallel/parMarkBitMap.inline.hpp"
  37 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  38 #include "gc/parallel/psCompactionManager.inline.hpp"
  39 #include "gc/parallel/psOldGen.hpp"
  40 #include "gc/parallel/psParallelCompact.inline.hpp"
  41 #include "gc/parallel/psPromotionManager.inline.hpp"
  42 #include "gc/parallel/psRootType.hpp"
  43 #include "gc/parallel/psScavenge.hpp"
  44 #include "gc/parallel/psStringDedup.hpp"
  45 #include "gc/parallel/psYoungGen.hpp"
  46 #include "gc/shared/classUnloadingContext.hpp"
  47 #include "gc/shared/fullGCForwarding.inline.hpp"
  48 #include "gc/shared/gcCause.hpp"
  49 #include "gc/shared/gcHeapSummary.hpp"
  50 #include "gc/shared/gcId.hpp"
  51 #include "gc/shared/gcLocker.hpp"
  52 #include "gc/shared/gcTimer.hpp"
  53 #include "gc/shared/gcTrace.hpp"
  54 #include "gc/shared/gcTraceTime.inline.hpp"
  55 #include "gc/shared/gcVMOperations.hpp"
  56 #include "gc/shared/isGCActiveMark.hpp"
  57 #include "gc/shared/oopStorage.inline.hpp"
  58 #include "gc/shared/oopStorageSet.inline.hpp"
  59 #include "gc/shared/oopStorageSetParState.inline.hpp"
  60 #include "gc/shared/preservedMarks.inline.hpp"
  61 #include "gc/shared/referencePolicy.hpp"
  62 #include "gc/shared/referenceProcessor.hpp"
  63 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  64 #include "gc/shared/spaceDecorator.hpp"
  65 #include "gc/shared/taskTerminator.hpp"
  66 #include "gc/shared/weakProcessor.inline.hpp"
  67 #include "gc/shared/workerPolicy.hpp"
  68 #include "gc/shared/workerThread.hpp"
  69 #include "gc/shared/workerUtils.hpp"
  70 #include "logging/log.hpp"
  71 #include "memory/iterator.inline.hpp"
  72 #include "memory/memoryReserver.hpp"
  73 #include "memory/metaspaceUtils.hpp"
  74 #include "memory/resourceArea.hpp"
  75 #include "memory/universe.hpp"
  76 #include "nmt/memTracker.hpp"
  77 #include "oops/access.inline.hpp"
  78 #include "oops/instanceClassLoaderKlass.inline.hpp"
  79 #include "oops/instanceKlass.inline.hpp"
  80 #include "oops/instanceMirrorKlass.inline.hpp"
  81 #include "oops/methodData.hpp"
  82 #include "oops/objArrayKlass.inline.hpp"
  83 #include "oops/oop.inline.hpp"
  84 #include "runtime/atomicAccess.hpp"
  85 #include "runtime/handles.inline.hpp"
  86 #include "runtime/java.hpp"
  87 #include "runtime/safepoint.hpp"
  88 #include "runtime/threads.hpp"
  89 #include "runtime/vmThread.hpp"
  90 #include "services/memoryService.hpp"
  91 #include "utilities/align.hpp"
  92 #include "utilities/debug.hpp"
  93 #include "utilities/events.hpp"
  94 #include "utilities/formatBuffer.hpp"
  95 #include "utilities/macros.hpp"
  96 #include "utilities/stack.inline.hpp"
  97 #if INCLUDE_JVMCI
  98 #include "jvmci/jvmci.hpp"
  99 #endif
 100 
 101 #include <math.h>
 102 
 103 // All sizes are in HeapWords.
 104 const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
 105 const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
 106 static_assert(ParallelCompactData::RegionSize >= BitsPerWord, "region-start bit word-aligned");
 107 const size_t ParallelCompactData::RegionSizeBytes =
 108   RegionSize << LogHeapWordSize;
 109 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
 110 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
 111 const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;
 112 
 113 const ParallelCompactData::RegionData::region_sz_t
 114 ParallelCompactData::RegionData::dc_shift = 27;
 115 
 116 const ParallelCompactData::RegionData::region_sz_t
 117 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
 118 
 119 const ParallelCompactData::RegionData::region_sz_t
 120 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
 121 
 122 const ParallelCompactData::RegionData::region_sz_t
 123 ParallelCompactData::RegionData::los_mask = ~dc_mask;
 124 
 125 const ParallelCompactData::RegionData::region_sz_t
 126 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
 127 
 128 const ParallelCompactData::RegionData::region_sz_t
 129 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
 130 
 131 bool ParallelCompactData::RegionData::is_clear() {
 132   return (_destination == nullptr) &&
 133          (_source_region == 0) &&
 134          (_partial_obj_addr == nullptr) &&
 135          (_partial_obj_size == 0) &&
 136          (_dc_and_los == 0) &&
 137          (_shadow_state == 0);
 138 }
 139 
 140 #ifdef ASSERT
 141 void ParallelCompactData::RegionData::verify_clear() {
 142   assert(_destination == nullptr, "inv");
 143   assert(_source_region == 0, "inv");
 144   assert(_partial_obj_addr == nullptr, "inv");
 145   assert(_partial_obj_size == 0, "inv");
 146   assert(_dc_and_los == 0, "inv");
 147   assert(_shadow_state == 0, "inv");
 148 }
 149 #endif
 150 
 151 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
 152 
 153 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
 154 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
 155 
 156 void SplitInfo::record(size_t split_region_idx, HeapWord* split_point, size_t preceding_live_words) {
 157   assert(split_region_idx != 0, "precondition");
 158 
 159   // Obj denoted by split_point will be deferred to the next space.
 160   assert(split_point != nullptr, "precondition");
 161 
 162   const ParallelCompactData& sd = PSParallelCompact::summary_data();
 163 
 164   PSParallelCompact::RegionData* split_region_ptr = sd.region(split_region_idx);
 165   assert(preceding_live_words < split_region_ptr->data_size(), "inv");
 166 
 167   HeapWord* preceding_destination = split_region_ptr->destination();
 168   assert(preceding_destination != nullptr, "inv");
 169 
 170   // How many regions does the preceding part occupy
 171   uint preceding_destination_count;
 172   if (preceding_live_words == 0) {
 173     preceding_destination_count = 0;
 174   } else {
 175     // -1 so that the ending address doesn't fall on the region-boundary
 176     if (sd.region_align_down(preceding_destination) ==
 177         sd.region_align_down(preceding_destination + preceding_live_words - 1)) {
 178       preceding_destination_count = 1;
 179     } else {
 180       preceding_destination_count = 2;
 181     }
 182   }
 183 
 184   _split_region_idx = split_region_idx;
 185   _split_point = split_point;
 186   _preceding_live_words = preceding_live_words;
 187   _preceding_destination = preceding_destination;
 188   _preceding_destination_count = preceding_destination_count;
 189 }
 190 
 191 void SplitInfo::clear()
 192 {
 193   _split_region_idx = 0;
 194   _split_point = nullptr;
 195   _preceding_live_words = 0;
 196   _preceding_destination = nullptr;
 197   _preceding_destination_count = 0;
 198   assert(!is_valid(), "sanity");
 199 }
 200 
 201 #ifdef  ASSERT
 202 void SplitInfo::verify_clear()
 203 {
 204   assert(_split_region_idx == 0, "not clear");
 205   assert(_split_point == nullptr, "not clear");
 206   assert(_preceding_live_words == 0, "not clear");
 207   assert(_preceding_destination == nullptr, "not clear");
 208   assert(_preceding_destination_count == 0, "not clear");
 209 }
 210 #endif  // #ifdef ASSERT
 211 
 212 
 213 void PSParallelCompact::print_on(outputStream* st) {
 214   _mark_bitmap.print_on(st);
 215 }
 216 
 217 ParallelCompactData::ParallelCompactData() :
 218   _heap_start(nullptr),
 219   DEBUG_ONLY(_heap_end(nullptr) COMMA)
 220   _region_vspace(nullptr),
 221   _reserved_byte_size(0),
 222   _region_data(nullptr),
 223   _region_count(0) {}
 224 
 225 bool ParallelCompactData::initialize(MemRegion reserved_heap)
 226 {
 227   _heap_start = reserved_heap.start();
 228   const size_t heap_size = reserved_heap.word_size();
 229   DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
 230 
 231   assert(region_align_down(_heap_start) == _heap_start,
 232          "region start not aligned");
 233 
 234   return initialize_region_data(heap_size);
 235 }
 236 
 237 PSVirtualSpace*
 238 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 239 {
 240   const size_t raw_bytes = count * element_size;
 241   const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
 242   const size_t granularity = os::vm_allocation_granularity();
 243   const size_t rs_align = MAX2(page_sz, granularity);
 244 
 245   _reserved_byte_size = align_up(raw_bytes, rs_align);
 246 
 247   ReservedSpace rs = MemoryReserver::reserve(_reserved_byte_size,
 248                                              rs_align,
 249                                              page_sz,
 250                                              mtGC);
 251 
 252   if (!rs.is_reserved()) {
 253     // Failed to reserve memory.
 254     return nullptr;
 255   }
 256 
 257   os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
 258                        rs.size(), page_sz);
 259 
 260   MemTracker::record_virtual_memory_tag(rs, mtGC);
 261 
 262   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
 263 
 264   if (!vspace->expand_by(_reserved_byte_size)) {
 265     // Failed to commit memory.
 266 
 267     delete vspace;
 268 
 269     // Release memory reserved in the space.
 270     MemoryReserver::release(rs);
 271 
 272     return nullptr;
 273   }
 274 
 275   return vspace;
 276 }
 277 
 278 bool ParallelCompactData::initialize_region_data(size_t heap_size)
 279 {
 280   assert(is_aligned(heap_size, RegionSize), "precondition");
 281 
 282   const size_t count = heap_size >> Log2RegionSize;
 283   _region_vspace = create_vspace(count, sizeof(RegionData));
 284   if (_region_vspace != nullptr) {
 285     _region_data = (RegionData*)_region_vspace->reserved_low_addr();
 286     _region_count = count;
 287     return true;
 288   }
 289   return false;
 290 }
 291 
 292 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
 293   assert(beg_region <= _region_count, "beg_region out of range");
 294   assert(end_region <= _region_count, "end_region out of range");
 295 
 296   const size_t region_cnt = end_region - beg_region;
 297   memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
 298 }
 299 
 300 // The total live words on src_region would overflow the target space, so find
 301 // the overflowing object and record the split point. The invariant is that an
 302 // obj should not cross space boundary.
 303 HeapWord* ParallelCompactData::summarize_split_space(size_t src_region,
 304                                                      SplitInfo& split_info,
 305                                                      HeapWord* const destination,
 306                                                      HeapWord* const target_end,
 307                                                      HeapWord** target_next) {
 308   assert(destination <= target_end, "sanity");
 309   assert(destination + _region_data[src_region].data_size() > target_end,
 310     "region should not fit into target space");
 311   assert(is_region_aligned(target_end), "sanity");
 312 
 313   size_t partial_obj_size = _region_data[src_region].partial_obj_size();
 314 
 315   if (destination + partial_obj_size > target_end) {
 316     assert(partial_obj_size > 0, "inv");
 317     // The overflowing obj is from a previous region.
 318     //
 319     // source-regions:
 320     //
 321     // ***************
 322     // |     A|AA    |
 323     // ***************
 324     //       ^
 325     //       | split-point
 326     //
 327     // dest-region:
 328     //
 329     // ********
 330     // |~~~~A |
 331     // ********
 332     //       ^^
 333     //       || target-space-end
 334     //       |
 335     //       | destination
 336     //
 337     // AAA would overflow target-space.
 338     //
 339     HeapWord* overflowing_obj = _region_data[src_region].partial_obj_addr();
 340     size_t split_region = addr_to_region_idx(overflowing_obj);
 341 
 342     // The number of live words before the overflowing object on this split region
 343     size_t preceding_live_words;
 344     if (is_region_aligned(overflowing_obj)) {
 345       preceding_live_words = 0;
 346     } else {
 347       // Words accounted by the overflowing object on the split region
 348       size_t overflowing_size = pointer_delta(region_align_up(overflowing_obj), overflowing_obj);
 349       preceding_live_words = region(split_region)->data_size() - overflowing_size;
 350     }
 351 
 352     split_info.record(split_region, overflowing_obj, preceding_live_words);
 353 
 354     // The [overflowing_obj, src_region_start) part has been accounted for, so
 355     // must move back the new_top, now that this overflowing obj is deferred.
 356     HeapWord* new_top = destination - pointer_delta(region_to_addr(src_region), overflowing_obj);
 357 
 358     // If the overflowing obj was relocated to its original destination,
 359     // those destination regions would have their source_region set. Now that
 360     // this overflowing obj is relocated somewhere else, reset the
 361     // source_region.
 362     {
 363       size_t range_start = addr_to_region_idx(region_align_up(new_top));
 364       size_t range_end = addr_to_region_idx(region_align_up(destination));
 365       for (size_t i = range_start; i < range_end; ++i) {
 366         region(i)->set_source_region(0);
 367       }
 368     }
 369 
 370     // Update new top of target space
 371     *target_next = new_top;
 372 
 373     return overflowing_obj;
 374   }
 375 
 376   // Obj-iteration to locate the overflowing obj
 377   HeapWord* region_start = region_to_addr(src_region);
 378   HeapWord* region_end = region_start + RegionSize;
 379   HeapWord* cur_addr = region_start + partial_obj_size;
 380   size_t live_words = partial_obj_size;
 381 
 382   while (true) {
 383     assert(cur_addr < region_end, "inv");
 384     cur_addr = PSParallelCompact::mark_bitmap()->find_obj_beg(cur_addr, region_end);
 385     // There must be an overflowing obj in this region
 386     assert(cur_addr < region_end, "inv");
 387 
 388     oop obj = cast_to_oop(cur_addr);
 389     size_t obj_size = obj->size();
 390     if (destination + live_words + obj_size > target_end) {
 391       // Found the overflowing obj
 392       split_info.record(src_region, cur_addr, live_words);
 393       *target_next = destination + live_words;
 394       return cur_addr;
 395     }
 396 
 397     live_words += obj_size;
 398     cur_addr += obj_size;
 399   }
 400 }
 401 
 402 size_t ParallelCompactData::live_words_in_space(const MutableSpace* space,
 403                                                 HeapWord** full_region_prefix_end) {
 404   size_t cur_region = addr_to_region_idx(space->bottom());
 405   const size_t end_region = addr_to_region_idx(region_align_up(space->top()));
 406   size_t live_words = 0;
 407   if (full_region_prefix_end == nullptr) {
 408     for (/* empty */; cur_region < end_region; ++cur_region) {
 409       live_words += _region_data[cur_region].data_size();
 410     }
 411   } else {
 412     bool first_set = false;
 413     for (/* empty */; cur_region < end_region; ++cur_region) {
 414       size_t live_words_in_region = _region_data[cur_region].data_size();
 415       if (!first_set && live_words_in_region < RegionSize) {
 416         *full_region_prefix_end = region_to_addr(cur_region);
 417         first_set = true;
 418       }
 419       live_words += live_words_in_region;
 420     }
 421     if (!first_set) {
 422       // All regions are full of live objs.
 423       assert(is_region_aligned(space->top()), "inv");
 424       *full_region_prefix_end = space->top();
 425     }
 426     assert(*full_region_prefix_end != nullptr, "postcondition");
 427     assert(is_region_aligned(*full_region_prefix_end), "inv");
 428     assert(*full_region_prefix_end >= space->bottom(), "in-range");
 429     assert(*full_region_prefix_end <= space->top(), "in-range");
 430   }
 431   return live_words;
 432 }
 433 
 434 bool ParallelCompactData::summarize(SplitInfo& split_info,
 435                                     HeapWord* source_beg, HeapWord* source_end,
 436                                     HeapWord** source_next,
 437                                     HeapWord* target_beg, HeapWord* target_end,
 438                                     HeapWord** target_next)
 439 {
 440   HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
 441   log_develop_trace(gc, compaction)(
 442       "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
 443       "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
 444       p2i(source_beg), p2i(source_end), p2i(source_next_val),
 445       p2i(target_beg), p2i(target_end), p2i(*target_next));
 446 
 447   size_t cur_region = addr_to_region_idx(source_beg);
 448   const size_t end_region = addr_to_region_idx(region_align_up(source_end));
 449 
 450   HeapWord *dest_addr = target_beg;
 451   for (/* empty */; cur_region < end_region; cur_region++) {
 452     size_t words = _region_data[cur_region].data_size();
 453 
 454     // Skip empty ones
 455     if (words == 0) {
 456       continue;
 457     }
 458 
 459     if (split_info.is_split(cur_region)) {
 460       assert(words > split_info.preceding_live_words(), "inv");
 461       words -= split_info.preceding_live_words();
 462     }
 463 
 464     _region_data[cur_region].set_destination(dest_addr);
 465 
 466     // If cur_region does not fit entirely into the target space, find a point
 467     // at which the source space can be 'split' so that part is copied to the
 468     // target space and the rest is copied elsewhere.
 469     if (dest_addr + words > target_end) {
 470       assert(source_next != nullptr, "source_next is null when splitting");
 471       *source_next = summarize_split_space(cur_region, split_info, dest_addr,
 472                                            target_end, target_next);
 473       return false;
 474     }
 475 
 476     uint destination_count = split_info.is_split(cur_region)
 477                              ? split_info.preceding_destination_count()
 478                              : 0;
 479 
 480     HeapWord* const last_addr = dest_addr + words - 1;
 481     const size_t dest_region_1 = addr_to_region_idx(dest_addr);
 482     const size_t dest_region_2 = addr_to_region_idx(last_addr);
 483 
 484     // Initially assume that the destination regions will be the same and
 485     // adjust the value below if necessary.  Under this assumption, if
 486     // cur_region == dest_region_2, then cur_region will be compacted
 487     // completely into itself.
 488     destination_count += cur_region == dest_region_2 ? 0 : 1;
 489     if (dest_region_1 != dest_region_2) {
 490       // Destination regions differ; adjust destination_count.
 491       destination_count += 1;
 492       // Data from cur_region will be copied to the start of dest_region_2.
 493       _region_data[dest_region_2].set_source_region(cur_region);
 494     } else if (is_region_aligned(dest_addr)) {
 495       // Data from cur_region will be copied to the start of the destination
 496       // region.
 497       _region_data[dest_region_1].set_source_region(cur_region);
 498     }
 499 
 500     _region_data[cur_region].set_destination_count(destination_count);
 501     dest_addr += words;
 502   }
 503 
 504   *target_next = dest_addr;
 505   return true;
 506 }
 507 
 508 #ifdef ASSERT
 509 void ParallelCompactData::verify_clear() {
 510   for (uint cur_idx = 0; cur_idx < region_count(); ++cur_idx) {
 511     if (!region(cur_idx)->is_clear()) {
 512       log_warning(gc)("Uncleared Region: %u", cur_idx);
 513       region(cur_idx)->verify_clear();
 514     }
 515   }
 516 }
 517 #endif  // #ifdef ASSERT
 518 
 519 STWGCTimer          PSParallelCompact::_gc_timer;
 520 ParallelOldTracer   PSParallelCompact::_gc_tracer;
 521 elapsedTimer        PSParallelCompact::_accumulated_time;
 522 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
 523 CollectorCounters*  PSParallelCompact::_counters = nullptr;
 524 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
 525 ParallelCompactData PSParallelCompact::_summary_data;
 526 
 527 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
 528 
 529 class PCAdjustPointerClosure: public BasicOopIterateClosure {
 530   template <typename T>
 531   void do_oop_work(T* p) { PSParallelCompact::adjust_pointer(p); }
 532 
 533 public:
 534   virtual void do_oop(oop* p)                { do_oop_work(p); }
 535   virtual void do_oop(narrowOop* p)          { do_oop_work(p); }
 536 
 537   virtual ReferenceIterationMode reference_iteration_mode() { return DO_FIELDS; }
 538 };
 539 
 540 static PCAdjustPointerClosure pc_adjust_pointer_closure;
 541 
 542 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
 543 
 544 void PSParallelCompact::post_initialize() {
 545   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 546   _span_based_discoverer.set_span(heap->reserved_region());
 547   _ref_processor =
 548     new ReferenceProcessor(&_span_based_discoverer,
 549                            ParallelGCThreads,   // mt processing degree
 550                            ParallelGCThreads,   // mt discovery degree
 551                            false,               // concurrent_discovery
 552                            &_is_alive_closure); // non-header is alive closure
 553 
 554   _counters = new CollectorCounters("Parallel full collection pauses", 1);
 555 
 556   // Initialize static fields in ParCompactionManager.
 557   ParCompactionManager::initialize(mark_bitmap());
 558 }
 559 
 560 bool PSParallelCompact::initialize_aux_data() {
 561   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 562   MemRegion mr = heap->reserved_region();
 563   assert(mr.byte_size() != 0, "heap should be reserved");
 564 
 565   initialize_space_info();
 566 
 567   if (!_mark_bitmap.initialize(mr)) {
 568     vm_shutdown_during_initialization(
 569       err_msg("Unable to allocate %zuKB bitmaps for parallel "
 570       "garbage collection for the requested %zuKB heap.",
 571       _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
 572     return false;
 573   }
 574 
 575   if (!_summary_data.initialize(mr)) {
 576     vm_shutdown_during_initialization(
 577       err_msg("Unable to allocate %zuKB card tables for parallel "
 578       "garbage collection for the requested %zuKB heap.",
 579       _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
 580     return false;
 581   }
 582 
 583   return true;
 584 }
 585 
 586 void PSParallelCompact::initialize_space_info()
 587 {
 588   memset(&_space_info, 0, sizeof(_space_info));
 589 
 590   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 591   PSYoungGen* young_gen = heap->young_gen();
 592 
 593   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
 594   _space_info[eden_space_id].set_space(young_gen->eden_space());
 595   _space_info[from_space_id].set_space(young_gen->from_space());
 596   _space_info[to_space_id].set_space(young_gen->to_space());
 597 
 598   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
 599 }
 600 
 601 void
 602 PSParallelCompact::clear_data_covering_space(SpaceId id)
 603 {
 604   // At this point, top is the value before GC, new_top() is the value that will
 605   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
 606   // should be marked above top.  The summary data is cleared to the larger of
 607   // top & new_top.
 608   MutableSpace* const space = _space_info[id].space();
 609   HeapWord* const bot = space->bottom();
 610   HeapWord* const top = space->top();
 611   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
 612 
 613   _mark_bitmap.clear_range(bot, top);
 614 
 615   const size_t beg_region = _summary_data.addr_to_region_idx(bot);
 616   const size_t end_region =
 617     _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
 618   _summary_data.clear_range(beg_region, end_region);
 619 
 620   // Clear the data used to 'split' regions.
 621   SplitInfo& split_info = _space_info[id].split_info();
 622   if (split_info.is_valid()) {
 623     split_info.clear();
 624   }
 625   DEBUG_ONLY(split_info.verify_clear();)
 626 }
 627 
 628 void PSParallelCompact::pre_compact()
 629 {
 630   // Update the from & to space pointers in space_info, since they are swapped
 631   // at each young gen gc.  Do the update unconditionally (even though a
 632   // promotion failure does not swap spaces) because an unknown number of young
 633   // collections will have swapped the spaces an unknown number of times.
 634   GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
 635   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 636   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
 637   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
 638 
 639   heap->increment_total_collections(true);
 640 
 641   CodeCache::on_gc_marking_cycle_start();
 642 
 643   heap->print_before_gc();
 644   heap->trace_heap_before_gc(&_gc_tracer);
 645 
 646   // Fill in TLABs
 647   heap->ensure_parsability(true);  // retire TLABs
 648 
 649   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 650     Universe::verify("Before GC");
 651   }
 652 
 653   DEBUG_ONLY(mark_bitmap()->verify_clear();)
 654   DEBUG_ONLY(summary_data().verify_clear();)
 655 }
 656 
 657 void PSParallelCompact::post_compact()
 658 {
 659   GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
 660   ParCompactionManager::remove_all_shadow_regions();
 661 
 662   CodeCache::on_gc_marking_cycle_finish();
 663   CodeCache::arm_all_nmethods();
 664 
 665   // Need to clear claim bits for the next full-gc (marking and adjust-pointers).
 666   ClassLoaderDataGraph::clear_claimed_marks();
 667 
 668   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
 669     // Clear the marking bitmap, summary data and split info.
 670     clear_data_covering_space(SpaceId(id));
 671     {
 672       MutableSpace* space = _space_info[id].space();
 673       HeapWord* top = space->top();
 674       HeapWord* new_top = _space_info[id].new_top();
 675       if (ZapUnusedHeapArea && new_top < top) {
 676         space->mangle_region(MemRegion(new_top, top));
 677       }
 678       // Update top().  Must be done after clearing the bitmap and summary data.
 679       space->set_top(new_top);
 680     }
 681   }
 682 
 683 #ifdef ASSERT
 684   {
 685     mark_bitmap()->verify_clear();
 686     summary_data().verify_clear();
 687   }
 688 #endif
 689 
 690   ParCompactionManager::flush_all_string_dedup_requests();
 691 
 692   MutableSpace* const eden_space = _space_info[eden_space_id].space();
 693   MutableSpace* const from_space = _space_info[from_space_id].space();
 694   MutableSpace* const to_space   = _space_info[to_space_id].space();
 695 
 696   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 697   bool eden_empty = eden_space->is_empty();
 698 
 699   // Update heap occupancy information which is used as input to the soft ref
 700   // clearing policy at the next gc.
 701   Universe::heap()->update_capacity_and_used_at_gc();
 702 
 703   bool young_gen_empty = eden_empty && from_space->is_empty() &&
 704     to_space->is_empty();
 705 
 706   PSCardTable* ct = heap->card_table();
 707   MemRegion old_mr = heap->old_gen()->committed();
 708   if (young_gen_empty) {
 709     ct->clear_MemRegion(old_mr);
 710   } else {
 711     ct->dirty_MemRegion(old_mr);
 712   }
 713 
 714   heap->prune_scavengable_nmethods();
 715 
 716 #if COMPILER2_OR_JVMCI
 717   DerivedPointerTable::update_pointers();
 718 #endif
 719 
 720   // Signal that we have completed a visit to all live objects.
 721   Universe::heap()->record_whole_heap_examined_timestamp();
 722 }
 723 
 724 HeapWord* PSParallelCompact::compute_dense_prefix_for_old_space(MutableSpace* old_space,
 725                                                                 HeapWord* full_region_prefix_end) {
 726   const size_t region_size = ParallelCompactData::RegionSize;
 727   const ParallelCompactData& sd = summary_data();
 728 
 729   // Iteration starts with the region *after* the full-region-prefix-end.
 730   const RegionData* const start_region = sd.addr_to_region_ptr(full_region_prefix_end);
 731   // If final region is not full, iteration stops before that region,
 732   // because fill_dense_prefix_end assumes that prefix_end <= top.
 733   const RegionData* const end_region = sd.addr_to_region_ptr(old_space->top());
 734   assert(start_region <= end_region, "inv");
 735 
 736   size_t max_waste = old_space->capacity_in_words() * (MarkSweepDeadRatio / 100.0);
 737   const RegionData* cur_region = start_region;
 738   for (/* empty */; cur_region < end_region; ++cur_region) {
 739     assert(region_size >= cur_region->data_size(), "inv");
 740     size_t dead_size = region_size - cur_region->data_size();
 741     if (max_waste < dead_size) {
 742       break;
 743     }
 744     max_waste -= dead_size;
 745   }
 746 
 747   HeapWord* const prefix_end = sd.region_to_addr(cur_region);
 748   assert(sd.is_region_aligned(prefix_end), "postcondition");
 749   assert(prefix_end >= full_region_prefix_end, "in-range");
 750   assert(prefix_end <= old_space->top(), "in-range");
 751   return prefix_end;
 752 }
 753 
 754 void PSParallelCompact::fill_dense_prefix_end(SpaceId id) {
 755   // Comparing two sizes to decide if filling is required:
 756   //
 757   // The size of the filler (min-obj-size) is 2 heap words with the default
 758   // MinObjAlignment, since both markword and klass take 1 heap word.
 759   // With +UseCompactObjectHeaders, the minimum filler size is only one word,
 760   // because the Klass* gets encoded in the mark-word.
 761   //
 762   // The size of the gap (if any) right before dense-prefix-end is
 763   // MinObjAlignment.
 764   //
 765   // Need to fill in the gap only if it's smaller than min-obj-size, and the
 766   // filler obj will extend to next region.
 767 
 768   if (MinObjAlignment >= checked_cast<int>(CollectedHeap::min_fill_size())) {
 769     return;
 770   }
 771 
 772   assert(!UseCompactObjectHeaders, "Compact headers can allocate small objects");
 773   assert(CollectedHeap::min_fill_size() == 2, "inv");
 774   HeapWord* const dense_prefix_end = dense_prefix(id);
 775   assert(_summary_data.is_region_aligned(dense_prefix_end), "precondition");
 776   assert(dense_prefix_end <= space(id)->top(), "precondition");
 777   if (dense_prefix_end == space(id)->top()) {
 778     // Must not have single-word gap right before prefix-end/top.
 779     return;
 780   }
 781   RegionData* const region_after_dense_prefix = _summary_data.addr_to_region_ptr(dense_prefix_end);
 782 
 783   if (region_after_dense_prefix->partial_obj_size() != 0 ||
 784       _mark_bitmap.is_marked(dense_prefix_end)) {
 785     // The region after the dense prefix starts with live bytes.
 786     return;
 787   }
 788 
 789   HeapWord* block_start = start_array(id)->block_start_reaching_into_card(dense_prefix_end);
 790   if (block_start == dense_prefix_end - 1) {
 791     assert(!_mark_bitmap.is_marked(block_start), "inv");
 792     // There is exactly one heap word gap right before the dense prefix end, so we need a filler object.
 793     // The filler object will extend into region_after_dense_prefix.
 794     const size_t obj_len = 2; // min-fill-size
 795     HeapWord* const obj_beg = dense_prefix_end - 1;
 796     CollectedHeap::fill_with_object(obj_beg, obj_len);
 797     _mark_bitmap.mark_obj(obj_beg);
 798     _summary_data.addr_to_region_ptr(obj_beg)->add_live_obj(1);
 799     region_after_dense_prefix->set_partial_obj_size(1);
 800     region_after_dense_prefix->set_partial_obj_addr(obj_beg);
 801     assert(start_array(id) != nullptr, "sanity");
 802     start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
 803   }
 804 }
 805 
 806 bool PSParallelCompact::check_maximum_compaction(bool should_do_max_compaction,
 807                                                  size_t total_live_words,
 808                                                  MutableSpace* const old_space,
 809                                                  HeapWord* full_region_prefix_end) {
 810 
 811   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 812 
 813   // Check System.GC
 814   bool is_max_on_system_gc = UseMaximumCompactionOnSystemGC
 815                           && GCCause::is_user_requested_gc(heap->gc_cause());
 816 
 817   // Check if all live objs are too much for old-gen.
 818   const bool is_old_gen_too_full = (total_live_words >= old_space->capacity_in_words());
 819 
 820   // If all regions in old-gen are full
 821   const bool is_region_full =
 822     full_region_prefix_end >= _summary_data.region_align_down(old_space->top());
 823 
 824   return should_do_max_compaction
 825       || is_max_on_system_gc
 826       || is_old_gen_too_full
 827       || is_region_full;
 828 }
 829 
 830 void PSParallelCompact::summary_phase(bool should_do_max_compaction)
 831 {
 832   GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
 833 
 834   MutableSpace* const old_space = _space_info[old_space_id].space();
 835   {
 836     size_t total_live_words = 0;
 837     HeapWord* full_region_prefix_end = nullptr;
 838     {
 839       // old-gen
 840       size_t live_words = _summary_data.live_words_in_space(old_space,
 841                                                             &full_region_prefix_end);
 842       total_live_words += live_words;
 843     }
 844     // young-gen
 845     for (uint i = eden_space_id; i < last_space_id; ++i) {
 846       const MutableSpace* space = _space_info[i].space();
 847       size_t live_words = _summary_data.live_words_in_space(space);
 848       total_live_words += live_words;
 849       _space_info[i].set_new_top(space->bottom() + live_words);
 850       _space_info[i].set_dense_prefix(space->bottom());
 851     }
 852 
 853     should_do_max_compaction = check_maximum_compaction(should_do_max_compaction,
 854                                                         total_live_words,
 855                                                         old_space,
 856                                                         full_region_prefix_end);
 857     {
 858       GCTraceTime(Info, gc, phases) tm("Summary Phase: expand", &_gc_timer);
 859       // Try to expand old-gen in order to fit all live objs and waste.
 860       size_t target_capacity_bytes = total_live_words * HeapWordSize
 861                                    + old_space->capacity_in_bytes() * (MarkSweepDeadRatio / 100);
 862       ParallelScavengeHeap::heap()->old_gen()->try_expand_till_size(target_capacity_bytes);
 863     }
 864 
 865     HeapWord* dense_prefix_end = should_do_max_compaction
 866                                  ? full_region_prefix_end
 867                                  : compute_dense_prefix_for_old_space(old_space,
 868                                                                       full_region_prefix_end);
 869     SpaceId id = old_space_id;
 870     _space_info[id].set_dense_prefix(dense_prefix_end);
 871 
 872     if (dense_prefix_end != old_space->bottom()) {
 873       fill_dense_prefix_end(id);
 874     }
 875 
 876     // Compacting objs in [dense_prefix_end, old_space->top())
 877     _summary_data.summarize(_space_info[id].split_info(),
 878                             dense_prefix_end, old_space->top(), nullptr,
 879                             dense_prefix_end, old_space->end(),
 880                             _space_info[id].new_top_addr());
 881   }
 882 
 883   // Summarize the remaining spaces in the young gen.  The initial target space
 884   // is the old gen.  If a space does not fit entirely into the target, then the
 885   // remainder is compacted into the space itself and that space becomes the new
 886   // target.
 887   SpaceId dst_space_id = old_space_id;
 888   HeapWord* dst_space_end = old_space->end();
 889   HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
 890   for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
 891     const MutableSpace* space = _space_info[id].space();
 892     const size_t live = pointer_delta(_space_info[id].new_top(),
 893                                       space->bottom());
 894     const size_t available = pointer_delta(dst_space_end, *new_top_addr);
 895 
 896     if (live > 0 && live <= available) {
 897       // All the live data will fit.
 898       bool done = _summary_data.summarize(_space_info[id].split_info(),
 899                                           space->bottom(), space->top(),
 900                                           nullptr,
 901                                           *new_top_addr, dst_space_end,
 902                                           new_top_addr);
 903       assert(done, "space must fit into old gen");
 904 
 905       // Reset the new_top value for the space.
 906       _space_info[id].set_new_top(space->bottom());
 907     } else if (live > 0) {
 908       // Attempt to fit part of the source space into the target space.
 909       HeapWord* next_src_addr = nullptr;
 910       bool done = _summary_data.summarize(_space_info[id].split_info(),
 911                                           space->bottom(), space->top(),
 912                                           &next_src_addr,
 913                                           *new_top_addr, dst_space_end,
 914                                           new_top_addr);
 915       assert(!done, "space should not fit into old gen");
 916       assert(next_src_addr != nullptr, "sanity");
 917 
 918       // The source space becomes the new target, so the remainder is compacted
 919       // within the space itself.
 920       dst_space_id = SpaceId(id);
 921       dst_space_end = space->end();
 922       new_top_addr = _space_info[id].new_top_addr();
 923       done = _summary_data.summarize(_space_info[id].split_info(),
 924                                      next_src_addr, space->top(),
 925                                      nullptr,
 926                                      space->bottom(), dst_space_end,
 927                                      new_top_addr);
 928       assert(done, "space must fit when compacted into itself");
 929       assert(*new_top_addr <= space->top(), "usage should not grow");
 930     }
 931   }
 932 }
 933 
 934 bool PSParallelCompact::invoke(bool clear_all_soft_refs, bool should_do_max_compaction) {
 935   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 936   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
 937          "should be in vm thread");
 938   assert(ref_processor() != nullptr, "Sanity");
 939 
 940   SvcGCMarker sgcm(SvcGCMarker::FULL);
 941   IsSTWGCActiveMark mark;
 942 
 943   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 944 
 945   GCIdMark gc_id_mark;
 946   _gc_timer.register_gc_start();
 947   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
 948 
 949   GCCause::Cause gc_cause = heap->gc_cause();
 950   PSOldGen* old_gen = heap->old_gen();
 951   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
 952 
 953   // Make sure data structures are sane, make the heap parsable, and do other
 954   // miscellaneous bookkeeping.
 955   pre_compact();
 956 
 957   const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
 958 
 959   {
 960     const uint active_workers =
 961       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
 962                                         ParallelScavengeHeap::heap()->workers().active_workers(),
 963                                         Threads::number_of_non_daemon_threads());
 964     ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
 965 
 966     GCTraceCPUTime tcpu(&_gc_tracer);
 967     GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
 968 
 969     heap->pre_full_gc_dump(&_gc_timer);
 970 
 971     TraceCollectorStats tcs(counters());
 972     TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
 973 
 974     if (log_is_enabled(Debug, gc, heap, exit)) {
 975       accumulated_time()->start();
 976     }
 977 
 978     // Let the size policy know we're starting
 979     size_policy->major_collection_begin();
 980 
 981 #if COMPILER2_OR_JVMCI
 982     DerivedPointerTable::clear();
 983 #endif
 984 
 985     ref_processor()->start_discovery(clear_all_soft_refs);
 986 
 987     marking_phase(&_gc_tracer);
 988 
 989     summary_phase(should_do_max_compaction);
 990 
 991 #if COMPILER2_OR_JVMCI
 992     assert(DerivedPointerTable::is_active(), "Sanity");
 993     DerivedPointerTable::set_active(false);
 994 #endif
 995 
 996     forward_to_new_addr();
 997 
 998     adjust_pointers();
 999 
1000     compact();
1001 
1002     ParCompactionManager::_preserved_marks_set->restore(&ParallelScavengeHeap::heap()->workers());
1003 
1004     ParCompactionManager::verify_all_region_stack_empty();
1005 
1006     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
1007     // done before resizing.
1008     post_compact();
1009 
1010     size_policy->major_collection_end();
1011 
1012     size_policy->sample_old_gen_used_bytes(MAX2(pre_gc_values.old_gen_used(), old_gen->used_in_bytes()));
1013 
1014     if (UseAdaptiveSizePolicy) {
1015       heap->resize_after_full_gc();
1016     }
1017 
1018     heap->resize_all_tlabs();
1019 
1020     // Resize the metaspace capacity after a collection
1021     MetaspaceGC::compute_new_size();
1022 
1023     if (log_is_enabled(Debug, gc, heap, exit)) {
1024       accumulated_time()->stop();
1025     }
1026 
1027     heap->print_heap_change(pre_gc_values);
1028 
1029     // Track memory usage and detect low memory
1030     MemoryService::track_memory_usage();
1031     heap->update_counters();
1032 
1033     heap->post_full_gc_dump(&_gc_timer);
1034 
1035     size_policy->record_gc_pause_end_instant();
1036   }
1037 
1038   heap->gc_epilogue(true);
1039 
1040   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1041     Universe::verify("After GC");
1042   }
1043 
1044   heap->print_after_gc();
1045   heap->trace_heap_after_gc(&_gc_tracer);
1046 
1047   _gc_timer.register_gc_end();
1048 
1049   _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1050   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1051 
1052   return true;
1053 }
1054 
1055 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1056   ParCompactionManager* _cm;
1057 
1058 public:
1059   PCAddThreadRootsMarkingTaskClosure(ParCompactionManager* cm) : _cm(cm) { }
1060   void do_thread(Thread* thread) {
1061     ResourceMark rm;
1062 
1063     MarkingNMethodClosure mark_and_push_in_blobs(&_cm->_mark_and_push_closure);
1064 
1065     thread->oops_do(&_cm->_mark_and_push_closure, &mark_and_push_in_blobs);
1066 
1067     // Do the real work
1068     _cm->follow_marking_stacks();
1069   }
1070 };
1071 
1072 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1073   assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1074 
1075   ParCompactionManager* cm =
1076     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1077 
1078   do {
1079     ScannerTask task;
1080     if (ParCompactionManager::steal(worker_id, task)) {
1081       cm->follow_contents(task, true);
1082     }
1083     cm->follow_marking_stacks();
1084   } while (!terminator.offer_termination());
1085 }
1086 
1087 class MarkFromRootsTask : public WorkerTask {
1088   NMethodMarkingScope _nmethod_marking_scope;
1089   ThreadsClaimTokenScope _threads_claim_token_scope;
1090   OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1091   TaskTerminator _terminator;
1092   uint _active_workers;
1093 
1094 public:
1095   MarkFromRootsTask(uint active_workers) :
1096       WorkerTask("MarkFromRootsTask"),
1097       _nmethod_marking_scope(),
1098       _threads_claim_token_scope(),
1099       _terminator(active_workers, ParCompactionManager::marking_stacks()),
1100       _active_workers(active_workers) {}
1101 
1102   virtual void work(uint worker_id) {
1103     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1104     cm->create_marking_stats_cache();
1105     {
1106       CLDToOopClosure cld_closure(&cm->_mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1107       ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1108 
1109       // Do the real work
1110       cm->follow_marking_stacks();
1111     }
1112 
1113     {
1114       PCAddThreadRootsMarkingTaskClosure closure(cm);
1115       Threads::possibly_parallel_threads_do(_active_workers > 1 /* is_par */, &closure);
1116     }
1117 
1118     // Mark from OopStorages
1119     {
1120       _oop_storage_set_par_state.oops_do(&cm->_mark_and_push_closure);
1121       // Do the real work
1122       cm->follow_marking_stacks();
1123     }
1124 
1125     if (_active_workers > 1) {
1126       steal_marking_work(_terminator, worker_id);
1127     }
1128   }
1129 };
1130 
1131 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
1132   TaskTerminator _terminator;
1133 
1134 public:
1135   ParallelCompactRefProcProxyTask(uint max_workers)
1136     : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
1137       _terminator(_max_workers, ParCompactionManager::marking_stacks()) {}
1138 
1139   void work(uint worker_id) override {
1140     assert(worker_id < _max_workers, "sanity");
1141     ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
1142     BarrierEnqueueDiscoveredFieldClosure enqueue;
1143     ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
1144     _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &cm->_mark_and_push_closure, &enqueue, &complete_gc);
1145   }
1146 
1147   void prepare_run_task_hook() override {
1148     _terminator.reset_for_reuse(_queue_count);
1149   }
1150 };
1151 
1152 static void flush_marking_stats_cache(const uint num_workers) {
1153   for (uint i = 0; i < num_workers; ++i) {
1154     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(i);
1155     cm->flush_and_destroy_marking_stats_cache();
1156   }
1157 }
1158 
1159 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
1160   // Recursively traverse all live objects and mark them
1161   GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
1162 
1163   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1164 
1165   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
1166   {
1167     GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
1168 
1169     MarkFromRootsTask task(active_gc_threads);
1170     ParallelScavengeHeap::heap()->workers().run_task(&task);
1171   }
1172 
1173   // Process reference objects found during marking
1174   {
1175     GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
1176 
1177     ReferenceProcessorStats stats;
1178     ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
1179 
1180     ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
1181     stats = ref_processor()->process_discovered_references(task, &ParallelScavengeHeap::heap()->workers(), pt);
1182 
1183     gc_tracer->report_gc_reference_stats(stats);
1184     pt.print_all_references();
1185   }
1186 
1187   {
1188     GCTraceTime(Debug, gc, phases) tm("Flush Marking Stats", &_gc_timer);
1189 
1190     flush_marking_stats_cache(active_gc_threads);
1191   }
1192 
1193   // This is the point where the entire marking should have completed.
1194   ParCompactionManager::verify_all_marking_stack_empty();
1195 
1196   {
1197     GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
1198     WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
1199                                 is_alive_closure(),
1200                                 &do_nothing_cl,
1201                                 1);
1202   }
1203 
1204   {
1205     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
1206 
1207     ClassUnloadingContext ctx(1 /* num_nmethod_unlink_workers */,
1208                               false /* unregister_nmethods_during_purge */,
1209                               false /* lock_nmethod_free_separately */);
1210 
1211     bool unloading_occurred;
1212     {
1213       CodeCache::UnlinkingScope scope(is_alive_closure());
1214 
1215       // Follow system dictionary roots and unload classes.
1216       unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
1217 
1218       // Unload nmethods.
1219       CodeCache::do_unloading(unloading_occurred);
1220     }
1221 
1222     {
1223       GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
1224       // Release unloaded nmethod's memory.
1225       ctx.purge_nmethods();
1226     }
1227     {
1228       GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
1229       ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
1230     }
1231     {
1232       GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
1233       ctx.free_nmethods();
1234     }
1235 
1236     // Prune dead klasses from subklass/sibling/implementor lists.
1237     Klass::clean_weak_klass_links(unloading_occurred);
1238 
1239     // Clean JVMCI metadata handles.
1240     JVMCI_ONLY(JVMCI::do_unloading(unloading_occurred));
1241     {
1242       // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1243       GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
1244       ClassLoaderDataGraph::purge(true /* at_safepoint */);
1245       DEBUG_ONLY(MetaspaceUtils::verify();)
1246     }
1247   }
1248 
1249   {
1250     GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
1251     _gc_tracer.report_object_count_after_gc(is_alive_closure(), &ParallelScavengeHeap::heap()->workers());
1252   }
1253 #if TASKQUEUE_STATS
1254   ParCompactionManager::print_and_reset_taskqueue_stats();
1255 #endif
1256 }
1257 
1258 template<typename Func>
1259 void PSParallelCompact::adjust_in_space_helper(SpaceId id, volatile uint* claim_counter, Func&& on_stripe) {
1260   MutableSpace* sp = PSParallelCompact::space(id);
1261   HeapWord* const bottom = sp->bottom();
1262   HeapWord* const top = sp->top();
1263   if (bottom == top) {
1264     return;
1265   }
1266 
1267   const uint num_regions_per_stripe = 2;
1268   const size_t region_size = ParallelCompactData::RegionSize;
1269   const size_t stripe_size = num_regions_per_stripe * region_size;
1270 
1271   while (true) {
1272     uint counter = AtomicAccess::fetch_then_add(claim_counter, num_regions_per_stripe);
1273     HeapWord* cur_stripe = bottom + counter * region_size;
1274     if (cur_stripe >= top) {
1275       break;
1276     }
1277     HeapWord* stripe_end = MIN2(cur_stripe + stripe_size, top);
1278     on_stripe(cur_stripe, stripe_end);
1279   }
1280 }
1281 
1282 void PSParallelCompact::adjust_in_old_space(volatile uint* claim_counter) {
1283   // Regions in old-space shouldn't be split.
1284   assert(!_space_info[old_space_id].split_info().is_valid(), "inv");
1285 
1286   auto scan_obj_with_limit = [&] (HeapWord* obj_start, HeapWord* left, HeapWord* right) {
1287     assert(mark_bitmap()->is_marked(obj_start), "inv");
1288     oop obj = cast_to_oop(obj_start);
1289     return obj->oop_iterate_size(&pc_adjust_pointer_closure, MemRegion(left, right));
1290   };
1291 
1292   adjust_in_space_helper(old_space_id, claim_counter, [&] (HeapWord* stripe_start, HeapWord* stripe_end) {
1293     assert(_summary_data.is_region_aligned(stripe_start), "inv");
1294     RegionData* cur_region = _summary_data.addr_to_region_ptr(stripe_start);
1295     HeapWord* obj_start;
1296     if (cur_region->partial_obj_size() != 0) {
1297       obj_start = cur_region->partial_obj_addr();
1298       obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1299     } else {
1300       obj_start = stripe_start;
1301     }
1302 
1303     while (obj_start < stripe_end) {
1304       obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1305       if (obj_start >= stripe_end) {
1306         break;
1307       }
1308       obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1309     }
1310   });
1311 }
1312 
1313 void PSParallelCompact::adjust_in_young_space(SpaceId id, volatile uint* claim_counter) {
1314   adjust_in_space_helper(id, claim_counter, [](HeapWord* stripe_start, HeapWord* stripe_end) {
1315     HeapWord* obj_start = stripe_start;
1316     while (obj_start < stripe_end) {
1317       obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1318       if (obj_start >= stripe_end) {
1319         break;
1320       }
1321       oop obj = cast_to_oop(obj_start);
1322       obj_start += obj->oop_iterate_size(&pc_adjust_pointer_closure);
1323     }
1324   });
1325 }
1326 
1327 void PSParallelCompact::adjust_pointers_in_spaces(uint worker_id, volatile uint* claim_counters) {
1328   auto start_time = Ticks::now();
1329   adjust_in_old_space(&claim_counters[0]);
1330   for (uint id = eden_space_id; id < last_space_id; ++id) {
1331     adjust_in_young_space(SpaceId(id), &claim_counters[id]);
1332   }
1333   log_trace(gc, phases)("adjust_pointers_in_spaces worker %u: %.3f ms", worker_id, (Ticks::now() - start_time).seconds() * 1000);
1334 }
1335 
1336 class PSAdjustTask final : public WorkerTask {
1337   SubTasksDone                               _sub_tasks;
1338   WeakProcessor::Task                        _weak_proc_task;
1339   OopStorageSetStrongParState<false, false>  _oop_storage_iter;
1340   uint                                       _nworkers;
1341   volatile uint _claim_counters[PSParallelCompact::last_space_id] = {};
1342 
1343   enum PSAdjustSubTask {
1344     PSAdjustSubTask_code_cache,
1345 
1346     PSAdjustSubTask_num_elements
1347   };
1348 
1349 public:
1350   PSAdjustTask(uint nworkers) :
1351     WorkerTask("PSAdjust task"),
1352     _sub_tasks(PSAdjustSubTask_num_elements),
1353     _weak_proc_task(nworkers),
1354     _nworkers(nworkers) {
1355 
1356     ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
1357     Threads::change_thread_claim_token();
1358   }
1359 
1360   ~PSAdjustTask() {
1361     Threads::assert_all_threads_claimed();
1362   }
1363 
1364   void work(uint worker_id) {
1365     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1366     cm->preserved_marks()->adjust_during_full_gc();
1367     {
1368       // adjust pointers in all spaces
1369       PSParallelCompact::adjust_pointers_in_spaces(worker_id, _claim_counters);
1370     }
1371     {
1372       ResourceMark rm;
1373       Threads::possibly_parallel_oops_do(_nworkers > 1, &pc_adjust_pointer_closure, nullptr);
1374     }
1375     _oop_storage_iter.oops_do(&pc_adjust_pointer_closure);
1376     {
1377       CLDToOopClosure cld_closure(&pc_adjust_pointer_closure, ClassLoaderData::_claim_stw_fullgc_adjust);
1378       ClassLoaderDataGraph::cld_do(&cld_closure);
1379     }
1380     {
1381       AlwaysTrueClosure always_alive;
1382       _weak_proc_task.work(worker_id, &always_alive, &pc_adjust_pointer_closure);
1383     }
1384     if (_sub_tasks.try_claim_task(PSAdjustSubTask_code_cache)) {
1385       NMethodToOopClosure adjust_code(&pc_adjust_pointer_closure, NMethodToOopClosure::FixRelocations);
1386       CodeCache::nmethods_do(&adjust_code);
1387     }
1388     _sub_tasks.all_tasks_claimed();
1389   }
1390 };
1391 
1392 void PSParallelCompact::adjust_pointers() {
1393   // Adjust the pointers to reflect the new locations
1394   GCTraceTime(Info, gc, phases) tm("Adjust Pointers", &_gc_timer);
1395   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1396   PSAdjustTask task(nworkers);
1397   ParallelScavengeHeap::heap()->workers().run_task(&task);
1398 }
1399 
1400 // Split [start, end) evenly for a number of workers and return the
1401 // range for worker_id.
1402 static void split_regions_for_worker(size_t start, size_t end,
1403                                      uint worker_id, uint num_workers,
1404                                      size_t* worker_start, size_t* worker_end) {
1405   assert(start < end, "precondition");
1406   assert(num_workers > 0, "precondition");
1407   assert(worker_id < num_workers, "precondition");
1408 
1409   size_t num_regions = end - start;
1410   size_t num_regions_per_worker = num_regions / num_workers;
1411   size_t remainder = num_regions % num_workers;
1412   // The first few workers will get one extra.
1413   *worker_start = start + worker_id * num_regions_per_worker
1414                   + MIN2(checked_cast<size_t>(worker_id), remainder);
1415   *worker_end = *worker_start + num_regions_per_worker
1416                 + (worker_id < remainder ? 1 : 0);
1417 }
1418 
1419 void PSParallelCompact::forward_to_new_addr() {
1420   GCTraceTime(Info, gc, phases) tm("Forward", &_gc_timer);
1421   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1422 
1423   struct ForwardTask final : public WorkerTask {
1424     uint _num_workers;
1425 
1426     explicit ForwardTask(uint num_workers) :
1427       WorkerTask("PSForward task"),
1428       _num_workers(num_workers) {}
1429 
1430     static void forward_objs_in_range(ParCompactionManager* cm,
1431                                       HeapWord* start,
1432                                       HeapWord* end,
1433                                       HeapWord* destination) {
1434       HeapWord* cur_addr = start;
1435       HeapWord* new_addr = destination;
1436 
1437       while (cur_addr < end) {
1438         cur_addr = mark_bitmap()->find_obj_beg(cur_addr, end);
1439         if (cur_addr >= end) {
1440           return;
1441         }
1442         assert(mark_bitmap()->is_marked(cur_addr), "inv");
1443         oop obj = cast_to_oop(cur_addr);
1444         if (new_addr != cur_addr) {
1445           cm->preserved_marks()->push_if_necessary(obj, obj->mark());
1446           FullGCForwarding::forward_to(obj, cast_to_oop(new_addr));
1447         }
1448         size_t obj_size = obj->size();
1449         new_addr += obj_size;
1450         cur_addr += obj_size;
1451       }
1452     }
1453 
1454     void work(uint worker_id) override {
1455       ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1456       for (uint id = old_space_id; id < last_space_id; ++id) {
1457         MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1458         HeapWord* dense_prefix_addr = dense_prefix(SpaceId(id));
1459         HeapWord* top = sp->top();
1460 
1461         if (dense_prefix_addr == top) {
1462           // Empty space
1463           continue;
1464         }
1465 
1466         const SplitInfo& split_info = _space_info[SpaceId(id)].split_info();
1467         size_t dense_prefix_region = _summary_data.addr_to_region_idx(dense_prefix_addr);
1468         size_t top_region = _summary_data.addr_to_region_idx(_summary_data.region_align_up(top));
1469         size_t start_region;
1470         size_t end_region;
1471         split_regions_for_worker(dense_prefix_region, top_region,
1472                                  worker_id, _num_workers,
1473                                  &start_region, &end_region);
1474         for (size_t cur_region = start_region; cur_region < end_region; ++cur_region) {
1475           RegionData* region_ptr = _summary_data.region(cur_region);
1476           size_t partial_obj_size = region_ptr->partial_obj_size();
1477 
1478           if (partial_obj_size == ParallelCompactData::RegionSize) {
1479             // No obj-start
1480             continue;
1481           }
1482 
1483           HeapWord* region_start = _summary_data.region_to_addr(cur_region);
1484           HeapWord* region_end = region_start + ParallelCompactData::RegionSize;
1485 
1486           if (split_info.is_split(cur_region)) {
1487             // Part 1: will be relocated to space-1
1488             HeapWord* preceding_destination = split_info.preceding_destination();
1489             HeapWord* split_point = split_info.split_point();
1490             forward_objs_in_range(cm, region_start + partial_obj_size, split_point, preceding_destination + partial_obj_size);
1491 
1492             // Part 2: will be relocated to space-2
1493             HeapWord* destination = region_ptr->destination();
1494             forward_objs_in_range(cm, split_point, region_end, destination);
1495           } else {
1496             HeapWord* destination = region_ptr->destination();
1497             forward_objs_in_range(cm, region_start + partial_obj_size, region_end, destination + partial_obj_size);
1498           }
1499         }
1500       }
1501     }
1502   } task(nworkers);
1503 
1504   ParallelScavengeHeap::heap()->workers().run_task(&task);
1505   DEBUG_ONLY(verify_forward();)
1506 }
1507 
1508 #ifdef ASSERT
1509 void PSParallelCompact::verify_forward() {
1510   HeapWord* const old_dense_prefix_addr = dense_prefix(SpaceId(old_space_id));
1511   // The destination addr for the first live obj after dense-prefix.
1512   HeapWord* bump_ptr = old_dense_prefix_addr
1513                      + _summary_data.addr_to_region_ptr(old_dense_prefix_addr)->partial_obj_size();
1514   SpaceId bump_ptr_space = old_space_id;
1515 
1516   for (uint id = old_space_id; id < last_space_id; ++id) {
1517     MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1518     // Only verify objs after dense-prefix, because those before dense-prefix are not moved (forwarded).
1519     HeapWord* cur_addr = dense_prefix(SpaceId(id));
1520     HeapWord* top = sp->top();
1521 
1522     while (cur_addr < top) {
1523       cur_addr = mark_bitmap()->find_obj_beg(cur_addr, top);
1524       if (cur_addr >= top) {
1525         break;
1526       }
1527       assert(mark_bitmap()->is_marked(cur_addr), "inv");
1528       assert(bump_ptr <= _space_info[bump_ptr_space].new_top(), "inv");
1529       // Move to the space containing cur_addr
1530       if (bump_ptr == _space_info[bump_ptr_space].new_top()) {
1531         bump_ptr = space(space_id(cur_addr))->bottom();
1532         bump_ptr_space = space_id(bump_ptr);
1533       }
1534       oop obj = cast_to_oop(cur_addr);
1535       if (cur_addr == bump_ptr) {
1536         assert(!FullGCForwarding::is_forwarded(obj), "inv");
1537       } else {
1538         assert(FullGCForwarding::forwardee(obj) == cast_to_oop(bump_ptr), "inv");
1539       }
1540       bump_ptr += obj->size();
1541       cur_addr += obj->size();
1542     }
1543   }
1544 }
1545 #endif
1546 
1547 // Helper class to print 8 region numbers per line and then print the total at the end.
1548 class FillableRegionLogger : public StackObj {
1549 private:
1550   Log(gc, compaction) log;
1551   static const int LineLength = 8;
1552   size_t _regions[LineLength];
1553   int _next_index;
1554   bool _enabled;
1555   size_t _total_regions;
1556 public:
1557   FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
1558   ~FillableRegionLogger() {
1559     log.trace("%zu initially fillable regions", _total_regions);
1560   }
1561 
1562   void print_line() {
1563     if (!_enabled || _next_index == 0) {
1564       return;
1565     }
1566     FormatBuffer<> line("Fillable: ");
1567     for (int i = 0; i < _next_index; i++) {
1568       line.append(" %7zu", _regions[i]);
1569     }
1570     log.trace("%s", line.buffer());
1571     _next_index = 0;
1572   }
1573 
1574   void handle(size_t region) {
1575     if (!_enabled) {
1576       return;
1577     }
1578     _regions[_next_index++] = region;
1579     if (_next_index == LineLength) {
1580       print_line();
1581     }
1582     _total_regions++;
1583   }
1584 };
1585 
1586 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
1587 {
1588   GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
1589 
1590   // Find the threads that are active
1591   uint worker_id = 0;
1592 
1593   // Find all regions that are available (can be filled immediately) and
1594   // distribute them to the thread stacks.  The iteration is done in reverse
1595   // order (high to low) so the regions will be removed in ascending order.
1596 
1597   const ParallelCompactData& sd = PSParallelCompact::summary_data();
1598 
1599   // id + 1 is used to test termination so unsigned  can
1600   // be used with an old_space_id == 0.
1601   FillableRegionLogger region_logger;
1602   for (unsigned int id = last_space_id - 1; id + 1 > old_space_id; --id) {
1603     SpaceInfo* const space_info = _space_info + id;
1604     HeapWord* const new_top = space_info->new_top();
1605 
1606     const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
1607     const size_t end_region =
1608       sd.addr_to_region_idx(sd.region_align_up(new_top));
1609 
1610     for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
1611       if (sd.region(cur)->claim_unsafe()) {
1612         ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1613         bool result = sd.region(cur)->mark_normal();
1614         assert(result, "Must succeed at this point.");
1615         cm->region_stack()->push(cur);
1616         region_logger.handle(cur);
1617         // Assign regions to tasks in round-robin fashion.
1618         if (++worker_id == parallel_gc_threads) {
1619           worker_id = 0;
1620         }
1621       }
1622     }
1623     region_logger.print_line();
1624   }
1625 }
1626 
1627 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
1628   assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1629 
1630   ParCompactionManager* cm =
1631     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1632 
1633   // Drain the stacks that have been preloaded with regions
1634   // that are ready to fill.
1635 
1636   cm->drain_region_stacks();
1637 
1638   guarantee(cm->region_stack()->is_empty(), "Not empty");
1639 
1640   size_t region_index = 0;
1641 
1642   while (true) {
1643     if (ParCompactionManager::steal(worker_id, region_index)) {
1644       PSParallelCompact::fill_and_update_region(cm, region_index);
1645       cm->drain_region_stacks();
1646     } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
1647       // Fill and update an unavailable region with the help of a shadow region
1648       PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
1649       cm->drain_region_stacks();
1650     } else {
1651       if (terminator->offer_termination()) {
1652         break;
1653       }
1654       // Go around again.
1655     }
1656   }
1657 }
1658 
1659 class FillDensePrefixAndCompactionTask: public WorkerTask {
1660   TaskTerminator _terminator;
1661 
1662 public:
1663   FillDensePrefixAndCompactionTask(uint active_workers) :
1664       WorkerTask("FillDensePrefixAndCompactionTask"),
1665       _terminator(active_workers, ParCompactionManager::region_task_queues()) {
1666   }
1667 
1668   virtual void work(uint worker_id) {
1669     if (worker_id == 0) {
1670       auto start = Ticks::now();
1671       PSParallelCompact::fill_dead_objs_in_dense_prefix();
1672       log_trace(gc, phases)("Fill dense prefix by worker 0: %.3f ms", (Ticks::now() - start).seconds() * 1000);
1673     }
1674     compaction_with_stealing_work(&_terminator, worker_id);
1675   }
1676 };
1677 
1678 void PSParallelCompact::fill_range_in_dense_prefix(HeapWord* start, HeapWord* end) {
1679 #ifdef ASSERT
1680   {
1681     assert(start < end, "precondition");
1682     assert(mark_bitmap()->find_obj_beg(start, end) == end, "precondition");
1683     HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1684     if (start != bottom) {
1685       // The preceding live obj.
1686       HeapWord* obj_start = mark_bitmap()->find_obj_beg_reverse(bottom, start);
1687       HeapWord* obj_end = obj_start + cast_to_oop(obj_start)->size();
1688       assert(obj_end == start, "precondition");
1689     }
1690   }
1691 #endif
1692 
1693   CollectedHeap::fill_with_objects(start, pointer_delta(end, start));
1694   HeapWord* addr = start;
1695   do {
1696     size_t size = cast_to_oop(addr)->size();
1697     start_array(old_space_id)->update_for_block(addr, addr + size);
1698     addr += size;
1699   } while (addr < end);
1700 }
1701 
1702 void PSParallelCompact::fill_dead_objs_in_dense_prefix() {
1703   ParMarkBitMap* bitmap = mark_bitmap();
1704 
1705   HeapWord* const bottom = _space_info[old_space_id].space()->bottom();
1706   HeapWord* const prefix_end = dense_prefix(old_space_id);
1707 
1708   const size_t region_size = ParallelCompactData::RegionSize;
1709 
1710   // Fill dead space in [start_addr, end_addr)
1711   HeapWord* const start_addr = bottom;
1712   HeapWord* const end_addr   = prefix_end;
1713 
1714   for (HeapWord* cur_addr = start_addr; cur_addr < end_addr; /* empty */) {
1715     RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1716     if (cur_region_ptr->data_size() == region_size) {
1717       // Full; no dead space. Next region.
1718       if (_summary_data.is_region_aligned(cur_addr)) {
1719         cur_addr += region_size;
1720       } else {
1721         cur_addr = _summary_data.region_align_up(cur_addr);
1722       }
1723       continue;
1724     }
1725 
1726     // Fill dead space inside cur_region.
1727     if (_summary_data.is_region_aligned(cur_addr)) {
1728       cur_addr += cur_region_ptr->partial_obj_size();
1729     }
1730 
1731     HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1732     assert(region_end_addr <= end_addr, "inv");
1733     while (cur_addr < region_end_addr) {
1734       // Use end_addr to allow filler-obj to cross region boundary.
1735       HeapWord* live_start = bitmap->find_obj_beg(cur_addr, end_addr);
1736       if (cur_addr != live_start) {
1737         // Found dead space [cur_addr, live_start).
1738         fill_range_in_dense_prefix(cur_addr, live_start);
1739       }
1740       if (live_start >= region_end_addr) {
1741         cur_addr = live_start;
1742         break;
1743       }
1744       assert(bitmap->is_marked(live_start), "inv");
1745       cur_addr = live_start + cast_to_oop(live_start)->size();
1746     }
1747   }
1748 }
1749 
1750 void PSParallelCompact::compact() {
1751   GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
1752 
1753   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1754 
1755   initialize_shadow_regions(active_gc_threads);
1756   prepare_region_draining_tasks(active_gc_threads);
1757 
1758   {
1759     GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
1760 
1761     FillDensePrefixAndCompactionTask task(active_gc_threads);
1762     ParallelScavengeHeap::heap()->workers().run_task(&task);
1763 
1764 #ifdef  ASSERT
1765     verify_filler_in_dense_prefix();
1766 
1767     // Verify that all regions have been processed.
1768     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1769       verify_complete(SpaceId(id));
1770     }
1771 #endif
1772   }
1773 }
1774 
1775 #ifdef  ASSERT
1776 void PSParallelCompact::verify_filler_in_dense_prefix() {
1777   HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1778   HeapWord* dense_prefix_end = dense_prefix(old_space_id);
1779 
1780   const size_t region_size = ParallelCompactData::RegionSize;
1781 
1782   for (HeapWord* cur_addr = bottom; cur_addr < dense_prefix_end; /* empty */) {
1783     RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1784     if (cur_region_ptr->data_size() == region_size) {
1785       // Full; no dead space. Next region.
1786       if (_summary_data.is_region_aligned(cur_addr)) {
1787         cur_addr += region_size;
1788       } else {
1789         cur_addr = _summary_data.region_align_up(cur_addr);
1790       }
1791       continue;
1792     }
1793 
1794     // This region contains filler objs.
1795     if (_summary_data.is_region_aligned(cur_addr)) {
1796       cur_addr += cur_region_ptr->partial_obj_size();
1797     }
1798 
1799     HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1800     assert(region_end_addr <= dense_prefix_end, "inv");
1801 
1802     while (cur_addr < region_end_addr) {
1803       oop obj = cast_to_oop(cur_addr);
1804       oopDesc::verify(obj);
1805       if (!mark_bitmap()->is_marked(cur_addr)) {
1806         Klass* k = cast_to_oop(cur_addr)->klass();
1807         assert(k == Universe::fillerArrayKlass() || k == vmClasses::FillerObject_klass(), "inv");
1808       }
1809       cur_addr += obj->size();
1810     }
1811   }
1812 }
1813 
1814 void PSParallelCompact::verify_complete(SpaceId space_id) {
1815   // All Regions served as compaction targets, from dense_prefix() to
1816   // new_top(), should be marked as filled and all Regions between new_top()
1817   // and top() should be available (i.e., should have been emptied).
1818   ParallelCompactData& sd = summary_data();
1819   SpaceInfo si = _space_info[space_id];
1820   HeapWord* new_top_addr = sd.region_align_up(si.new_top());
1821   HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
1822   const size_t beg_region = sd.addr_to_region_idx(si.dense_prefix());
1823   const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
1824   const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
1825 
1826   size_t cur_region;
1827   for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
1828     const RegionData* const c = sd.region(cur_region);
1829     assert(c->completed(), "region %zu not filled: destination_count=%u",
1830            cur_region, c->destination_count());
1831   }
1832 
1833   for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
1834     const RegionData* const c = sd.region(cur_region);
1835     assert(c->available(), "region %zu not empty: destination_count=%u",
1836            cur_region, c->destination_count());
1837   }
1838 }
1839 #endif  // #ifdef ASSERT
1840 
1841 // Return the SpaceId for the space containing addr.  If addr is not in the
1842 // heap, last_space_id is returned.  In debug mode it expects the address to be
1843 // in the heap and asserts such.
1844 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
1845   assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
1846 
1847   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1848     if (_space_info[id].space()->contains(addr)) {
1849       return SpaceId(id);
1850     }
1851   }
1852 
1853   assert(false, "no space contains the addr");
1854   return last_space_id;
1855 }
1856 
1857 // Skip over count live words starting from beg, and return the address of the
1858 // next live word. Callers must also ensure that there are enough live words in
1859 // the range [beg, end) to skip.
1860 HeapWord* PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
1861 {
1862   ParMarkBitMap* m = mark_bitmap();
1863   HeapWord* cur_addr = beg;
1864   while (true) {
1865     cur_addr = m->find_obj_beg(cur_addr, end);
1866     assert(cur_addr < end, "inv");
1867     size_t obj_size = cast_to_oop(cur_addr)->size();
1868     // Strictly greater-than
1869     if (obj_size > count) {
1870       return cur_addr + count;
1871     }
1872     count -= obj_size;
1873     cur_addr += obj_size;
1874   }
1875 }
1876 
1877 // On starting to fill a destination region (dest-region), we need to know the
1878 // location of the word that will be at the start of the dest-region after
1879 // compaction. A dest-region can have one or more source regions, but only the
1880 // first source-region contains this location. This location is retrieved by
1881 // calling `first_src_addr` on a dest-region.
1882 // Conversely, a source-region has a dest-region which holds the destination of
1883 // the first live word on this source-region, based on which the destination
1884 // for the rest of live words can be derived.
1885 //
1886 // Note:
1887 // There is some complication due to space-boundary-fragmentation (an obj can't
1888 // cross space-boundary) -- a source-region may be split and behave like two
1889 // distinct regions with their own dest-region, as depicted below.
1890 //
1891 // source-region: region-n
1892 //
1893 // **********************
1894 // |     A|A~~~~B|B     |
1895 // **********************
1896 //    n-1     n     n+1
1897 //
1898 // AA, BB denote two live objs. ~~~~ denotes unknown number of live objs.
1899 //
1900 // Assuming the dest-region for region-n is the final region before
1901 // old-space-end and its first-live-word is the middle of AA, the heap content
1902 // will look like the following after compaction:
1903 //
1904 // **************                  *************
1905 //      A|A~~~~ |                  |BB    |
1906 // **************                  *************
1907 //              ^                  ^
1908 //              | old-space-end    | eden-space-start
1909 //
1910 // Therefore, in this example, region-n will have two dest-regions:
1911 // 1. the final region in old-space
1912 // 2. the first region in eden-space.
1913 // To handle this special case, we introduce the concept of split-region, whose
1914 // contents are relocated to two spaces. `SplitInfo` captures all necessary
1915 // info about the split, the first part, spliting-point, and the second part.
1916 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
1917                                             SpaceId src_space_id,
1918                                             size_t src_region_idx)
1919 {
1920   const size_t RegionSize = ParallelCompactData::RegionSize;
1921   const ParallelCompactData& sd = summary_data();
1922   assert(sd.is_region_aligned(dest_addr), "precondition");
1923 
1924   const RegionData* const src_region_ptr = sd.region(src_region_idx);
1925   assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
1926 
1927   const size_t partial_obj_size = src_region_ptr->partial_obj_size();
1928   HeapWord* const src_region_destination = src_region_ptr->destination();
1929 
1930   HeapWord* const region_start = sd.region_to_addr(src_region_idx);
1931   HeapWord* const region_end = sd.region_to_addr(src_region_idx) + RegionSize;
1932 
1933   // Identify the actual destination for the first live words on this region,
1934   // taking split-region into account.
1935   HeapWord* region_start_destination;
1936   const SplitInfo& split_info = _space_info[src_space_id].split_info();
1937   if (split_info.is_split(src_region_idx)) {
1938     // The second part of this split region; use the recorded split point.
1939     if (dest_addr == src_region_destination) {
1940       return split_info.split_point();
1941     }
1942     region_start_destination = split_info.preceding_destination();
1943   } else {
1944     region_start_destination = src_region_destination;
1945   }
1946 
1947   // Calculate the offset to be skipped
1948   size_t words_to_skip = pointer_delta(dest_addr, region_start_destination);
1949 
1950   HeapWord* result;
1951   if (partial_obj_size > words_to_skip) {
1952     result = region_start + words_to_skip;
1953   } else {
1954     words_to_skip -= partial_obj_size;
1955     result = skip_live_words(region_start + partial_obj_size, region_end, words_to_skip);
1956   }
1957 
1958   if (split_info.is_split(src_region_idx)) {
1959     assert(result < split_info.split_point(), "postcondition");
1960   } else {
1961     assert(result < region_end, "postcondition");
1962   }
1963 
1964   return result;
1965 }
1966 
1967 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
1968                                                      SpaceId src_space_id,
1969                                                      size_t beg_region,
1970                                                      HeapWord* end_addr)
1971 {
1972   ParallelCompactData& sd = summary_data();
1973 
1974 #ifdef ASSERT
1975   MutableSpace* const src_space = _space_info[src_space_id].space();
1976   HeapWord* const beg_addr = sd.region_to_addr(beg_region);
1977   assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
1978          "src_space_id does not match beg_addr");
1979   assert(src_space->contains(end_addr) || end_addr == src_space->end(),
1980          "src_space_id does not match end_addr");
1981 #endif // #ifdef ASSERT
1982 
1983   RegionData* const beg = sd.region(beg_region);
1984   RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
1985 
1986   // Regions up to new_top() are enqueued if they become available.
1987   HeapWord* const new_top = _space_info[src_space_id].new_top();
1988   RegionData* const enqueue_end =
1989     sd.addr_to_region_ptr(sd.region_align_up(new_top));
1990 
1991   for (RegionData* cur = beg; cur < end; ++cur) {
1992     assert(cur->data_size() > 0, "region must have live data");
1993     cur->decrement_destination_count();
1994     if (cur < enqueue_end && cur->available() && cur->claim()) {
1995       if (cur->mark_normal()) {
1996         cm->push_region(sd.region(cur));
1997       } else if (cur->mark_copied()) {
1998         // Try to copy the content of the shadow region back to its corresponding
1999         // heap region if the shadow region is filled. Otherwise, the GC thread
2000         // fills the shadow region will copy the data back (see
2001         // MoveAndUpdateShadowClosure::complete_region).
2002         copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2003         ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2004         cur->set_completed();
2005       }
2006     }
2007   }
2008 }
2009 
2010 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2011                                           SpaceId& src_space_id,
2012                                           HeapWord*& src_space_top,
2013                                           HeapWord* end_addr)
2014 {
2015   ParallelCompactData& sd = PSParallelCompact::summary_data();
2016 
2017   size_t src_region_idx = 0;
2018 
2019   // Skip empty regions (if any) up to the top of the space.
2020   HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2021   RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2022   HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2023   const RegionData* const top_region_ptr = sd.addr_to_region_ptr(top_aligned_up);
2024 
2025   while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2026     ++src_region_ptr;
2027   }
2028 
2029   if (src_region_ptr < top_region_ptr) {
2030     // Found the first non-empty region in the same space.
2031     src_region_idx = sd.region(src_region_ptr);
2032     closure.set_source(sd.region_to_addr(src_region_idx));
2033     return src_region_idx;
2034   }
2035 
2036   // Switch to a new source space and find the first non-empty region.
2037   uint space_id = src_space_id + 1;
2038   assert(space_id < last_space_id, "not enough spaces");
2039 
2040   for (/* empty */; space_id < last_space_id; ++space_id) {
2041     HeapWord* bottom = _space_info[space_id].space()->bottom();
2042     HeapWord* top = _space_info[space_id].space()->top();
2043     // Skip empty space
2044     if (bottom == top) {
2045       continue;
2046     }
2047 
2048     // Identify the first region that contains live words in this space
2049     size_t cur_region = sd.addr_to_region_idx(bottom);
2050     size_t end_region = sd.addr_to_region_idx(sd.region_align_up(top));
2051 
2052     for (/* empty */ ; cur_region < end_region; ++cur_region) {
2053       RegionData* cur = sd.region(cur_region);
2054       if (cur->live_obj_size() > 0) {
2055         HeapWord* region_start_addr = sd.region_to_addr(cur_region);
2056 
2057         src_space_id = SpaceId(space_id);
2058         src_space_top = top;
2059         closure.set_source(region_start_addr);
2060         return cur_region;
2061       }
2062     }
2063   }
2064 
2065   ShouldNotReachHere();
2066 }
2067 
2068 HeapWord* PSParallelCompact::partial_obj_end(HeapWord* region_start_addr) {
2069   ParallelCompactData& sd = summary_data();
2070   assert(sd.is_region_aligned(region_start_addr), "precondition");
2071 
2072   // Use per-region partial_obj_size to locate the end of the obj, that extends
2073   // to region_start_addr.
2074   size_t start_region_idx = sd.addr_to_region_idx(region_start_addr);
2075   size_t end_region_idx = sd.region_count();
2076   size_t accumulated_size = 0;
2077   for (size_t region_idx = start_region_idx; region_idx < end_region_idx; ++region_idx) {
2078     size_t cur_partial_obj_size = sd.region(region_idx)->partial_obj_size();
2079     accumulated_size += cur_partial_obj_size;
2080     if (cur_partial_obj_size != ParallelCompactData::RegionSize) {
2081       break;
2082     }
2083   }
2084   return region_start_addr + accumulated_size;
2085 }
2086 
2087 // Use region_idx as the destination region, and evacuate all live objs on its
2088 // source regions to this destination region.
2089 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2090 {
2091   ParMarkBitMap* const bitmap = mark_bitmap();
2092   ParallelCompactData& sd = summary_data();
2093   RegionData* const region_ptr = sd.region(region_idx);
2094 
2095   // Get the source region and related info.
2096   size_t src_region_idx = region_ptr->source_region();
2097   SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2098   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2099   HeapWord* dest_addr = sd.region_to_addr(region_idx);
2100 
2101   closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2102 
2103   // Adjust src_region_idx to prepare for decrementing destination counts (the
2104   // destination count is not decremented when a region is copied to itself).
2105   if (src_region_idx == region_idx) {
2106     src_region_idx += 1;
2107   }
2108 
2109   // source-region:
2110   //
2111   // **********
2112   // |   ~~~  |
2113   // **********
2114   //      ^
2115   //      |-- closure.source() / first_src_addr
2116   //
2117   //
2118   // ~~~ : live words
2119   //
2120   // destination-region:
2121   //
2122   // **********
2123   // |        |
2124   // **********
2125   // ^
2126   // |-- region-start
2127   if (bitmap->is_unmarked(closure.source())) {
2128     // An object overflows the previous destination region, so this
2129     // destination region should copy the remainder of the object or as much as
2130     // will fit.
2131     HeapWord* const old_src_addr = closure.source();
2132     {
2133       HeapWord* region_start = sd.region_align_down(closure.source());
2134       HeapWord* obj_start = bitmap->find_obj_beg_reverse(region_start, closure.source());
2135       HeapWord* obj_end;
2136       if (obj_start != closure.source()) {
2137         assert(bitmap->is_marked(obj_start), "inv");
2138         // Found the actual obj-start, try to find the obj-end using either
2139         // size() if this obj is completely contained in the current region.
2140         HeapWord* next_region_start = region_start + ParallelCompactData::RegionSize;
2141         HeapWord* partial_obj_start = (next_region_start >= src_space_top)
2142                                       ? nullptr
2143                                       : sd.addr_to_region_ptr(next_region_start)->partial_obj_addr();
2144         // This obj extends to next region iff partial_obj_addr of the *next*
2145         // region is the same as obj-start.
2146         if (partial_obj_start == obj_start) {
2147           // This obj extends to next region.
2148           obj_end = partial_obj_end(next_region_start);
2149         } else {
2150           // Completely contained in this region; safe to use size().
2151           obj_end = obj_start + cast_to_oop(obj_start)->size();
2152         }
2153       } else {
2154         // This obj extends to current region.
2155         obj_end = partial_obj_end(region_start);
2156       }
2157       size_t partial_obj_size = pointer_delta(obj_end, closure.source());
2158       closure.copy_partial_obj(partial_obj_size);
2159     }
2160 
2161     if (closure.is_full()) {
2162       decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2163       closure.complete_region(dest_addr, region_ptr);
2164       return;
2165     }
2166 
2167     // Finished copying without using up the current destination-region
2168     HeapWord* const end_addr = sd.region_align_down(closure.source());
2169     if (sd.region_align_down(old_src_addr) != end_addr) {
2170       assert(sd.region_align_up(old_src_addr) == end_addr, "only one region");
2171       // The partial object was copied from more than one source region.
2172       decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2173 
2174       // Move to the next source region, possibly switching spaces as well.  All
2175       // args except end_addr may be modified.
2176       src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2177     }
2178   }
2179 
2180   // Handle the rest obj-by-obj, where we know obj-start.
2181   do {
2182     HeapWord* cur_addr = closure.source();
2183     HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2184                                     src_space_top);
2185     // To handle the case where the final obj in source region extends to next region.
2186     HeapWord* final_obj_start = (end_addr == src_space_top)
2187                                 ? nullptr
2188                                 : sd.addr_to_region_ptr(end_addr)->partial_obj_addr();
2189     // Apply closure on objs inside [cur_addr, end_addr)
2190     do {
2191       cur_addr = bitmap->find_obj_beg(cur_addr, end_addr);
2192       if (cur_addr == end_addr) {
2193         break;
2194       }
2195       size_t obj_size;
2196       if (final_obj_start == cur_addr) {
2197         obj_size = pointer_delta(partial_obj_end(end_addr), cur_addr);
2198       } else {
2199         // This obj doesn't extend into next region; size() is safe to use.
2200         obj_size = cast_to_oop(cur_addr)->size();
2201       }
2202       closure.do_addr(cur_addr, obj_size);
2203       cur_addr += obj_size;
2204     } while (cur_addr < end_addr && !closure.is_full());
2205 
2206     if (closure.is_full()) {
2207       decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2208       closure.complete_region(dest_addr, region_ptr);
2209       return;
2210     }
2211 
2212     decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2213 
2214     // Move to the next source region, possibly switching spaces as well.  All
2215     // args except end_addr may be modified.
2216     src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2217   } while (true);
2218 }
2219 
2220 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2221 {
2222   MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2223   fill_region(cm, cl, region_idx);
2224 }
2225 
2226 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2227 {
2228   // Get a shadow region first
2229   ParallelCompactData& sd = summary_data();
2230   RegionData* const region_ptr = sd.region(region_idx);
2231   size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2232   // The InvalidShadow return value indicates the corresponding heap region is available,
2233   // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2234   // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2235   if (shadow_region == ParCompactionManager::InvalidShadow) {
2236     MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2237     region_ptr->shadow_to_normal();
2238     return fill_region(cm, cl, region_idx);
2239   } else {
2240     MoveAndUpdateShadowClosure cl(mark_bitmap(), region_idx, shadow_region);
2241     return fill_region(cm, cl, region_idx);
2242   }
2243 }
2244 
2245 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2246 {
2247   Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2248 }
2249 
2250 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t &region_idx)
2251 {
2252   size_t next = cm->next_shadow_region();
2253   ParallelCompactData& sd = summary_data();
2254   size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2255   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2256 
2257   while (next < old_new_top) {
2258     if (sd.region(next)->mark_shadow()) {
2259       region_idx = next;
2260       return true;
2261     }
2262     next = cm->move_next_shadow_region_by(active_gc_threads);
2263   }
2264 
2265   return false;
2266 }
2267 
2268 // The shadow region is an optimization to address region dependencies in full GC. The basic
2269 // idea is making more regions available by temporally storing their live objects in empty
2270 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
2271 // GC threads need not wait destination regions to be available before processing sources.
2272 //
2273 // A typical workflow would be:
2274 // After draining its own stack and failing to steal from others, a GC worker would pick an
2275 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
2276 // the shadow region by copying live objects from source regions of the unavailable one. Once
2277 // the unavailable region becomes available, the data in the shadow region will be copied back.
2278 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
2279 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
2280 {
2281   const ParallelCompactData& sd = PSParallelCompact::summary_data();
2282 
2283   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2284     SpaceInfo* const space_info = _space_info + id;
2285     MutableSpace* const space = space_info->space();
2286 
2287     const size_t beg_region =
2288       sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
2289     const size_t end_region =
2290       sd.addr_to_region_idx(sd.region_align_down(space->end()));
2291 
2292     for (size_t cur = beg_region; cur < end_region; ++cur) {
2293       ParCompactionManager::push_shadow_region(cur);
2294     }
2295   }
2296 
2297   size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
2298   for (uint i = 0; i < parallel_gc_threads; i++) {
2299     ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
2300     cm->set_next_shadow_region(beg_region + i);
2301   }
2302 }
2303 
2304 void MoveAndUpdateClosure::copy_partial_obj(size_t partial_obj_size)
2305 {
2306   size_t words = MIN2(partial_obj_size, words_remaining());
2307 
2308   // This test is necessary; if omitted, the pointer updates to a partial object
2309   // that crosses the dense prefix boundary could be overwritten.
2310   if (source() != copy_destination()) {
2311     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2312     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2313   }
2314   update_state(words);
2315 }
2316 
2317 void MoveAndUpdateClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2318   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
2319   region_ptr->set_completed();
2320 }
2321 
2322 void MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
2323   assert(destination() != nullptr, "sanity");
2324   _source = addr;
2325 
2326   // The start_array must be updated even if the object is not moving.
2327   if (_start_array != nullptr) {
2328     _start_array->update_for_block(destination(), destination() + words);
2329   }
2330 
2331   // Avoid overflow
2332   words = MIN2(words, words_remaining());
2333   assert(words > 0, "inv");
2334 
2335   if (copy_destination() != source()) {
2336     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2337     assert(source() != destination(), "inv");
2338     assert(FullGCForwarding::is_forwarded(cast_to_oop(source())), "inv");
2339     assert(FullGCForwarding::forwardee(cast_to_oop(source())) == cast_to_oop(destination()), "inv");
2340     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2341     cast_to_oop(copy_destination())->init_mark();
2342   }
2343 
2344   update_state(words);
2345 }
2346 
2347 void MoveAndUpdateShadowClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2348   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
2349   // Record the shadow region index
2350   region_ptr->set_shadow_region(_shadow);
2351   // Mark the shadow region as filled to indicate the data is ready to be
2352   // copied back
2353   region_ptr->mark_filled();
2354   // Try to copy the content of the shadow region back to its corresponding
2355   // heap region if available; the GC thread that decreases the destination
2356   // count to zero will do the copying otherwise (see
2357   // PSParallelCompact::decrement_destination_counts).
2358   if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
2359     region_ptr->set_completed();
2360     PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
2361     ParCompactionManager::push_shadow_region_mt_safe(_shadow);
2362   }
2363 }