1 /*
   2  * Copyright (c) 2014, 2021, Red Hat, Inc. All rights reserved.
   3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 
  28 #include "compiler/oopMap.hpp"
  29 #include "gc/shared/continuationGCSupport.hpp"
  30 #include "gc/shared/fullGCForwarding.inline.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/preservedMarks.inline.hpp"
  33 #include "gc/shared/tlab_globals.hpp"
  34 #include "gc/shared/workerThread.hpp"
  35 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  36 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  37 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  38 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  39 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  40 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  41 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  42 #include "gc/shenandoah/shenandoahFullGC.hpp"
  43 #include "gc/shenandoah/shenandoahGenerationalFullGC.hpp"
  44 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
  45 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  46 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  47 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  48 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
  49 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  50 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  51 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  52 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  53 #include "gc/shenandoah/shenandoahMetrics.hpp"
  54 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  55 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  56 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  57 #include "gc/shenandoah/shenandoahUtils.hpp"
  58 #include "gc/shenandoah/shenandoahVerifier.hpp"
  59 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  60 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  61 #include "memory/metaspaceUtils.hpp"
  62 #include "memory/universe.hpp"
  63 #include "oops/compressedOops.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "runtime/orderAccess.hpp"
  66 #include "runtime/vmThread.hpp"
  67 #include "utilities/copy.hpp"
  68 #include "utilities/events.hpp"
  69 #include "utilities/growableArray.hpp"
  70 
  71 ShenandoahFullGC::ShenandoahFullGC() :
  72   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
  73   _preserved_marks(new PreservedMarksSet(true)) {}
  74 
  75 ShenandoahFullGC::~ShenandoahFullGC() {
  76   delete _preserved_marks;
  77 }
  78 
  79 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
  80   vmop_entry_full(cause);
  81   // Always success
  82   return true;
  83 }
  84 
  85 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
  86   ShenandoahHeap* const heap = ShenandoahHeap::heap();
  87   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
  88   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
  89 
  90   heap->try_inject_alloc_failure();
  91   VM_ShenandoahFullGC op(cause, this);
  92   VMThread::execute(&op);
  93 }
  94 
  95 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
  96   static const char* msg = "Pause Full";
  97   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
  98   EventMark em("%s", msg);
  99 
 100   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 101                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
 102                               "full gc");
 103 
 104   op_full(cause);
 105 }
 106 
 107 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
 108   ShenandoahMetricsSnapshot metrics;
 109   metrics.snap_before();
 110 
 111   // Perform full GC
 112   do_it(cause);
 113 
 114   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 115 
 116   if (heap->mode()->is_generational()) {
 117     ShenandoahGenerationalFullGC::handle_completion(heap);
 118   }
 119 
 120   metrics.snap_after();
 121 
 122   if (metrics.is_good_progress()) {
 123     heap->notify_gc_progress();
 124   } else {
 125     // Nothing to do. Tell the allocation path that we have failed to make
 126     // progress, and it can finally fail.
 127     heap->notify_gc_no_progress();
 128   }
 129 
 130   // Regardless if progress was made, we record that we completed a "successful" full GC.
 131   heap->global_generation()->heuristics()->record_success_full();
 132   heap->shenandoah_policy()->record_success_full();
 133 }
 134 
 135 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 136   ShenandoahHeap* heap = ShenandoahHeap::heap();
 137 
 138   if (heap->mode()->is_generational()) {
 139     ShenandoahGenerationalFullGC::prepare();
 140   }
 141 
 142   if (ShenandoahVerify) {
 143     heap->verifier()->verify_before_fullgc();
 144   }
 145 
 146   if (VerifyBeforeGC) {
 147     Universe::verify();
 148   }
 149 
 150   // Degenerated GC may carry concurrent root flags when upgrading to
 151   // full GC. We need to reset it before mutators resume.
 152   heap->set_concurrent_strong_root_in_progress(false);
 153   heap->set_concurrent_weak_root_in_progress(false);
 154 
 155   heap->set_full_gc_in_progress(true);
 156 
 157   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 158   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 159 
 160   {
 161     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);
 162     heap->pre_full_gc_dump(_gc_timer);
 163   }
 164 
 165   {
 166     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 167     // Full GC is supposed to recover from any GC state:
 168 
 169     // a0. Remember if we have forwarded objects
 170     bool has_forwarded_objects = heap->has_forwarded_objects();
 171 
 172     // a1. Cancel evacuation, if in progress
 173     if (heap->is_evacuation_in_progress()) {
 174       heap->set_evacuation_in_progress(false);
 175     }
 176     assert(!heap->is_evacuation_in_progress(), "sanity");
 177 
 178     // a2. Cancel update-refs, if in progress
 179     if (heap->is_update_refs_in_progress()) {
 180       heap->set_update_refs_in_progress(false);
 181     }
 182     assert(!heap->is_update_refs_in_progress(), "sanity");
 183 
 184     // b. Cancel all concurrent marks, if in progress
 185     if (heap->is_concurrent_mark_in_progress()) {
 186       heap->cancel_concurrent_mark();
 187     }
 188     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 189 
 190     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 191     if (has_forwarded_objects) {
 192       update_roots(true /*full_gc*/);
 193     }
 194 
 195     // d. Reset the bitmaps for new marking
 196     heap->global_generation()->reset_mark_bitmap();
 197     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 198     assert(!heap->global_generation()->is_mark_complete(), "sanity");
 199 
 200     // e. Abandon reference discovery and clear all discovered references.
 201     ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 202     rp->abandon_partial_discovery();
 203 
 204     // f. Sync pinned region status from the CP marks
 205     heap->sync_pinned_region_status();
 206 
 207     if (heap->mode()->is_generational()) {
 208       ShenandoahGenerationalFullGC::restore_top_before_promote(heap);
 209     }
 210 
 211     // The rest of prologue:
 212     _preserved_marks->init(heap->workers()->active_workers());
 213 
 214     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 215   }
 216 
 217   if (UseTLAB) {
 218     // Note: PLABs are also retired with GCLABs in generational mode.
 219     heap->gclabs_retire(ResizeTLAB);
 220     heap->tlabs_retire(ResizeTLAB);
 221   }
 222 
 223   OrderAccess::fence();
 224 
 225   phase1_mark_heap();
 226 
 227   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 228   // Coming out of Full GC, we would not have any forwarded objects.
 229   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 230   heap->set_has_forwarded_objects(false);
 231 
 232   heap->set_full_gc_move_in_progress(true);
 233 
 234   // Setup workers for the rest
 235   OrderAccess::fence();
 236 
 237   // Initialize worker slices
 238   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 239   for (uint i = 0; i < heap->max_workers(); i++) {
 240     worker_slices[i] = new ShenandoahHeapRegionSet();
 241   }
 242 
 243   {
 244     // The rest of code performs region moves, where region status is undefined
 245     // until all phases run together.
 246     ShenandoahHeapLocker lock(heap->lock());
 247 
 248     FullGCForwarding::begin();
 249 
 250     phase2_calculate_target_addresses(worker_slices);
 251 
 252     OrderAccess::fence();
 253 
 254     phase3_update_references();
 255 
 256     phase4_compact_objects(worker_slices);
 257 
 258     phase5_epilog();
 259 
 260     FullGCForwarding::end();
 261   }
 262 
 263   // Resize metaspace
 264   MetaspaceGC::compute_new_size();
 265 
 266   // Free worker slices
 267   for (uint i = 0; i < heap->max_workers(); i++) {
 268     delete worker_slices[i];
 269   }
 270   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 271 
 272   heap->set_full_gc_move_in_progress(false);
 273   heap->set_full_gc_in_progress(false);
 274 
 275   if (ShenandoahVerify) {
 276     heap->verifier()->verify_after_fullgc();
 277   }
 278 
 279   if (VerifyAfterGC) {
 280     Universe::verify();
 281   }
 282 
 283   {
 284     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 285     heap->post_full_gc_dump(_gc_timer);
 286   }
 287 }
 288 
 289 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 290 private:
 291   ShenandoahMarkingContext* const _ctx;
 292 
 293 public:
 294   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 295 
 296   void heap_region_do(ShenandoahHeapRegion *r) override {
 297     _ctx->capture_top_at_mark_start(r);
 298     r->clear_live_data();
 299   }
 300 
 301   bool is_thread_safe() override { return true; }
 302 };
 303 
 304 void ShenandoahFullGC::phase1_mark_heap() {
 305   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 306   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 307 
 308   ShenandoahHeap* heap = ShenandoahHeap::heap();
 309 
 310   ShenandoahPrepareForMarkClosure prepare_for_mark;
 311   ShenandoahExcludeRegionClosure<FREE> cl(&prepare_for_mark);
 312   heap->parallel_heap_region_iterate(&cl);
 313 
 314   heap->set_unload_classes(heap->global_generation()->heuristics()->can_unload_classes());
 315 
 316   ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 317   // enable ("weak") refs discovery
 318   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 319 
 320   ShenandoahSTWMark mark(heap->global_generation(), true /*full_gc*/);
 321   mark.mark();
 322   heap->parallel_cleaning(true /* full_gc */);
 323 
 324   if (ShenandoahHeap::heap()->mode()->is_generational()) {
 325     ShenandoahGenerationalFullGC::log_live_in_old(heap);
 326   }
 327 }
 328 
 329 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 330 private:
 331   PreservedMarks*          const _preserved_marks;
 332   ShenandoahHeap*          const _heap;
 333   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 334   int _empty_regions_pos;
 335   ShenandoahHeapRegion*          _to_region;
 336   ShenandoahHeapRegion*          _from_region;
 337   HeapWord* _compact_point;
 338 
 339 public:
 340   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 341                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 342                                               ShenandoahHeapRegion* to_region) :
 343     _preserved_marks(preserved_marks),
 344     _heap(ShenandoahHeap::heap()),
 345     _empty_regions(empty_regions),
 346     _empty_regions_pos(0),
 347     _to_region(to_region),
 348     _from_region(nullptr),
 349     _compact_point(to_region->bottom()) {}
 350 
 351   void set_from_region(ShenandoahHeapRegion* from_region) {
 352     _from_region = from_region;
 353   }
 354 
 355   void finish() {
 356     assert(_to_region != nullptr, "should not happen");
 357     _to_region->set_new_top(_compact_point);
 358   }
 359 
 360   bool is_compact_same_region() {
 361     return _from_region == _to_region;
 362   }
 363 
 364   int empty_regions_pos() {
 365     return _empty_regions_pos;
 366   }
 367 
 368   void do_object(oop p) {
 369     assert(_from_region != nullptr, "must set before work");
 370     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 371     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 372 
 373     size_t old_size = p->size();
 374     size_t new_size = p->copy_size(old_size, p->mark());
 375     size_t obj_size = _compact_point == cast_from_oop<HeapWord*>(p) ? old_size : new_size;
 376     if (_compact_point + obj_size > _to_region->end()) {
 377       finish();
 378 
 379       // Object doesn't fit. Pick next empty region and start compacting there.
 380       ShenandoahHeapRegion* new_to_region;
 381       if (_empty_regions_pos < _empty_regions.length()) {
 382         new_to_region = _empty_regions.at(_empty_regions_pos);
 383         _empty_regions_pos++;
 384       } else {
 385         // Out of empty region? Compact within the same region.
 386         new_to_region = _from_region;
 387       }
 388 
 389       assert(new_to_region != _to_region, "must not reuse same to-region");
 390       assert(new_to_region != nullptr, "must not be null");
 391       _to_region = new_to_region;
 392       _compact_point = _to_region->bottom();
 393       obj_size = _compact_point == cast_from_oop<HeapWord*>(p) ? old_size : new_size;
 394     }
 395 
 396     // Object fits into current region, record new location, if object does not move:
 397     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 398     shenandoah_assert_not_forwarded(nullptr, p);
 399     if (_compact_point != cast_from_oop<HeapWord*>(p)) {
 400       _preserved_marks->push_if_necessary(p, p->mark());
 401       FullGCForwarding::forward_to(p, cast_to_oop(_compact_point));
 402     }
 403     _compact_point += obj_size;
 404   }
 405 };
 406 
 407 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 408 private:
 409   PreservedMarksSet*        const _preserved_marks;
 410   ShenandoahHeap*           const _heap;
 411   ShenandoahHeapRegionSet** const _worker_slices;
 412 
 413 public:
 414   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :
 415     WorkerTask("Shenandoah Prepare For Compaction"),
 416     _preserved_marks(preserved_marks),
 417     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
 418   }
 419 
 420   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 421     // Empty region: get it into the slice to defragment the slice itself.
 422     // We could have skipped this without violating correctness, but we really
 423     // want to compact all live regions to the start of the heap, which sometimes
 424     // means moving them into the fully empty regions.
 425     if (r->is_empty()) return true;
 426 
 427     // Can move the region, and this is not the humongous region. Humongous
 428     // moves are special cased here, because their moves are handled separately.
 429     return r->is_stw_move_allowed() && !r->is_humongous();
 430   }
 431 
 432   void work(uint worker_id) override;
 433 private:
 434   template<typename ClosureType>
 435   void prepare_for_compaction(ClosureType& cl,
 436                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 437                               ShenandoahHeapRegionSetIterator& it,
 438                               ShenandoahHeapRegion* from_region);
 439 };
 440 
 441 void ShenandoahPrepareForCompactionTask::work(uint worker_id) {
 442   ShenandoahParallelWorkerSession worker_session(worker_id);
 443   ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 444   ShenandoahHeapRegionSetIterator it(slice);
 445   ShenandoahHeapRegion* from_region = it.next();
 446   // No work?
 447   if (from_region == nullptr) {
 448     return;
 449   }
 450 
 451   // Sliding compaction. Walk all regions in the slice, and compact them.
 452   // Remember empty regions and reuse them as needed.
 453   ResourceMark rm;
 454 
 455   GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 456 
 457   if (_heap->mode()->is_generational()) {
 458     ShenandoahPrepareForGenerationalCompactionObjectClosure cl(_preserved_marks->get(worker_id),
 459                                                                empty_regions, from_region, worker_id);
 460     prepare_for_compaction(cl, empty_regions, it, from_region);
 461   } else {
 462     ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);
 463     prepare_for_compaction(cl, empty_regions, it, from_region);
 464   }
 465 }
 466 
 467 template<typename ClosureType>
 468 void ShenandoahPrepareForCompactionTask::prepare_for_compaction(ClosureType& cl,
 469                                                                 GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 470                                                                 ShenandoahHeapRegionSetIterator& it,
 471                                                                 ShenandoahHeapRegion* from_region) {
 472   while (from_region != nullptr) {
 473     assert(is_candidate_region(from_region), "Sanity");
 474     cl.set_from_region(from_region);
 475     if (from_region->has_live()) {
 476       _heap->marked_object_iterate(from_region, &cl);
 477     }
 478 
 479     // Compacted the region to somewhere else? From-region is empty then.
 480     if (!cl.is_compact_same_region()) {
 481       empty_regions.append(from_region);
 482     }
 483     from_region = it.next();
 484   }
 485   cl.finish();
 486 
 487   // Mark all remaining regions as empty
 488   for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 489     ShenandoahHeapRegion* r = empty_regions.at(pos);
 490     r->set_new_top(r->bottom());
 491   }
 492 }
 493 
 494 void ShenandoahFullGC::calculate_target_humongous_objects() {
 495   ShenandoahHeap* heap = ShenandoahHeap::heap();
 496 
 497   // Compute the new addresses for humongous objects. We need to do this after addresses
 498   // for regular objects are calculated, and we know what regions in heap suffix are
 499   // available for humongous moves.
 500   //
 501   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 502   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 503   // humongous start there.
 504   //
 505   // The complication is potential non-movable regions during the scan. If such region is
 506   // detected, then sliding restarts towards that non-movable region.
 507 
 508   size_t to_begin = heap->num_regions();
 509   size_t to_end = heap->num_regions();
 510 
 511   log_debug(gc)("Full GC calculating target humongous objects from end " SIZE_FORMAT, to_end);
 512   for (size_t c = heap->num_regions(); c > 0; c--) {
 513     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 514     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 515       // To-region candidate: record this, and continue scan
 516       to_begin = r->index();
 517       continue;
 518     }
 519 
 520     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 521       // From-region candidate: movable humongous region
 522       oop old_obj = cast_to_oop(r->bottom());
 523       size_t words_size = old_obj->size();
 524       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 525 
 526       size_t start = to_end - num_regions;
 527 
 528       if (start >= to_begin && start != r->index()) {
 529         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 530         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 531         FullGCForwarding::forward_to(old_obj, cast_to_oop(heap->get_region(start)->bottom()));
 532         to_end = start;
 533         continue;
 534       }
 535     }
 536 
 537     // Failed to fit. Scan starting from current region.
 538     to_begin = r->index();
 539     to_end = r->index();
 540   }
 541 }
 542 
 543 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 544 private:
 545   ShenandoahHeap* const _heap;
 546 
 547 public:
 548   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 549   void heap_region_do(ShenandoahHeapRegion* r) {
 550     if (r->is_trash()) {
 551       r->recycle();
 552     }
 553     if (r->is_cset()) {
 554       // Leave affiliation unchanged
 555       r->make_regular_bypass();
 556     }
 557     if (r->is_empty_uncommitted()) {
 558       r->make_committed_bypass();
 559     }
 560     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());
 561 
 562     // Record current region occupancy: this communicates empty regions are free
 563     // to the rest of Full GC code.
 564     r->set_new_top(r->top());
 565   }
 566 };
 567 
 568 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 569 private:
 570   ShenandoahHeap* const _heap;
 571   ShenandoahMarkingContext* const _ctx;
 572 
 573 public:
 574   ShenandoahTrashImmediateGarbageClosure() :
 575     _heap(ShenandoahHeap::heap()),
 576     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 577 
 578   void heap_region_do(ShenandoahHeapRegion* r) override {
 579     if (r->is_humongous_start()) {
 580       oop humongous_obj = cast_to_oop(r->bottom());
 581       if (!_ctx->is_marked(humongous_obj)) {
 582         assert(!r->has_live(), "Region " SIZE_FORMAT " is not marked, should not have live", r->index());
 583         _heap->trash_humongous_region_at(r);
 584       } else {
 585         assert(r->has_live(), "Region " SIZE_FORMAT " should have live", r->index());
 586       }
 587     } else if (r->is_humongous_continuation()) {
 588       // If we hit continuation, the non-live humongous starts should have been trashed already
 589       assert(r->humongous_start_region()->has_live(), "Region " SIZE_FORMAT " should have live", r->index());
 590     } else if (r->is_regular()) {
 591       if (!r->has_live()) {
 592         r->make_trash_immediate();
 593       }
 594     }
 595   }
 596 };
 597 
 598 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 599   ShenandoahHeap* heap = ShenandoahHeap::heap();
 600 
 601   uint n_workers = heap->workers()->active_workers();
 602   size_t n_regions = heap->num_regions();
 603 
 604   // What we want to accomplish: have the dense prefix of data, while still balancing
 605   // out the parallel work.
 606   //
 607   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 608   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 609   // thread takes all regions in its prefix subset, and then it takes some regions from
 610   // the tail.
 611   //
 612   // Tail region selection becomes interesting.
 613   //
 614   // First, we want to distribute the regions fairly between the workers, and those regions
 615   // might have different amount of live data. So, until we sure no workers need live data,
 616   // we need to only take what the worker needs.
 617   //
 618   // Second, since we slide everything to the left in each slice, the most busy regions
 619   // would be the ones on the left. Which means we want to have all workers have their after-tail
 620   // regions as close to the left as possible.
 621   //
 622   // The easiest way to do this is to distribute after-tail regions in round-robin between
 623   // workers that still need live data.
 624   //
 625   // Consider parallel workers A, B, C, then the target slice layout would be:
 626   //
 627   //  AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA
 628   //
 629   //  (.....dense-prefix.....) (.....................tail...................)
 630   //  [all regions fully live] [left-most regions are fuller that right-most]
 631   //
 632 
 633   // Compute how much live data is there. This would approximate the size of dense prefix
 634   // we target to create.
 635   size_t total_live = 0;
 636   for (size_t idx = 0; idx < n_regions; idx++) {
 637     ShenandoahHeapRegion *r = heap->get_region(idx);
 638     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 639       total_live += r->get_live_data_words();
 640     }
 641   }
 642 
 643   // Estimate the size for the dense prefix. Note that we specifically count only the
 644   // "full" regions, so there would be some non-full regions in the slice tail.
 645   size_t live_per_worker = total_live / n_workers;
 646   size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();
 647   size_t prefix_regions_total = prefix_regions_per_worker * n_workers;
 648   prefix_regions_total = MIN2(prefix_regions_total, n_regions);
 649   assert(prefix_regions_total <= n_regions, "Sanity");
 650 
 651   // There might be non-candidate regions in the prefix. To compute where the tail actually
 652   // ends up being, we need to account those as well.
 653   size_t prefix_end = prefix_regions_total;
 654   for (size_t idx = 0; idx < prefix_regions_total; idx++) {
 655     ShenandoahHeapRegion *r = heap->get_region(idx);
 656     if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 657       prefix_end++;
 658     }
 659   }
 660   prefix_end = MIN2(prefix_end, n_regions);
 661   assert(prefix_end <= n_regions, "Sanity");
 662 
 663   // Distribute prefix regions per worker: each thread definitely gets its own same-sized
 664   // subset of dense prefix.
 665   size_t prefix_idx = 0;
 666 
 667   size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);
 668 
 669   for (size_t wid = 0; wid < n_workers; wid++) {
 670     ShenandoahHeapRegionSet* slice = worker_slices[wid];
 671 
 672     live[wid] = 0;
 673     size_t regs = 0;
 674 
 675     // Add all prefix regions for this worker
 676     while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {
 677       ShenandoahHeapRegion *r = heap->get_region(prefix_idx);
 678       if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 679         slice->add_region(r);
 680         live[wid] += r->get_live_data_words();
 681         regs++;
 682       }
 683       prefix_idx++;
 684     }
 685   }
 686 
 687   // Distribute the tail among workers in round-robin fashion.
 688   size_t wid = n_workers - 1;
 689 
 690   for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {
 691     ShenandoahHeapRegion *r = heap->get_region(tail_idx);
 692     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 693       assert(wid < n_workers, "Sanity");
 694 
 695       size_t live_region = r->get_live_data_words();
 696 
 697       // Select next worker that still needs live data.
 698       size_t old_wid = wid;
 699       do {
 700         wid++;
 701         if (wid == n_workers) wid = 0;
 702       } while (live[wid] + live_region >= live_per_worker && old_wid != wid);
 703 
 704       if (old_wid == wid) {
 705         // Circled back to the same worker? This means liveness data was
 706         // miscalculated. Bump the live_per_worker limit so that
 707         // everyone gets a piece of the leftover work.
 708         live_per_worker += ShenandoahHeapRegion::region_size_words();
 709       }
 710 
 711       worker_slices[wid]->add_region(r);
 712       live[wid] += live_region;
 713     }
 714   }
 715 
 716   FREE_C_HEAP_ARRAY(size_t, live);
 717 
 718 #ifdef ASSERT
 719   ResourceBitMap map(n_regions);
 720   for (size_t wid = 0; wid < n_workers; wid++) {
 721     ShenandoahHeapRegionSetIterator it(worker_slices[wid]);
 722     ShenandoahHeapRegion* r = it.next();
 723     while (r != nullptr) {
 724       size_t idx = r->index();
 725       assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: " SIZE_FORMAT, idx);
 726       assert(!map.at(idx), "No region distributed twice: " SIZE_FORMAT, idx);
 727       map.at_put(idx, true);
 728       r = it.next();
 729     }
 730   }
 731 
 732   for (size_t rid = 0; rid < n_regions; rid++) {
 733     bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));
 734     bool is_distributed = map.at(rid);
 735     assert(is_distributed || !is_candidate, "All candidates are distributed: " SIZE_FORMAT, rid);
 736   }
 737 #endif
 738 }
 739 
 740 void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 741   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 742   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 743 
 744   ShenandoahHeap* heap = ShenandoahHeap::heap();
 745 
 746   // About to figure out which regions can be compacted, make sure pinning status
 747   // had been updated in GC prologue.
 748   heap->assert_pinned_region_status();
 749 
 750   {
 751     // Trash the immediately collectible regions before computing addresses
 752     ShenandoahTrashImmediateGarbageClosure trash_immediate_garbage;
 753     ShenandoahExcludeRegionClosure<FREE> cl(&trash_immediate_garbage);
 754     heap->heap_region_iterate(&cl);
 755 
 756     // Make sure regions are in good state: committed, active, clean.
 757     // This is needed because we are potentially sliding the data through them.
 758     ShenandoahEnsureHeapActiveClosure ecl;
 759     heap->heap_region_iterate(&ecl);
 760   }
 761 
 762   // Compute the new addresses for regular objects
 763   {
 764     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 765 
 766     distribute_slices(worker_slices);
 767 
 768     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);
 769     heap->workers()->run_task(&task);
 770   }
 771 
 772   // Compute the new addresses for humongous objects
 773   {
 774     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 775     calculate_target_humongous_objects();
 776   }
 777 }
 778 
 779 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
 780 private:
 781   ShenandoahHeap* const _heap;
 782   ShenandoahMarkingContext* const _ctx;
 783 
 784   template <class T>
 785   inline void do_oop_work(T* p) {
 786     T o = RawAccess<>::oop_load(p);
 787     if (!CompressedOops::is_null(o)) {
 788       oop obj = CompressedOops::decode_not_null(o);
 789       assert(_ctx->is_marked(obj), "must be marked");
 790       if (FullGCForwarding::is_forwarded(obj)) {
 791         oop forw = FullGCForwarding::forwardee(obj);
 792         RawAccess<IS_NOT_NULL>::oop_store(p, forw);
 793       }
 794     }
 795   }
 796 
 797 public:
 798   ShenandoahAdjustPointersClosure() :
 799     _heap(ShenandoahHeap::heap()),
 800     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 801 
 802   void do_oop(oop* p)       { do_oop_work(p); }
 803   void do_oop(narrowOop* p) { do_oop_work(p); }
 804   void do_method(Method* m) {}
 805   void do_nmethod(nmethod* nm) {}
 806 };
 807 
 808 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 809 private:
 810   ShenandoahHeap* const _heap;
 811   ShenandoahAdjustPointersClosure _cl;
 812 
 813 public:
 814   ShenandoahAdjustPointersObjectClosure() :
 815     _heap(ShenandoahHeap::heap()) {
 816   }
 817   void do_object(oop p) {
 818     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 819     p->oop_iterate(&_cl);
 820   }
 821 };
 822 
 823 class ShenandoahAdjustPointersTask : public WorkerTask {
 824 private:
 825   ShenandoahHeap*          const _heap;
 826   ShenandoahRegionIterator       _regions;
 827 
 828 public:
 829   ShenandoahAdjustPointersTask() :
 830     WorkerTask("Shenandoah Adjust Pointers"),
 831     _heap(ShenandoahHeap::heap()) {
 832   }
 833 
 834   void work(uint worker_id) {
 835     ShenandoahParallelWorkerSession worker_session(worker_id);
 836     ShenandoahAdjustPointersObjectClosure obj_cl;
 837     ShenandoahHeapRegion* r = _regions.next();
 838     while (r != nullptr) {
 839       if (!r->is_humongous_continuation() && r->has_live()) {
 840         _heap->marked_object_iterate(r, &obj_cl);
 841       }
 842       if (_heap->mode()->is_generational()) {
 843         ShenandoahGenerationalFullGC::maybe_coalesce_and_fill_region(r);
 844       }
 845       r = _regions.next();
 846     }
 847   }
 848 };
 849 
 850 class ShenandoahAdjustRootPointersTask : public WorkerTask {
 851 private:
 852   ShenandoahRootAdjuster* _rp;
 853   PreservedMarksSet* _preserved_marks;
 854 public:
 855   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
 856     WorkerTask("Shenandoah Adjust Root Pointers"),
 857     _rp(rp),
 858     _preserved_marks(preserved_marks) {}
 859 
 860   void work(uint worker_id) {
 861     ShenandoahParallelWorkerSession worker_session(worker_id);
 862     ShenandoahAdjustPointersClosure cl;
 863     _rp->roots_do(worker_id, &cl);
 864     _preserved_marks->get(worker_id)->adjust_during_full_gc();
 865   }
 866 };
 867 
 868 void ShenandoahFullGC::phase3_update_references() {
 869   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 870   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 871 
 872   ShenandoahHeap* heap = ShenandoahHeap::heap();
 873 
 874   WorkerThreads* workers = heap->workers();
 875   uint nworkers = workers->active_workers();
 876   {
 877 #if COMPILER2_OR_JVMCI
 878     DerivedPointerTable::clear();
 879 #endif
 880     ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);
 881     ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);
 882     workers->run_task(&task);
 883 #if COMPILER2_OR_JVMCI
 884     DerivedPointerTable::update_pointers();
 885 #endif
 886   }
 887 
 888   ShenandoahAdjustPointersTask adjust_pointers_task;
 889   workers->run_task(&adjust_pointers_task);
 890 }
 891 
 892 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 893 private:
 894   ShenandoahHeap* const _heap;
 895   uint            const _worker_id;
 896 
 897 public:
 898   ShenandoahCompactObjectsClosure(uint worker_id) :
 899     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
 900 
 901   void do_object(oop p) {
 902     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 903     size_t size = p->size();
 904     if (FullGCForwarding::is_forwarded(p)) {
 905       HeapWord* compact_from = cast_from_oop<HeapWord*>(p);
 906       HeapWord* compact_to = cast_from_oop<HeapWord*>(FullGCForwarding::forwardee(p));
 907       assert(compact_from != compact_to, "Forwarded object should move");
 908       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 909       oop new_obj = cast_to_oop(compact_to);
 910 
 911       ContinuationGCSupport::relativize_stack_chunk(new_obj);
 912       new_obj->init_mark();
 913       new_obj->initialize_hash_if_necessary(p);
 914     }
 915   }
 916 };
 917 
 918 class ShenandoahCompactObjectsTask : public WorkerTask {
 919 private:
 920   ShenandoahHeap* const _heap;
 921   ShenandoahHeapRegionSet** const _worker_slices;
 922 
 923 public:
 924   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 925     WorkerTask("Shenandoah Compact Objects"),
 926     _heap(ShenandoahHeap::heap()),
 927     _worker_slices(worker_slices) {
 928   }
 929 
 930   void work(uint worker_id) {
 931     ShenandoahParallelWorkerSession worker_session(worker_id);
 932     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
 933 
 934     ShenandoahCompactObjectsClosure cl(worker_id);
 935     ShenandoahHeapRegion* r = slice.next();
 936     while (r != nullptr) {
 937       assert(!r->is_humongous(), "must not get humongous regions here");
 938       if (r->has_live()) {
 939         _heap->marked_object_iterate(r, &cl);
 940       }
 941       r->set_top(r->new_top());
 942       r = slice.next();
 943     }
 944   }
 945 };
 946 
 947 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 948 private:
 949   ShenandoahHeap* const _heap;
 950   bool _is_generational;
 951   size_t _young_regions, _young_usage, _young_humongous_waste;
 952   size_t _old_regions, _old_usage, _old_humongous_waste;
 953 
 954 public:
 955   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()),
 956                                    _is_generational(_heap->mode()->is_generational()),
 957                                    _young_regions(0),
 958                                    _young_usage(0),
 959                                    _young_humongous_waste(0),
 960                                    _old_regions(0),
 961                                    _old_usage(0),
 962                                    _old_humongous_waste(0)
 963   {
 964     _heap->free_set()->clear();
 965   }
 966 
 967   void heap_region_do(ShenandoahHeapRegion* r) {
 968     assert (!r->is_cset(), "cset regions should have been demoted already");
 969 
 970     // Need to reset the complete-top-at-mark-start pointer here because
 971     // the complete marking bitmap is no longer valid. This ensures
 972     // size-based iteration in marked_object_iterate().
 973     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 974     // pinned regions.
 975     if (!r->is_pinned()) {
 976       _heap->complete_marking_context()->reset_top_at_mark_start(r);
 977     }
 978 
 979     size_t live = r->used();
 980 
 981     // Make empty regions that have been allocated into regular
 982     if (r->is_empty() && live > 0) {
 983       if (!_is_generational) {
 984         r->make_affiliated_maybe();
 985       }
 986       // else, generational mode compaction has already established affiliation.
 987       r->make_regular_bypass();
 988       if (ZapUnusedHeapArea) {
 989         SpaceMangler::mangle_region(MemRegion(r->top(), r->end()));
 990       }
 991     }
 992 
 993     // Reclaim regular regions that became empty
 994     if (r->is_regular() && live == 0) {
 995       r->make_trash();
 996     }
 997 
 998     // Recycle all trash regions
 999     if (r->is_trash()) {
1000       live = 0;
1001       r->recycle();
1002     } else {
1003       if (r->is_old()) {
1004         ShenandoahGenerationalFullGC::account_for_region(r, _old_regions, _old_usage, _old_humongous_waste);
1005       } else if (r->is_young()) {
1006         ShenandoahGenerationalFullGC::account_for_region(r, _young_regions, _young_usage, _young_humongous_waste);
1007       }
1008     }
1009     r->set_live_data(live);
1010     r->reset_alloc_metadata();
1011   }
1012 
1013   void update_generation_usage() {
1014     if (_is_generational) {
1015       _heap->old_generation()->establish_usage(_old_regions, _old_usage, _old_humongous_waste);
1016       _heap->young_generation()->establish_usage(_young_regions, _young_usage, _young_humongous_waste);
1017     } else {
1018       assert(_old_regions == 0, "Old regions only expected in generational mode");
1019       assert(_old_usage == 0, "Old usage only expected in generational mode");
1020       assert(_old_humongous_waste == 0, "Old humongous waste only expected in generational mode");
1021     }
1022 
1023     // In generational mode, global usage should be the sum of young and old. This is also true
1024     // for non-generational modes except that there are no old regions.
1025     _heap->global_generation()->establish_usage(_old_regions + _young_regions,
1026                                                 _old_usage + _young_usage,
1027                                                 _old_humongous_waste + _young_humongous_waste);
1028   }
1029 };
1030 
1031 void ShenandoahFullGC::compact_humongous_objects() {
1032   // Compact humongous regions, based on their fwdptr objects.
1033   //
1034   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
1035   // humongous regions are already compacted, and do not require further moves, which alleviates
1036   // sliding costs. We may consider doing this in parallel in the future.
1037 
1038   ShenandoahHeap* heap = ShenandoahHeap::heap();
1039 
1040   for (size_t c = heap->num_regions(); c > 0; c--) {
1041     ShenandoahHeapRegion* r = heap->get_region(c - 1);
1042     if (r->is_humongous_start()) {
1043       oop old_obj = cast_to_oop(r->bottom());
1044       if (!FullGCForwarding::is_forwarded(old_obj)) {
1045         // No need to move the object, it stays at the same slot
1046         continue;
1047       }
1048       size_t words_size = old_obj->size();
1049       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1050 
1051       size_t old_start = r->index();
1052       size_t old_end   = old_start + num_regions - 1;
1053       size_t new_start = heap->heap_region_index_containing(FullGCForwarding::forwardee(old_obj));
1054       size_t new_end   = new_start + num_regions - 1;
1055       assert(old_start != new_start, "must be real move");
1056       assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());
1057 
1058       log_debug(gc)("Full GC compaction moves humongous object from region " SIZE_FORMAT " to region " SIZE_FORMAT, old_start, new_start);
1059       Copy::aligned_conjoint_words(r->bottom(), heap->get_region(new_start)->bottom(), words_size);
1060       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(r->bottom()));
1061 
1062       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1063       new_obj->init_mark();
1064 
1065       {
1066         ShenandoahAffiliation original_affiliation = r->affiliation();
1067         for (size_t c = old_start; c <= old_end; c++) {
1068           ShenandoahHeapRegion* r = heap->get_region(c);
1069           // Leave humongous region affiliation unchanged.
1070           r->make_regular_bypass();
1071           r->set_top(r->bottom());
1072         }
1073 
1074         for (size_t c = new_start; c <= new_end; c++) {
1075           ShenandoahHeapRegion* r = heap->get_region(c);
1076           if (c == new_start) {
1077             r->make_humongous_start_bypass(original_affiliation);
1078           } else {
1079             r->make_humongous_cont_bypass(original_affiliation);
1080           }
1081 
1082           // Trailing region may be non-full, record the remainder there
1083           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1084           if ((c == new_end) && (remainder != 0)) {
1085             r->set_top(r->bottom() + remainder);
1086           } else {
1087             r->set_top(r->end());
1088           }
1089 
1090           r->reset_alloc_metadata();
1091         }
1092       }
1093     }
1094   }
1095 }
1096 
1097 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1098 // we need to remain able to walk pinned regions.
1099 // Since pinned region do not move and don't get compacted, we will get holes with
1100 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
1101 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
1102 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
1103 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
1104 class ShenandoahMCResetCompleteBitmapTask : public WorkerTask {
1105 private:
1106   ShenandoahRegionIterator _regions;
1107 
1108 public:
1109   ShenandoahMCResetCompleteBitmapTask() :
1110     WorkerTask("Shenandoah Reset Bitmap") {
1111   }
1112 
1113   void work(uint worker_id) {
1114     ShenandoahParallelWorkerSession worker_session(worker_id);
1115     ShenandoahHeapRegion* region = _regions.next();
1116     ShenandoahHeap* heap = ShenandoahHeap::heap();
1117     ShenandoahMarkingContext* const ctx = heap->complete_marking_context();
1118     while (region != nullptr) {
1119       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
1120         ctx->clear_bitmap(region);
1121       }
1122       region = _regions.next();
1123     }
1124   }
1125 };
1126 
1127 void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
1128   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
1129   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
1130 
1131   ShenandoahHeap* heap = ShenandoahHeap::heap();
1132 
1133   // Compact regular objects first
1134   {
1135     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
1136     ShenandoahCompactObjectsTask compact_task(worker_slices);
1137     heap->workers()->run_task(&compact_task);
1138   }
1139 
1140   // Compact humongous objects after regular object moves
1141   {
1142     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1143     compact_humongous_objects();
1144   }
1145 }
1146 
1147 void ShenandoahFullGC::phase5_epilog() {
1148   GCTraceTime(Info, gc, phases) time("Phase 5: Full GC epilog", _gc_timer);
1149   ShenandoahHeap* heap = ShenandoahHeap::heap();
1150 
1151   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1152   // and must ensure the bitmap is in sync.
1153   {
1154     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1155     ShenandoahMCResetCompleteBitmapTask task;
1156     heap->workers()->run_task(&task);
1157   }
1158 
1159   // Bring regions in proper states after the collection, and set heap properties.
1160   {
1161     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1162     ShenandoahPostCompactClosure post_compact;
1163     heap->heap_region_iterate(&post_compact);
1164     post_compact.update_generation_usage();
1165 
1166     if (heap->mode()->is_generational()) {
1167       ShenandoahGenerationalFullGC::balance_generations_after_gc(heap);
1168     }
1169 
1170     heap->collection_set()->clear();
1171     size_t young_cset_regions, old_cset_regions;
1172     size_t first_old, last_old, num_old;
1173     heap->free_set()->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old, last_old, num_old);
1174 
1175     // We also do not expand old generation size following Full GC because we have scrambled age populations and
1176     // no longer have objects separated by age into distinct regions.
1177     if (heap->mode()->is_generational()) {
1178       ShenandoahGenerationalFullGC::compute_balances();
1179     }
1180 
1181     heap->free_set()->finish_rebuild(young_cset_regions, old_cset_regions, num_old);
1182 
1183     heap->clear_cancelled_gc(true /* clear oom handler */);
1184   }
1185 
1186   _preserved_marks->restore(heap->workers());
1187   _preserved_marks->reclaim();
1188 
1189   // We defer generation resizing actions until after cset regions have been recycled.  We do this even following an
1190   // abbreviated cycle.
1191   if (heap->mode()->is_generational()) {
1192     ShenandoahGenerationalFullGC::balance_generations_after_rebuilding_free_set();
1193     ShenandoahGenerationalFullGC::rebuild_remembered_set(heap);
1194   }
1195 }