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