1 /*
   2  * Copyright (c) 2014, 2017, Red Hat, Inc. and/or its affiliates.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "gc/shared/gcTraceTime.inline.hpp"
  29 #include "gc/shenandoah/brooksPointer.hpp"
  30 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  31 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  32 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  33 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  34 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  35 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  36 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  37 #include "gc/shenandoah/shenandoahHeap.hpp"
  38 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  39 #include "gc/shenandoah/shenandoahPartialGC.hpp"
  40 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  41 #include "gc/shenandoah/shenandoahTraversalGC.hpp"
  42 #include "gc/shenandoah/shenandoahUtils.hpp"
  43 #include "gc/shenandoah/shenandoahVerifier.hpp"
  44 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  45 #include "gc/shenandoah/vm_operations_shenandoah.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "runtime/biasedLocking.hpp"
  48 #include "runtime/thread.hpp"
  49 #include "utilities/copy.hpp"
  50 #include "utilities/growableArray.hpp"
  51 #include "gc/shared/taskqueue.inline.hpp"
  52 #include "gc/shared/workgroup.hpp"
  53 
  54 class ShenandoahClearRegionStatusClosure: public ShenandoahHeapRegionClosure {
  55 private:
  56   ShenandoahHeap* const _heap;
  57 
  58 public:
  59   ShenandoahClearRegionStatusClosure() : _heap(ShenandoahHeap::heap()) {}
  60 
  61   bool heap_region_do(ShenandoahHeapRegion *r) {
  62     _heap->set_next_top_at_mark_start(r->bottom(), r->top());
  63     r->clear_live_data();
  64     r->set_concurrent_iteration_safe_limit(r->top());
  65     return false;
  66   }
  67 };
  68 
  69 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
  70 private:
  71   ShenandoahHeap* const _heap;
  72 
  73 public:
  74   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
  75   bool heap_region_do(ShenandoahHeapRegion* r) {
  76     if (r->is_trash()) {
  77       r->recycle();
  78     }
  79     if (r->is_cset()) {
  80       r->make_regular_bypass();
  81     }
  82     if (r->is_empty_uncommitted()) {
  83       r->make_committed_bypass();
  84     }
  85     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->region_number());
  86 
  87     // Record current region occupancy: this communicates empty regions are free
  88     // to the rest of Full GC code.
  89     r->set_new_top(r->top());
  90     return false;
  91   }
  92 };
  93 
  94 void ShenandoahMarkCompact::initialize(GCTimer* gc_timer) {
  95   _gc_timer = gc_timer;
  96 }
  97 
  98 void ShenandoahMarkCompact::do_it(GCCause::Cause gc_cause) {
  99   ShenandoahHeap* heap = ShenandoahHeap::heap();
 100 
 101   {
 102     if (ShenandoahVerify) {
 103       heap->verifier()->verify_before_fullgc();
 104     }
 105 
 106     heap->set_full_gc_in_progress(true);
 107 
 108     assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 109     assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 110 
 111     {
 112       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
 113       heap->pre_full_gc_dump(_gc_timer);
 114     }
 115 
 116     {
 117       ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 118       // Full GC is supposed to recover from any GC state:
 119 
 120       // a1. Cancel evacuation, if in progress
 121       if (heap->is_evacuation_in_progress()) {
 122         heap->set_evacuation_in_progress(false);
 123       }
 124       assert(!heap->is_evacuation_in_progress(), "sanity");
 125 
 126       // a2. Cancel update-refs, if in progress
 127       if (heap->is_update_refs_in_progress()) {
 128         heap->set_update_refs_in_progress(false);
 129       }
 130       assert(!heap->is_update_refs_in_progress(), "sanity");
 131 
 132       // a3. Cancel concurrent partial GC, if in progress
 133       if (heap->is_concurrent_partial_in_progress()) {
 134         heap->partial_gc()->reset();
 135         heap->set_concurrent_partial_in_progress(false);
 136       }
 137 
 138       // a3. Cancel concurrent traversal GC, if in progress
 139       if (heap->is_concurrent_traversal_in_progress()) {
 140         heap->traversal_gc()->reset();
 141         heap->set_concurrent_traversal_in_progress(false);
 142       }
 143 
 144       // b. Cancel concurrent mark, if in progress
 145       if (heap->is_concurrent_mark_in_progress()) {
 146         heap->concurrentMark()->cancel();
 147         heap->stop_concurrent_marking();
 148       }
 149       assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 150 
 151       // c. Reset the bitmaps for new marking
 152       heap->reset_next_mark_bitmap();
 153       assert(heap->is_next_bitmap_clear(), "sanity");
 154 
 155       // d. Abandon reference discovery and clear all discovered references.
 156       ReferenceProcessor* rp = heap->ref_processor();
 157       rp->disable_discovery();
 158       rp->abandon_partial_discovery();
 159       rp->verify_no_references_recorded();
 160 
 161       {
 162         ShenandoahHeapLocker lock(heap->lock());
 163 
 164         // f. Make sure all regions are active. This is needed because we are potentially
 165         // sliding the data through them
 166         ShenandoahEnsureHeapActiveClosure ecl;
 167         heap->heap_region_iterate(&ecl, false, false);
 168 
 169         // g. Clear region statuses, including collection set status
 170         ShenandoahClearRegionStatusClosure cl;
 171         heap->heap_region_iterate(&cl, false, false);
 172       }
 173     }
 174 
 175     {
 176       if (UseTLAB) {
 177         heap->make_tlabs_parsable(true);
 178       }
 179 
 180       CodeCache::gc_prologue();
 181 
 182       // TODO: We don't necessarily need to update refs. We might want to clean
 183       // up managing has_forwarded_objects when diving into degen/full-gc.
 184       heap->set_has_forwarded_objects(true);
 185 
 186       OrderAccess::fence();
 187 
 188       phase1_mark_heap();
 189 
 190       // Prevent read-barrier from kicking in while adjusting pointers in phase3.
 191       heap->set_has_forwarded_objects(false);
 192 
 193       heap->set_full_gc_move_in_progress(true);
 194 
 195       // Setup workers for the rest
 196       {
 197         OrderAccess::fence();
 198 
 199         // Initialize worker slices
 200         ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 201         for (uint i = 0; i < heap->max_workers(); i++) {
 202           worker_slices[i] = new ShenandoahHeapRegionSet();
 203         }
 204 
 205         phase2_calculate_target_addresses(worker_slices);
 206 
 207         OrderAccess::fence();
 208 
 209         phase3_update_references();
 210 
 211         phase4_compact_objects(worker_slices);
 212 
 213         // Free worker slices
 214         for (uint i = 0; i < heap->max_workers(); i++) {
 215           delete worker_slices[i];
 216         }
 217         FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 218 
 219         CodeCache::gc_epilogue();
 220         JvmtiExport::gc_epilogue();
 221       }
 222 
 223       heap->set_full_gc_move_in_progress(false);
 224       heap->set_full_gc_in_progress(false);
 225 
 226       if (ShenandoahVerify) {
 227         heap->verifier()->verify_after_fullgc();
 228       }
 229     }
 230 
 231     {
 232       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
 233       heap->post_full_gc_dump(_gc_timer);
 234     }
 235 
 236     if (UseTLAB) {
 237       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
 238       heap->resize_all_tlabs();
 239     }
 240   }
 241 
 242 
 243   if (UseShenandoahMatrix && PrintShenandoahMatrix) {
 244     LogTarget(Info, gc) lt;
 245     LogStream ls(lt);
 246     heap->connection_matrix()->print_on(&ls);
 247   }
 248 }
 249 
 250 void ShenandoahMarkCompact::phase1_mark_heap() {
 251   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 252   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 253 
 254   ShenandoahHeap* heap = ShenandoahHeap::heap();
 255 
 256   ShenandoahConcurrentMark* cm = heap->concurrentMark();
 257 
 258   // Do not trust heuristics, because this can be our last resort collection.
 259   // Only ignore processing references and class unloading if explicitly disabled.
 260   heap->set_process_references(ShenandoahRefProcFrequency != 0);
 261   heap->set_unload_classes(ShenandoahUnloadClassesFrequency != 0);
 262 
 263   ReferenceProcessor* rp = heap->ref_processor();
 264   // enable ("weak") refs discovery
 265   rp->enable_discovery(true /*verify_no_refs*/);
 266   rp->setup_policy(true); // snapshot the soft ref policy to be used in this cycle
 267   rp->set_active_mt_degree(heap->workers()->active_workers());
 268 
 269   cm->update_roots(ShenandoahPhaseTimings::full_gc_roots);
 270   cm->mark_roots(ShenandoahPhaseTimings::full_gc_roots);
 271   cm->shared_finish_mark_from_roots(/* full_gc = */ true);
 272 
 273   heap->swap_mark_bitmaps();
 274 
 275   if (UseShenandoahMatrix && PrintShenandoahMatrix) {
 276     LogTarget(Info, gc) lt;
 277     LogStream ls(lt);
 278     heap->connection_matrix()->print_on(&ls);
 279   }
 280 }
 281 
 282 class ShenandoahMCReclaimHumongousRegionClosure : public ShenandoahHeapRegionClosure {
 283 private:
 284   ShenandoahHeap* const _heap;
 285 public:
 286   ShenandoahMCReclaimHumongousRegionClosure() : _heap(ShenandoahHeap::heap()) {}
 287 
 288   bool heap_region_do(ShenandoahHeapRegion* r) {
 289     if (r->is_humongous_start()) {
 290       oop humongous_obj = oop(r->bottom() + BrooksPointer::word_size());
 291       if (!_heap->is_marked_complete(humongous_obj)) {
 292         _heap->trash_humongous_region_at(r);
 293       }
 294     }
 295     return false;
 296   }
 297 };
 298 
 299 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 300 private:
 301   ShenandoahHeap*          const _heap;
 302   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 303   int _empty_regions_pos;
 304   ShenandoahHeapRegion*          _to_region;
 305   ShenandoahHeapRegion*          _from_region;
 306   HeapWord* _compact_point;
 307 
 308 public:
 309   ShenandoahPrepareForCompactionObjectClosure(GrowableArray<ShenandoahHeapRegion*>& empty_regions, ShenandoahHeapRegion* to_region) :
 310     _heap(ShenandoahHeap::heap()),
 311     _empty_regions(empty_regions),
 312     _empty_regions_pos(0),
 313     _to_region(to_region),
 314     _from_region(NULL),
 315     _compact_point(to_region->bottom()) {}
 316 
 317   void set_from_region(ShenandoahHeapRegion* from_region) {
 318     _from_region = from_region;
 319   }
 320 
 321   void finish_region() {
 322     assert(_to_region != NULL, "should not happen");
 323     _to_region->set_new_top(_compact_point);
 324   }
 325 
 326   bool is_compact_same_region() {
 327     return _from_region == _to_region;
 328   }
 329 
 330   int empty_regions_pos() {
 331     return _empty_regions_pos;
 332   }
 333 
 334   void do_object(oop p) {
 335     assert(_from_region != NULL, "must set before work");
 336     assert(_heap->is_marked_complete(p), "must be marked");
 337     assert(!_heap->allocated_after_complete_mark_start((HeapWord*) p), "must be truly marked");
 338 
 339     size_t obj_size = p->size() + BrooksPointer::word_size();
 340     if (_compact_point + obj_size > _to_region->end()) {
 341       finish_region();
 342 
 343       // Object doesn't fit. Pick next empty region and start compacting there.
 344       ShenandoahHeapRegion* new_to_region;
 345       if (_empty_regions_pos < _empty_regions.length()) {
 346         new_to_region = _empty_regions.at(_empty_regions_pos);
 347         _empty_regions_pos++;
 348       } else {
 349         // Out of empty region? Compact within the same region.
 350         new_to_region = _from_region;
 351       }
 352 
 353       assert(new_to_region != _to_region, "must not reuse same to-region");
 354       assert(new_to_region != NULL, "must not be NULL");
 355       _to_region = new_to_region;
 356       _compact_point = _to_region->bottom();
 357     }
 358 
 359     // Object fits into current region, record new location:
 360     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 361     shenandoah_assert_not_forwarded(NULL, p);
 362     BrooksPointer::set_raw(p, _compact_point + BrooksPointer::word_size());
 363     _compact_point += obj_size;
 364   }
 365 };
 366 
 367 class ShenandoahPrepareForCompactionTask : public AbstractGangTask {
 368 private:
 369   ShenandoahHeap*           const _heap;
 370   ShenandoahHeapRegionSet** const _worker_slices;
 371   ShenandoahRegionIterator        _heap_regions;
 372 
 373   ShenandoahHeapRegion* next_from_region(ShenandoahHeapRegionSet* slice) {
 374     ShenandoahHeapRegion* from_region = _heap_regions.next();
 375 
 376     while (from_region != NULL && (!from_region->is_move_allowed() || from_region->is_humongous())) {
 377       from_region = _heap_regions.next();
 378     }
 379 
 380     if (from_region != NULL) {
 381       assert(slice != NULL, "sanity");
 382       assert(!from_region->is_humongous(), "this path cannot handle humongous regions");
 383       assert(from_region->is_move_allowed(), "only regions that can be moved in mark-compact");
 384       slice->add_region(from_region);
 385     }
 386 
 387     return from_region;
 388   }
 389 
 390 public:
 391   ShenandoahPrepareForCompactionTask(ShenandoahHeapRegionSet** worker_slices) :
 392     AbstractGangTask("Shenandoah Prepare For Compaction Task"),
 393     _heap(ShenandoahHeap::heap()), _heap_regions(_heap->region_iterator()), _worker_slices(worker_slices) {
 394   }
 395 
 396   void work(uint worker_id) {
 397     ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 398     ShenandoahHeapRegion* from_region = next_from_region(slice);
 399     // No work?
 400     if (from_region == NULL) {
 401       return;
 402     }
 403 
 404     // Sliding compaction. Walk all regions in the slice, and compact them.
 405     // Remember empty regions and reuse them as needed.
 406     ResourceMark rm;
 407     GrowableArray<ShenandoahHeapRegion*> empty_regions(_heap->num_regions());
 408     ShenandoahPrepareForCompactionObjectClosure cl(empty_regions, from_region);
 409     while (from_region != NULL) {
 410       cl.set_from_region(from_region);
 411       _heap->marked_object_iterate(from_region, &cl);
 412 
 413       // Compacted the region to somewhere else? From-region is empty then.
 414       if (!cl.is_compact_same_region()) {
 415         empty_regions.append(from_region);
 416       }
 417       from_region = next_from_region(slice);
 418     }
 419     cl.finish_region();
 420 
 421     // Mark all remaining regions as empty
 422     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 423       ShenandoahHeapRegion* r = empty_regions.at(pos);
 424       r->set_new_top(r->bottom());
 425     }
 426   }
 427 };
 428 
 429 void ShenandoahMarkCompact::calculate_target_humongous_objects() {
 430   ShenandoahHeap* heap = ShenandoahHeap::heap();
 431 
 432   // Compute the new addresses for humongous objects. We need to do this after addresses
 433   // for regular objects are calculated, and we know what regions in heap suffix are
 434   // available for humongous moves.
 435   //
 436   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 437   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 438   // humongous start there.
 439   //
 440   // The complication is potential non-movable regions during the scan. If such region is
 441   // detected, then sliding restarts towards that non-movable region.
 442 
 443   size_t to_begin = heap->num_regions();
 444   size_t to_end = heap->num_regions();
 445 
 446   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 447     ShenandoahHeapRegion *r = heap->get_region(c);
 448     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 449       // To-region candidate: record this, and continue scan
 450       to_begin = r->region_number();
 451       continue;
 452     }
 453 
 454     if (r->is_humongous_start() && r->is_move_allowed()) {
 455       // From-region candidate: movable humongous region
 456       oop old_obj = oop(r->bottom() + BrooksPointer::word_size());
 457       size_t words_size = old_obj->size() + BrooksPointer::word_size();
 458       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 459 
 460       size_t start = to_end - num_regions;
 461 
 462       if (start >= to_begin && start != r->region_number()) {
 463         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 464         BrooksPointer::set_raw(old_obj, heap->get_region(start)->bottom() + BrooksPointer::word_size());
 465         to_end = start;
 466         continue;
 467       }
 468     }
 469 
 470     // Failed to fit. Scan starting from current region.
 471     to_begin = r->region_number();
 472     to_end = r->region_number();
 473   }
 474 }
 475 
 476 void ShenandoahMarkCompact::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 477   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 478   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 479 
 480   ShenandoahHeap* heap = ShenandoahHeap::heap();
 481 
 482   {
 483     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 484 
 485     {
 486       ShenandoahHeapLocker lock(heap->lock());
 487 
 488       ShenandoahMCReclaimHumongousRegionClosure cl;
 489       heap->heap_region_iterate(&cl);
 490 
 491       // After some humongous regions were reclaimed, we need to ensure their
 492       // backing storage is active. This is needed because we are potentially
 493       // sliding the data through them.
 494       ShenandoahEnsureHeapActiveClosure ecl;
 495       heap->heap_region_iterate(&ecl, false, false);
 496     }
 497 
 498     // Compute the new addresses for regular objects
 499     ShenandoahPrepareForCompactionTask prepare_task(worker_slices);
 500     heap->workers()->run_task(&prepare_task);
 501   }
 502 
 503   // Compute the new addresses for humongous objects
 504   {
 505     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 506     calculate_target_humongous_objects();
 507   }
 508 }
 509 
 510 class ShenandoahAdjustPointersClosure : public MetadataAwareOopClosure {
 511 private:
 512   ShenandoahHeap* const _heap;
 513   size_t _new_obj_offset;
 514 
 515   template <class T>
 516   inline void do_oop_work(T* p) {
 517     T o = oopDesc::load_heap_oop(p);
 518     if (! oopDesc::is_null(o)) {
 519       oop obj = oopDesc::decode_heap_oop_not_null(o);
 520       assert(_heap->is_marked_complete(obj), "must be marked");
 521       oop forw = oop(BrooksPointer::get_raw(obj));
 522       oopDesc::encode_store_heap_oop(p, forw);
 523       if (UseShenandoahMatrix) {
 524         if (_heap->is_in_reserved(p)) {
 525           assert(_heap->is_in_reserved(forw), "must be in heap");
 526           assert(_new_obj_offset != SIZE_MAX, "should be set");
 527           // We're moving a to a', which points to b, about to be moved to b'.
 528           // We already know b' from the fwd pointer of b.
 529           // In the object closure, we see a, and we know a' (by looking at its
 530           // fwd ptr). We store the offset in the OopClosure, which is going
 531           // to visit all of a's fields, and then, when we see each field, we
 532           // subtract the offset from each field address to get the final ptr.
 533           _heap->connection_matrix()->set_connected(((HeapWord*) p) - _new_obj_offset, forw);
 534         }
 535       }
 536     }
 537   }
 538 
 539 public:
 540   ShenandoahAdjustPointersClosure() : _heap(ShenandoahHeap::heap()), _new_obj_offset(SIZE_MAX)  {}
 541 
 542   void do_oop(oop* p)       { do_oop_work(p); }
 543   void do_oop(narrowOop* p) { do_oop_work(p); }
 544 
 545   void set_new_obj_offset(size_t new_obj_offset) {
 546     _new_obj_offset = new_obj_offset;
 547   }
 548 };
 549 
 550 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 551 private:
 552   ShenandoahHeap* const _heap;
 553   ShenandoahAdjustPointersClosure _cl;
 554 
 555 public:
 556   ShenandoahAdjustPointersObjectClosure() :
 557     _heap(ShenandoahHeap::heap()) {
 558   }
 559   void do_object(oop p) {
 560     assert(_heap->is_marked_complete(p), "must be marked");
 561     HeapWord* forw = BrooksPointer::get_raw(p);
 562     _cl.set_new_obj_offset(pointer_delta((HeapWord*) p, forw));
 563     p->oop_iterate(&_cl);
 564   }
 565 };
 566 
 567 class ShenandoahAdjustPointersTask : public AbstractGangTask {
 568 private:
 569   ShenandoahHeap*          const _heap;
 570   ShenandoahRegionIterator       _regions;
 571 
 572 public:
 573   ShenandoahAdjustPointersTask() :
 574     AbstractGangTask("Shenandoah Adjust Pointers Task"),
 575     _heap(ShenandoahHeap::heap()), _regions(_heap->region_iterator()) {
 576   }
 577 
 578   void work(uint worker_id) {
 579     ShenandoahAdjustPointersObjectClosure obj_cl;
 580     ShenandoahHeapRegion* r = _regions.next();
 581     while (r != NULL) {
 582       if (!r->is_humongous_continuation()) {
 583         _heap->marked_object_iterate(r, &obj_cl);
 584       }
 585       r = _regions.next();
 586     }
 587   }
 588 };
 589 
 590 class ShenandoahAdjustRootPointersTask : public AbstractGangTask {
 591 private:
 592   ShenandoahRootProcessor* _rp;
 593 
 594 public:
 595   ShenandoahAdjustRootPointersTask(ShenandoahRootProcessor* rp) :
 596     AbstractGangTask("Shenandoah Adjust Root Pointers Task"),
 597     _rp(rp) {}
 598 
 599   void work(uint worker_id) {
 600     ShenandoahAdjustPointersClosure cl;
 601     CLDToOopClosure adjust_cld_closure(&cl, true);
 602     MarkingCodeBlobClosure adjust_code_closure(&cl,
 603                                              CodeBlobToOopClosure::FixRelocations);
 604 
 605     _rp->process_all_roots(&cl, &cl,
 606                            &adjust_cld_closure,
 607                            &adjust_code_closure, NULL, worker_id);
 608   }
 609 };
 610 
 611 void ShenandoahMarkCompact::phase3_update_references() {
 612   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 613   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 614 
 615   ShenandoahHeap* heap = ShenandoahHeap::heap();
 616 
 617   if (UseShenandoahMatrix) {
 618     heap->connection_matrix()->clear_all();
 619   }
 620 
 621   WorkGang* workers = heap->workers();
 622   uint nworkers = workers->active_workers();
 623   {
 624 #if COMPILER2_OR_JVMCI
 625     DerivedPointerTable::clear();
 626 #endif
 627     ShenandoahRootProcessor rp(heap, nworkers, ShenandoahPhaseTimings::full_gc_roots);
 628     ShenandoahAdjustRootPointersTask task(&rp);
 629     workers->run_task(&task);
 630 #if COMPILER2_OR_JVMCI
 631     DerivedPointerTable::update_pointers();
 632 #endif
 633   }
 634 
 635   ShenandoahAdjustPointersTask adjust_pointers_task;
 636   workers->run_task(&adjust_pointers_task);
 637 }
 638 
 639 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 640 private:
 641   ShenandoahHeap* const _heap;
 642   uint            const _worker_id;
 643 
 644 public:
 645   ShenandoahCompactObjectsClosure(uint worker_id) :
 646     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
 647 
 648   void do_object(oop p) {
 649     assert(_heap->is_marked_complete(p), "must be marked");
 650     size_t size = (size_t)p->size();
 651     HeapWord* compact_to = BrooksPointer::get_raw(p);
 652     HeapWord* compact_from = (HeapWord*) p;
 653     if (compact_from != compact_to) {
 654       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 655     }
 656     oop new_obj = oop(compact_to);
 657     BrooksPointer::initialize(new_obj);
 658   }
 659 };
 660 
 661 class ShenandoahCompactObjectsTask : public AbstractGangTask {
 662 private:
 663   ShenandoahHeap* const _heap;
 664   ShenandoahHeapRegionSet** const _worker_slices;
 665 
 666 public:
 667   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 668     AbstractGangTask("Shenandoah Compact Objects Task"),
 669     _heap(ShenandoahHeap::heap()),
 670     _worker_slices(worker_slices) {
 671   }
 672 
 673   void work(uint worker_id) {
 674     ShenandoahHeapRegionSetIterator slice = _worker_slices[worker_id]->iterator();
 675 
 676     ShenandoahCompactObjectsClosure cl(worker_id);
 677     ShenandoahHeapRegion* r = slice.next();
 678     while (r != NULL) {
 679       assert(!r->is_humongous(), "must not get humongous regions here");
 680       _heap->marked_object_iterate(r, &cl);
 681       r->set_top(r->new_top());
 682       r = slice.next();
 683     }
 684   }
 685 };
 686 
 687 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 688 private:
 689   ShenandoahHeap* const _heap;
 690   size_t _live;
 691 
 692 public:
 693   ShenandoahPostCompactClosure() : _live(0), _heap(ShenandoahHeap::heap()) {
 694     _heap->free_set()->clear();
 695   }
 696 
 697   bool heap_region_do(ShenandoahHeapRegion* r) {
 698     assert (!r->is_cset(), "cset regions should have been demoted already");
 699 
 700     // Need to reset the complete-top-at-mark-start pointer here because
 701     // the complete marking bitmap is no longer valid. This ensures
 702     // size-based iteration in marked_object_iterate().
 703     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 704     // pinned regions.
 705     if (!r->is_pinned()) {
 706       _heap->set_complete_top_at_mark_start(r->bottom(), r->bottom());
 707     }
 708 
 709     size_t live = r->used();
 710 
 711     // Make empty regions that have been allocated into regular
 712     if (r->is_empty() && live > 0) {
 713       r->make_regular_bypass();
 714     }
 715 
 716     // Reclaim regular regions that became empty
 717     if (r->is_regular() && live == 0) {
 718       r->make_trash();
 719     }
 720 
 721     // Recycle all trash regions
 722     if (r->is_trash()) {
 723       live = 0;
 724       r->recycle();
 725     }
 726 
 727     r->set_live_data(live);
 728     r->reset_alloc_metadata_to_shared();
 729     _live += live;
 730     return false;
 731   }
 732 
 733   size_t get_live() {
 734     return _live;
 735   }
 736 };
 737 
 738 void ShenandoahMarkCompact::compact_humongous_objects() {
 739   // Compact humongous regions, based on their fwdptr objects.
 740   //
 741   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
 742   // humongous regions are already compacted, and do not require further moves, which alleviates
 743   // sliding costs. We may consider doing this in parallel in future.
 744 
 745   ShenandoahHeap* heap = ShenandoahHeap::heap();
 746 
 747   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 748     ShenandoahHeapRegion* r = heap->get_region(c);
 749     if (r->is_humongous_start()) {
 750       oop old_obj = oop(r->bottom() + BrooksPointer::word_size());
 751       size_t words_size = old_obj->size() + BrooksPointer::word_size();
 752       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 753 
 754       size_t old_start = r->region_number();
 755       size_t old_end   = old_start + num_regions - 1;
 756       size_t new_start = heap->heap_region_index_containing(BrooksPointer::get_raw(old_obj));
 757       size_t new_end   = new_start + num_regions - 1;
 758 
 759       if (old_start == new_start) {
 760         // No need to move the object, it stays at the same slot
 761         continue;
 762       }
 763 
 764       assert (r->is_move_allowed(), "should be movable");
 765 
 766       Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),
 767                                    heap->get_region(new_start)->bottom(),
 768                                    ShenandoahHeapRegion::region_size_words()*num_regions);
 769 
 770       oop new_obj = oop(heap->get_region(new_start)->bottom() + BrooksPointer::word_size());
 771       BrooksPointer::initialize(new_obj);
 772 
 773       {
 774         ShenandoahHeapLocker lock(heap->lock());
 775 
 776         for (size_t c = old_start; c <= old_end; c++) {
 777           ShenandoahHeapRegion* r = heap->get_region(c);
 778           r->make_regular_bypass();
 779           r->set_top(r->bottom());
 780         }
 781 
 782         for (size_t c = new_start; c <= new_end; c++) {
 783           ShenandoahHeapRegion* r = heap->get_region(c);
 784           if (c == new_start) {
 785             r->make_humongous_start_bypass();
 786           } else {
 787             r->make_humongous_cont_bypass();
 788           }
 789 
 790           // Trailing region may be non-full, record the remainder there
 791           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
 792           if ((c == new_end) && (remainder != 0)) {
 793             r->set_top(r->bottom() + remainder);
 794           } else {
 795             r->set_top(r->end());
 796           }
 797 
 798           r->reset_alloc_metadata_to_shared();
 799         }
 800       }
 801     }
 802   }
 803 }
 804 
 805 // This is slightly different to ShHeap::reset_next_mark_bitmap:
 806 // we need to remain able to walk pinned regions.
 807 // Since pinned region do not move and don't get compacted, we will get holes with
 808 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
 809 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
 810 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
 811 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
 812 class ShenandoahMCResetCompleteBitmapTask : public AbstractGangTask {
 813 private:
 814   ShenandoahRegionIterator _regions;
 815 
 816 public:
 817   ShenandoahMCResetCompleteBitmapTask(ShenandoahRegionIterator regions) :
 818     AbstractGangTask("Parallel Reset Bitmap Task"),
 819     _regions(regions) {
 820   }
 821 
 822   void work(uint worker_id) {
 823     ShenandoahHeapRegion* region = _regions.next();
 824     ShenandoahHeap* heap = ShenandoahHeap::heap();
 825     while (region != NULL) {
 826       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned()) {
 827         HeapWord* bottom = region->bottom();
 828         HeapWord* top = heap->complete_top_at_mark_start(region->bottom());
 829         if (top > bottom) {
 830           heap->complete_mark_bit_map()->clear_range_large(MemRegion(bottom, top));
 831         }
 832         assert(heap->is_complete_bitmap_clear_range(bottom, region->end()), "must be clear");
 833       }
 834       region = _regions.next();
 835     }
 836   }
 837 };
 838 
 839 void ShenandoahMarkCompact::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
 840   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
 841   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
 842 
 843   ShenandoahHeap* heap = ShenandoahHeap::heap();
 844 
 845   // Compact regular objects first
 846   {
 847     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
 848     ShenandoahCompactObjectsTask compact_task(worker_slices);
 849     heap->workers()->run_task(&compact_task);
 850   }
 851 
 852   // Compact humongous objects after regular object moves
 853   {
 854     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
 855     compact_humongous_objects();
 856   }
 857 
 858   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
 859   // and must ensure the bitmap is in sync.
 860   ShenandoahMCResetCompleteBitmapTask task(heap->region_iterator());
 861   heap->workers()->run_task(&task);
 862 
 863   // Bring regions in proper states after the collection, and set heap properties.
 864   {
 865     ShenandoahHeapLocker lock(heap->lock());
 866     ShenandoahPostCompactClosure post_compact;
 867     heap->heap_region_iterate(&post_compact);
 868     heap->set_used(post_compact.get_live());
 869 
 870     heap->collection_set()->clear();
 871     heap->free_set()->rebuild();
 872   }
 873 
 874   heap->clear_cancelled_concgc();
 875 
 876   // Also clear the next bitmap in preparation for next marking.
 877   heap->reset_next_mark_bitmap();
 878 }