mark-compact.cc 125 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

30
#include "code-stubs.h"
31
#include "compilation-cache.h"
32
#include "deoptimizer.h"
33
#include "execution.h"
34
#include "gdb-jit.h"
35
#include "global-handles.h"
36
#include "heap-profiler.h"
37
#include "ic-inl.h"
38
#include "incremental-marking.h"
39
#include "liveobjectlist-inl.h"
40
#include "mark-compact.h"
41
#include "objects-visiting.h"
42
#include "objects-visiting-inl.h"
43 44
#include "stub-cache.h"

45 46
namespace v8 {
namespace internal {
47

48 49 50 51 52 53 54

const char* Marking::kWhiteBitPattern = "00";
const char* Marking::kBlackBitPattern = "10";
const char* Marking::kGreyBitPattern = "11";
const char* Marking::kImpossibleBitPattern = "01";


55
// -------------------------------------------------------------------------
56 57
// MarkCompactCollector

58 59 60 61
MarkCompactCollector::MarkCompactCollector() :  // NOLINT
#ifdef DEBUG
      state_(IDLE),
#endif
62
      sweep_precisely_(false),
63 64
      reduce_memory_footprint_(false),
      abort_incremental_marking_(false),
65
      marking_parity_(ODD_MARKING_PARITY),
66
      compacting_(false),
67
      was_marked_incrementally_(false),
68
      tracer_(NULL),
69
      migration_slots_buffer_(NULL),
70
      heap_(NULL),
71
      code_flusher_(NULL),
72
      encountered_weak_maps_(NULL) { }
73

74

75
#ifdef VERIFY_HEAP
76 77 78 79 80 81
class VerifyMarkingVisitor: public ObjectVisitor {
 public:
  void VisitPointers(Object** start, Object** end) {
    for (Object** current = start; current < end; current++) {
      if ((*current)->IsHeapObject()) {
        HeapObject* object = HeapObject::cast(*current);
82
        CHECK(HEAP->mark_compact_collector()->IsMarked(object));
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
      }
    }
  }
};


static void VerifyMarking(Address bottom, Address top) {
  VerifyMarkingVisitor visitor;
  HeapObject* object;
  Address next_object_must_be_here_or_later = bottom;

  for (Address current = bottom;
       current < top;
       current += kPointerSize) {
    object = HeapObject::FromAddress(current);
    if (MarkCompactCollector::IsMarked(object)) {
99
      CHECK(current >= next_object_must_be_here_or_later);
100 101 102 103 104 105 106 107 108 109 110
      object->Iterate(&visitor);
      next_object_must_be_here_or_later = current + object->Size();
    }
  }
}


static void VerifyMarking(NewSpace* space) {
  Address end = space->top();
  NewSpacePageIterator it(space->bottom(), end);
  // The bottom position is at the start of its page. Allows us to use
111
  // page->area_start() as start of range on all pages.
112
  CHECK_EQ(space->bottom(),
113
            NewSpacePage::FromAddress(space->bottom())->area_start());
114 115
  while (it.has_next()) {
    NewSpacePage* page = it.next();
116
    Address limit = it.has_next() ? page->area_end() : end;
117
    CHECK(limit == end || !page->Contains(end));
118
    VerifyMarking(page->area_start(), limit);
119 120 121 122 123 124 125 126
  }
}


static void VerifyMarking(PagedSpace* space) {
  PageIterator it(space);

  while (it.has_next()) {
127
    Page* p = it.next();
128
    VerifyMarking(p->area_start(), p->area_end());
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  }
}


static void VerifyMarking(Heap* heap) {
  VerifyMarking(heap->old_pointer_space());
  VerifyMarking(heap->old_data_space());
  VerifyMarking(heap->code_space());
  VerifyMarking(heap->cell_space());
  VerifyMarking(heap->map_space());
  VerifyMarking(heap->new_space());

  VerifyMarkingVisitor visitor;

  LargeObjectIterator it(heap->lo_space());
  for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
    if (MarkCompactCollector::IsMarked(obj)) {
      obj->Iterate(&visitor);
    }
  }

  heap->IterateStrongRoots(&visitor, VISIT_ONLY_STRONG);
}


class VerifyEvacuationVisitor: public ObjectVisitor {
 public:
  void VisitPointers(Object** start, Object** end) {
    for (Object** current = start; current < end; current++) {
      if ((*current)->IsHeapObject()) {
        HeapObject* object = HeapObject::cast(*current);
160
        CHECK(!MarkCompactCollector::IsOnEvacuationCandidate(object));
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      }
    }
  }
};


static void VerifyEvacuation(Address bottom, Address top) {
  VerifyEvacuationVisitor visitor;
  HeapObject* object;
  Address next_object_must_be_here_or_later = bottom;

  for (Address current = bottom;
       current < top;
       current += kPointerSize) {
    object = HeapObject::FromAddress(current);
    if (MarkCompactCollector::IsMarked(object)) {
177
      CHECK(current >= next_object_must_be_here_or_later);
178 179 180 181 182 183 184 185
      object->Iterate(&visitor);
      next_object_must_be_here_or_later = current + object->Size();
    }
  }
}


static void VerifyEvacuation(NewSpace* space) {
186 187 188 189 190
  NewSpacePageIterator it(space->bottom(), space->top());
  VerifyEvacuationVisitor visitor;

  while (it.has_next()) {
    NewSpacePage* page = it.next();
191 192
    Address current = page->area_start();
    Address limit = it.has_next() ? page->area_end() : space->top();
193
    CHECK(limit == space->top() || !page->Contains(space->top()));
194 195 196 197 198 199
    while (current < limit) {
      HeapObject* object = HeapObject::FromAddress(current);
      object->Iterate(&visitor);
      current += object->Size();
    }
  }
200 201 202 203 204 205 206
}


static void VerifyEvacuation(PagedSpace* space) {
  PageIterator it(space);

  while (it.has_next()) {
207 208
    Page* p = it.next();
    if (p->IsEvacuationCandidate()) continue;
209
    VerifyEvacuation(p->area_start(), p->area_end());
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  }
}


static void VerifyEvacuation(Heap* heap) {
  VerifyEvacuation(heap->old_pointer_space());
  VerifyEvacuation(heap->old_data_space());
  VerifyEvacuation(heap->code_space());
  VerifyEvacuation(heap->cell_space());
  VerifyEvacuation(heap->map_space());
  VerifyEvacuation(heap->new_space());

  VerifyEvacuationVisitor visitor;
  heap->IterateStrongRoots(&visitor, VISIT_ALL);
}
225
#endif  // VERIFY_HEAP
226 227


228
#ifdef DEBUG
229
class VerifyNativeContextSeparationVisitor: public ObjectVisitor {
230
 public:
231
  VerifyNativeContextSeparationVisitor() : current_native_context_(NULL) {}
232 233 234 235 236 237 238 239 240 241 242

  void VisitPointers(Object** start, Object** end) {
    for (Object** current = start; current < end; current++) {
      if ((*current)->IsHeapObject()) {
        HeapObject* object = HeapObject::cast(*current);
        if (object->IsString()) continue;
        switch (object->map()->instance_type()) {
          case JS_FUNCTION_TYPE:
            CheckContext(JSFunction::cast(object)->context());
            break;
          case JS_GLOBAL_PROXY_TYPE:
243
            CheckContext(JSGlobalProxy::cast(object)->native_context());
244 245 246
            break;
          case JS_GLOBAL_OBJECT_TYPE:
          case JS_BUILTINS_OBJECT_TYPE:
247
            CheckContext(GlobalObject::cast(object)->native_context());
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
            break;
          case JS_ARRAY_TYPE:
          case JS_DATE_TYPE:
          case JS_OBJECT_TYPE:
          case JS_REGEXP_TYPE:
            VisitPointer(HeapObject::RawField(object, JSObject::kMapOffset));
            break;
          case MAP_TYPE:
            VisitPointer(HeapObject::RawField(object, Map::kPrototypeOffset));
            VisitPointer(HeapObject::RawField(object, Map::kConstructorOffset));
            break;
          case FIXED_ARRAY_TYPE:
            if (object->IsContext()) {
              CheckContext(object);
            } else {
              FixedArray* array = FixedArray::cast(object);
              int length = array->length();
              // Set array length to zero to prevent cycles while iterating
              // over array bodies, this is easier than intrusive marking.
              array->set_length(0);
              array->IterateBody(
                  FIXED_ARRAY_TYPE, FixedArray::SizeFor(length), this);
              array->set_length(length);
            }
            break;
          case JS_GLOBAL_PROPERTY_CELL_TYPE:
          case JS_PROXY_TYPE:
          case JS_VALUE_TYPE:
          case TYPE_FEEDBACK_INFO_TYPE:
            object->Iterate(this);
            break;
          case ACCESSOR_INFO_TYPE:
          case BYTE_ARRAY_TYPE:
          case CALL_HANDLER_INFO_TYPE:
          case CODE_TYPE:
          case FIXED_DOUBLE_ARRAY_TYPE:
          case HEAP_NUMBER_TYPE:
          case INTERCEPTOR_INFO_TYPE:
          case ODDBALL_TYPE:
          case SCRIPT_TYPE:
          case SHARED_FUNCTION_INFO_TYPE:
            break;
          default:
            UNREACHABLE();
        }
      }
    }
  }

 private:
  void CheckContext(Object* context) {
    if (!context->IsContext()) return;
300 301 302
    Context* native_context = Context::cast(context)->native_context();
    if (current_native_context_ == NULL) {
      current_native_context_ = native_context;
303
    } else {
304
      CHECK_EQ(current_native_context_, native_context);
305 306 307
    }
  }

308
  Context* current_native_context_;
309 310 311
};


312
static void VerifyNativeContextSeparation(Heap* heap) {
313 314 315
  HeapObjectIterator it(heap->code_space());

  for (Object* object = it.Next(); object != NULL; object = it.Next()) {
316
    VerifyNativeContextSeparationVisitor visitor;
317 318 319
    Code::cast(object)->CodeIterateBody(&visitor);
  }
}
320 321 322 323 324 325 326 327 328
#endif


void MarkCompactCollector::AddEvacuationCandidate(Page* p) {
  p->MarkEvacuationCandidate();
  evacuation_candidates_.Add(p);
}


329 330
static void TraceFragmentation(PagedSpace* space) {
  int number_of_pages = space->CountTotalPages();
331
  intptr_t reserved = (number_of_pages * space->AreaSize());
332 333 334 335 336 337 338 339 340
  intptr_t free = reserved - space->SizeOfObjects();
  PrintF("[%s]: %d pages, %d (%.1f%%) free\n",
         AllocationSpaceName(space->identity()),
         number_of_pages,
         static_cast<int>(free),
         static_cast<double>(free) * 100 / reserved);
}


341
bool MarkCompactCollector::StartCompaction(CompactionMode mode) {
342
  if (!compacting_) {
343 344
    ASSERT(evacuation_candidates_.length() == 0);

345 346 347 348 349
#ifdef ENABLE_GDB_JIT_INTERFACE
    // If GDBJIT interface is active disable compaction.
    if (FLAG_gdbjit) return false;
#endif

350 351
    CollectEvacuationCandidates(heap()->old_pointer_space());
    CollectEvacuationCandidates(heap()->old_data_space());
352

353 354 355
    if (FLAG_compact_code_space &&
        (mode == NON_INCREMENTAL_COMPACTION ||
         FLAG_incremental_code_compaction)) {
356
      CollectEvacuationCandidates(heap()->code_space());
357 358 359 360 361 362 363
    } else if (FLAG_trace_fragmentation) {
      TraceFragmentation(heap()->code_space());
    }

    if (FLAG_trace_fragmentation) {
      TraceFragmentation(heap()->map_space());
      TraceFragmentation(heap()->cell_space());
364
    }
365 366 367 368 369 370 371 372 373 374 375 376

    heap()->old_pointer_space()->EvictEvacuationCandidatesFromFreeLists();
    heap()->old_data_space()->EvictEvacuationCandidatesFromFreeLists();
    heap()->code_space()->EvictEvacuationCandidatesFromFreeLists();

    compacting_ = evacuation_candidates_.length() > 0;
  }

  return compacting_;
}


377 378 379 380
void MarkCompactCollector::CollectGarbage() {
  // Make sure that Prepare() has been called. The individual steps below will
  // update the state as they proceed.
  ASSERT(state_ == PREPARE_GC);
381
  ASSERT(encountered_weak_maps_ == Smi::FromInt(0));
382

383
  MarkLiveObjects();
384
  ASSERT(heap_->incremental_marking()->IsStopped());
385

386
  if (FLAG_collect_maps) ClearNonLiveTransitions();
387

388 389
  ClearWeakMaps();

390
#ifdef VERIFY_HEAP
391 392 393 394
  if (FLAG_verify_heap) {
    VerifyMarking(heap_);
  }
#endif
395

396
  SweepSpaces();
397

398
  if (!FLAG_collect_maps) ReattachInitialMaps();
399

400
#ifdef DEBUG
401 402
  if (FLAG_verify_native_context_separation) {
    VerifyNativeContextSeparation(heap_);
403 404 405
  }
#endif

406
  Finish();
407

408 409 410 411 412 413 414
  if (marking_parity_ == EVEN_MARKING_PARITY) {
    marking_parity_ = ODD_MARKING_PARITY;
  } else {
    ASSERT(marking_parity_ == ODD_MARKING_PARITY);
    marking_parity_ = EVEN_MARKING_PARITY;
  }

415
  tracer_ = NULL;
416 417 418
}


419
#ifdef VERIFY_HEAP
420 421 422 423 424
void MarkCompactCollector::VerifyMarkbitsAreClean(PagedSpace* space) {
  PageIterator it(space);

  while (it.has_next()) {
    Page* p = it.next();
425 426
    CHECK(p->markbits()->IsClean());
    CHECK_EQ(0, p->LiveBytes());
427 428 429
  }
}

430

431 432 433 434 435
void MarkCompactCollector::VerifyMarkbitsAreClean(NewSpace* space) {
  NewSpacePageIterator it(space->bottom(), space->top());

  while (it.has_next()) {
    NewSpacePage* p = it.next();
436 437
    CHECK(p->markbits()->IsClean());
    CHECK_EQ(0, p->LiveBytes());
438 439 440
  }
}

441

442 443 444 445 446 447 448 449 450 451 452
void MarkCompactCollector::VerifyMarkbitsAreClean() {
  VerifyMarkbitsAreClean(heap_->old_pointer_space());
  VerifyMarkbitsAreClean(heap_->old_data_space());
  VerifyMarkbitsAreClean(heap_->code_space());
  VerifyMarkbitsAreClean(heap_->cell_space());
  VerifyMarkbitsAreClean(heap_->map_space());
  VerifyMarkbitsAreClean(heap_->new_space());

  LargeObjectIterator it(heap_->lo_space());
  for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
    MarkBit mark_bit = Marking::MarkBitFrom(obj);
453 454
    CHECK(Marking::IsWhite(mark_bit));
    CHECK_EQ(0, Page::FromAddress(obj->address())->LiveBytes());
455 456
  }
}
457
#endif  // VERIFY_HEAP
458 459


460
static void ClearMarkbitsInPagedSpace(PagedSpace* space) {
461 462 463 464 465 466 467 468
  PageIterator it(space);

  while (it.has_next()) {
    Bitmap::Clear(it.next());
  }
}


469
static void ClearMarkbitsInNewSpace(NewSpace* space) {
470 471 472 473 474 475 476 477
  NewSpacePageIterator it(space->ToSpaceStart(), space->ToSpaceEnd());

  while (it.has_next()) {
    Bitmap::Clear(it.next());
  }
}


478 479 480 481 482 483 484
void MarkCompactCollector::ClearMarkbits() {
  ClearMarkbitsInPagedSpace(heap_->code_space());
  ClearMarkbitsInPagedSpace(heap_->map_space());
  ClearMarkbitsInPagedSpace(heap_->old_pointer_space());
  ClearMarkbitsInPagedSpace(heap_->old_data_space());
  ClearMarkbitsInPagedSpace(heap_->cell_space());
  ClearMarkbitsInNewSpace(heap_->new_space());
485

486
  LargeObjectIterator it(heap_->lo_space());
487 488 489 490
  for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
    MarkBit mark_bit = Marking::MarkBitFrom(obj);
    mark_bit.Clear();
    mark_bit.Next().Clear();
491
    Page::FromAddress(obj->address())->ResetProgressBar();
492
    Page::FromAddress(obj->address())->ResetLiveBytes();
493 494 495 496 497 498 499 500
  }
}


bool Marking::TransferMark(Address old_start, Address new_start) {
  // This is only used when resizing an object.
  ASSERT(MemoryChunk::FromAddress(old_start) ==
         MemoryChunk::FromAddress(new_start));
501

502 503 504 505 506 507
  // If the mark doesn't move, we don't check the color of the object.
  // It doesn't matter whether the object is black, since it hasn't changed
  // size, so the adjustment to the live data count will be zero anyway.
  if (old_start == new_start) return false;

  MarkBit new_mark_bit = MarkBitFrom(new_start);
508
  MarkBit old_mark_bit = MarkBitFrom(old_start);
509 510

#ifdef DEBUG
511
  ObjectColor old_color = Color(old_mark_bit);
512
#endif
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

  if (Marking::IsBlack(old_mark_bit)) {
    old_mark_bit.Clear();
    ASSERT(IsWhite(old_mark_bit));
    Marking::MarkBlack(new_mark_bit);
    return true;
  } else if (Marking::IsGrey(old_mark_bit)) {
    ASSERT(heap_->incremental_marking()->IsMarking());
    old_mark_bit.Clear();
    old_mark_bit.Next().Clear();
    ASSERT(IsWhite(old_mark_bit));
    heap_->incremental_marking()->WhiteToGreyAndPush(
        HeapObject::FromAddress(new_start), new_mark_bit);
    heap_->incremental_marking()->RestartIfNotMarking();
  }
528 529

#ifdef DEBUG
530 531
  ObjectColor new_color = Color(new_mark_bit);
  ASSERT(new_color == old_color);
532
#endif
533 534

  return false;
535 536 537
}


538
const char* AllocationSpaceName(AllocationSpace space) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  switch (space) {
    case NEW_SPACE: return "NEW_SPACE";
    case OLD_POINTER_SPACE: return "OLD_POINTER_SPACE";
    case OLD_DATA_SPACE: return "OLD_DATA_SPACE";
    case CODE_SPACE: return "CODE_SPACE";
    case MAP_SPACE: return "MAP_SPACE";
    case CELL_SPACE: return "CELL_SPACE";
    case LO_SPACE: return "LO_SPACE";
    default:
      UNREACHABLE();
  }

  return NULL;
}


555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
// Returns zero for pages that have so little fragmentation that it is not
// worth defragmenting them.  Otherwise a positive integer that gives an
// estimate of fragmentation on an arbitrary scale.
static int FreeListFragmentation(PagedSpace* space, Page* p) {
  // If page was not swept then there are no free list items on it.
  if (!p->WasSwept()) {
    if (FLAG_trace_fragmentation) {
      PrintF("%p [%s]: %d bytes live (unswept)\n",
             reinterpret_cast<void*>(p),
             AllocationSpaceName(space->identity()),
             p->LiveBytes());
    }
    return 0;
  }

  FreeList::SizeStats sizes;
  space->CountFreeListItems(p, &sizes);

  intptr_t ratio;
  intptr_t ratio_threshold;
575
  intptr_t area_size = space->AreaSize();
576 577
  if (space->identity() == CODE_SPACE) {
    ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 /
578
        area_size;
579 580 581
    ratio_threshold = 10;
  } else {
    ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 /
582
        area_size;
583 584 585 586 587 588 589 590 591
    ratio_threshold = 15;
  }

  if (FLAG_trace_fragmentation) {
    PrintF("%p [%s]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
           reinterpret_cast<void*>(p),
           AllocationSpaceName(space->identity()),
           static_cast<int>(sizes.small_size_),
           static_cast<double>(sizes.small_size_ * 100) /
592
           area_size,
593 594
           static_cast<int>(sizes.medium_size_),
           static_cast<double>(sizes.medium_size_ * 100) /
595
           area_size,
596 597
           static_cast<int>(sizes.large_size_),
           static_cast<double>(sizes.large_size_ * 100) /
598
           area_size,
599 600
           static_cast<int>(sizes.huge_size_),
           static_cast<double>(sizes.huge_size_ * 100) /
601
           area_size,
602 603 604
           (ratio > ratio_threshold) ? "[fragmented]" : "");
  }

605
  if (FLAG_always_compact && sizes.Total() != area_size) {
606 607 608 609 610 611 612 613 614
    return 1;
  }

  if (ratio <= ratio_threshold) return 0;  // Not fragmented.

  return static_cast<int>(ratio - ratio_threshold);
}


615 616 617 618 619
void MarkCompactCollector::CollectEvacuationCandidates(PagedSpace* space) {
  ASSERT(space->identity() == OLD_POINTER_SPACE ||
         space->identity() == OLD_DATA_SPACE ||
         space->identity() == CODE_SPACE);

620
  static const int kMaxMaxEvacuationCandidates = 1000;
621
  int number_of_pages = space->CountTotalPages();
622
  int max_evacuation_candidates =
623
      static_cast<int>(sqrt(number_of_pages / 2.0) + 1);
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

  if (FLAG_stress_compaction || FLAG_always_compact) {
    max_evacuation_candidates = kMaxMaxEvacuationCandidates;
  }

  class Candidate {
   public:
    Candidate() : fragmentation_(0), page_(NULL) { }
    Candidate(int f, Page* p) : fragmentation_(f), page_(p) { }

    int fragmentation() { return fragmentation_; }
    Page* page() { return page_; }

   private:
    int fragmentation_;
    Page* page_;
  };

642 643 644 645 646 647 648
  enum CompactionMode {
    COMPACT_FREE_LISTS,
    REDUCE_MEMORY_FOOTPRINT
  };

  CompactionMode mode = COMPACT_FREE_LISTS;

649
  intptr_t reserved = number_of_pages * space->AreaSize();
650 651 652
  intptr_t over_reserved = reserved - space->SizeOfObjects();
  static const intptr_t kFreenessThreshold = 50;

653
  if (reduce_memory_footprint_ && over_reserved >= space->AreaSize()) {
654 655 656
    // If reduction of memory footprint was requested, we are aggressive
    // about choosing pages to free.  We expect that half-empty pages
    // are easier to compact so slightly bump the limit.
657 658 659 660
    mode = REDUCE_MEMORY_FOOTPRINT;
    max_evacuation_candidates += 2;
  }

661

662
  if (over_reserved > reserved / 3 && over_reserved >= 2 * space->AreaSize()) {
663 664 665
    // If over-usage is very high (more than a third of the space), we
    // try to free all mostly empty pages.  We expect that almost empty
    // pages are even easier to compact so bump the limit even more.
666 667 668
    mode = REDUCE_MEMORY_FOOTPRINT;
    max_evacuation_candidates *= 2;
  }
669

670 671 672 673 674
  if (FLAG_trace_fragmentation && mode == REDUCE_MEMORY_FOOTPRINT) {
    PrintF("Estimated over reserved memory: %.1f / %.1f MB (threshold %d)\n",
           static_cast<double>(over_reserved) / MB,
           static_cast<double>(reserved) / MB,
           static_cast<int>(kFreenessThreshold));
675 676 677 678
  }

  intptr_t estimated_release = 0;

679 680
  Candidate candidates[kMaxMaxEvacuationCandidates];

681 682 683
  max_evacuation_candidates =
      Min(kMaxMaxEvacuationCandidates, max_evacuation_candidates);

684
  int count = 0;
685 686
  int fragmentation = 0;
  Candidate* least = NULL;
687 688 689 690

  PageIterator it(space);
  if (it.has_next()) it.next();  // Never compact the first page.

691 692
  while (it.has_next()) {
    Page* p = it.next();
693
    p->ClearEvacuationCandidate();
694

695
    if (FLAG_stress_compaction) {
696
      unsigned int counter = space->heap()->ms_count();
697
      uintptr_t page_number = reinterpret_cast<uintptr_t>(p) >> kPageSizeBits;
698
      if ((counter & 1) == (page_number & 1)) fragmentation = 1;
699 700 701 702 703 704 705 706 707
    } else if (mode == REDUCE_MEMORY_FOOTPRINT) {
      // Don't try to release too many pages.
      if (estimated_release >= ((over_reserved * 3) / 4)) {
        continue;
      }

      intptr_t free_bytes = 0;

      if (!p->WasSwept()) {
708
        free_bytes = (p->area_size() - p->LiveBytes());
709 710 711 712 713 714
      } else {
        FreeList::SizeStats sizes;
        space->CountFreeListItems(p, &sizes);
        free_bytes = sizes.Total();
      }

715
      int free_pct = static_cast<int>(free_bytes * 100) / p->area_size();
716 717

      if (free_pct >= kFreenessThreshold) {
718
        estimated_release += 2 * p->area_size() - free_bytes;
719 720 721 722 723 724 725 726 727
        fragmentation = free_pct;
      } else {
        fragmentation = 0;
      }

      if (FLAG_trace_fragmentation) {
        PrintF("%p [%s]: %d (%.2f%%) free %s\n",
               reinterpret_cast<void*>(p),
               AllocationSpaceName(space->identity()),
728
               static_cast<int>(free_bytes),
729
               static_cast<double>(free_bytes * 100) / p->area_size(),
730 731
               (fragmentation > 0) ? "[fragmented]" : "");
      }
732
    } else {
733
      fragmentation = FreeListFragmentation(space, p);
734
    }
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    if (fragmentation != 0) {
      if (count < max_evacuation_candidates) {
        candidates[count++] = Candidate(fragmentation, p);
      } else {
        if (least == NULL) {
          for (int i = 0; i < max_evacuation_candidates; i++) {
            if (least == NULL ||
                candidates[i].fragmentation() < least->fragmentation()) {
              least = candidates + i;
            }
          }
        }
        if (least->fragmentation() < fragmentation) {
          *least = Candidate(fragmentation, p);
          least = NULL;
        }
      }
753 754
    }
  }
755

756 757 758
  for (int i = 0; i < count; i++) {
    AddEvacuationCandidate(candidates[i].page());
  }
759 760 761 762 763 764 765 766 767

  if (count > 0 && FLAG_trace_fragmentation) {
    PrintF("Collected %d evacuation candidates for space %s\n",
           count,
           AllocationSpaceName(space->identity()));
  }
}


768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
void MarkCompactCollector::AbortCompaction() {
  if (compacting_) {
    int npages = evacuation_candidates_.length();
    for (int i = 0; i < npages; i++) {
      Page* p = evacuation_candidates_[i];
      slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
      p->ClearEvacuationCandidate();
      p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
    }
    compacting_ = false;
    evacuation_candidates_.Rewind(0);
    invalidated_code_.Rewind(0);
  }
  ASSERT_EQ(0, evacuation_candidates_.length());
}


785
void MarkCompactCollector::Prepare(GCTracer* tracer) {
786 787
  was_marked_incrementally_ = heap()->incremental_marking()->IsMarking();

788 789 790 791
  // Rather than passing the tracer around we stash it in a static member
  // variable.
  tracer_ = tracer;

792 793 794 795
#ifdef DEBUG
  ASSERT(state_ == IDLE);
  state_ = PREPARE_GC;
#endif
796

797
  ASSERT(!FLAG_never_compact || !FLAG_always_compact);
798

799 800
  // Clear marking bits if incremental marking is aborted.
  if (was_marked_incrementally_ && abort_incremental_marking_) {
801
    heap()->incremental_marking()->Abort();
802
    ClearMarkbits();
803
    AbortCompaction();
804
    was_marked_incrementally_ = false;
805 806
  }

807 808 809
  // Don't start compaction if we are in the middle of incremental
  // marking cycle. We did not collect any slots.
  if (!FLAG_never_compact && !was_marked_incrementally_) {
810
    StartCompaction(NON_INCREMENTAL_COMPACTION);
811
  }
812

813
  PagedSpaces spaces;
814
  for (PagedSpace* space = spaces.next();
815 816 817
       space != NULL;
       space = spaces.next()) {
    space->PrepareForMarkCompact();
818
  }
819

820
#ifdef VERIFY_HEAP
821
  if (!was_marked_incrementally_ && FLAG_verify_heap) {
822 823 824
    VerifyMarkbitsAreClean();
  }
#endif
825 826 827 828 829
}


void MarkCompactCollector::Finish() {
#ifdef DEBUG
830
  ASSERT(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS);
831 832 833 834 835 836
  state_ = IDLE;
#endif
  // The stub cache is not traversed during GC; clear the cache to
  // force lazy re-initialization of it. This must be done after the
  // GC, because it relies on the new address of certain old space
  // objects (empty string, illegal builtin).
837
  heap()->isolate()->stub_cache()->Clear();
838 839 840
}


841
// -------------------------------------------------------------------------
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
// Phase 1: tracing and marking live objects.
//   before: all objects are in normal state.
//   after: a live object's map pointer is marked as '00'.

// Marking all live objects in the heap as part of mark-sweep or mark-compact
// collection.  Before marking, all objects are in their normal state.  After
// marking, live objects' map pointers are marked indicating that the object
// has been found reachable.
//
// The marking algorithm is a (mostly) depth-first (because of possible stack
// overflow) traversal of the graph of objects reachable from the roots.  It
// uses an explicit stack of pointers rather than recursion.  The young
// generation's inactive ('from') space is used as a marking stack.  The
// objects in the marking stack are the ones that have been reached and marked
// but their children have not yet been visited.
//
// The marking stack can overflow during traversal.  In that case, we set an
// overflow flag.  When the overflow flag is set, we continue marking objects
// reachable from the objects on the marking stack, but no longer push them on
// the marking stack.  Instead, we mark them as both marked and overflowed.
// When the stack is in the overflowed state, objects marked as overflowed
// have been reached and marked but their children have not been visited yet.
// After emptying the marking stack, we clear the overflow flag and traverse
// the heap looking for objects marked as overflowed, push them on the stack,
// and continue with marking.  This process repeats until all reachable
// objects have been marked.

869 870
void CodeFlusher::ProcessJSFunctionCandidates() {
  Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kLazyCompile);
871
  Object* undefined = isolate_->heap()->undefined_value();
872

873 874 875 876
  JSFunction* candidate = jsfunction_candidates_head_;
  JSFunction* next_candidate;
  while (candidate != NULL) {
    next_candidate = GetNextCandidate(candidate);
877
    ClearNextCandidate(candidate, undefined);
878

879
    SharedFunctionInfo* shared = candidate->shared();
880

881 882 883 884 885
    Code* code = shared->code();
    MarkBit code_mark = Marking::MarkBitFrom(code);
    if (!code_mark.Get()) {
      shared->set_code(lazy_compile);
      candidate->set_code(lazy_compile);
886 887
    } else if (code == lazy_compile) {
      candidate->set_code(lazy_compile);
888 889
    }

890 891 892 893 894 895
    // We are in the middle of a GC cycle so the write barrier in the code
    // setter did not record the slot update and we have to do that manually.
    Address slot = candidate->address() + JSFunction::kCodeEntryOffset;
    Code* target = Code::cast(Code::GetObjectFromEntryAddress(slot));
    isolate_->heap()->mark_compact_collector()->
        RecordCodeEntrySlot(slot, target);
896

897 898 899 900
    Object** shared_code_slot =
        HeapObject::RawField(shared, SharedFunctionInfo::kCodeOffset);
    isolate_->heap()->mark_compact_collector()->
        RecordSlot(shared_code_slot, shared_code_slot, *shared_code_slot);
901

902
    candidate = next_candidate;
903 904
  }

905 906
  jsfunction_candidates_head_ = NULL;
}
907

908

909 910
void CodeFlusher::ProcessSharedFunctionInfoCandidates() {
  Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kLazyCompile);
911

912 913 914 915
  SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
  SharedFunctionInfo* next_candidate;
  while (candidate != NULL) {
    next_candidate = GetNextCandidate(candidate);
916
    ClearNextCandidate(candidate);
917

918
    Code* code = candidate->code();
919 920 921 922
    MarkBit code_mark = Marking::MarkBitFrom(code);
    if (!code_mark.Get()) {
      candidate->set_code(lazy_compile);
    }
923

924 925 926 927
    Object** code_slot =
        HeapObject::RawField(candidate, SharedFunctionInfo::kCodeOffset);
    isolate_->heap()->mark_compact_collector()->
        RecordSlot(code_slot, code_slot, *code_slot);
928

929
    candidate = next_candidate;
930 931
  }

932 933
  shared_function_info_candidates_head_ = NULL;
}
934 935


936 937 938 939
void CodeFlusher::EvictCandidate(JSFunction* function) {
  ASSERT(!function->next_function_link()->IsUndefined());
  Object* undefined = isolate_->heap()->undefined_value();

940 941 942 943
  // The function is no longer a candidate, make sure it gets visited
  // again so that previous flushing decisions are revisited.
  isolate_->heap()->incremental_marking()->RecordWrites(function);

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  JSFunction* candidate = jsfunction_candidates_head_;
  JSFunction* next_candidate;
  if (candidate == function) {
    next_candidate = GetNextCandidate(function);
    jsfunction_candidates_head_ = next_candidate;
    ClearNextCandidate(function, undefined);
  } else {
    while (candidate != NULL) {
      next_candidate = GetNextCandidate(candidate);

      if (next_candidate == function) {
        next_candidate = GetNextCandidate(function);
        SetNextCandidate(candidate, next_candidate);
        ClearNextCandidate(function, undefined);
      }

      candidate = next_candidate;
    }
  }
}


966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
void CodeFlusher::EvictJSFunctionCandidates() {
  Object* undefined = isolate_->heap()->undefined_value();

  JSFunction* candidate = jsfunction_candidates_head_;
  JSFunction* next_candidate;
  while (candidate != NULL) {
    next_candidate = GetNextCandidate(candidate);
    ClearNextCandidate(candidate, undefined);
    candidate = next_candidate;
  }

  jsfunction_candidates_head_ = NULL;
}


void CodeFlusher::EvictSharedFunctionInfoCandidates() {
  SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
  SharedFunctionInfo* next_candidate;
  while (candidate != NULL) {
    next_candidate = GetNextCandidate(candidate);
    ClearNextCandidate(candidate);
    candidate = next_candidate;
  }

  shared_function_info_candidates_head_ = NULL;
}


994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
void CodeFlusher::IteratePointersToFromSpace(ObjectVisitor* v) {
  Heap* heap = isolate_->heap();

  JSFunction** slot = &jsfunction_candidates_head_;
  JSFunction* candidate = jsfunction_candidates_head_;
  while (candidate != NULL) {
    if (heap->InFromSpace(candidate)) {
      v->VisitPointer(reinterpret_cast<Object**>(slot));
    }
    candidate = GetNextCandidate(*slot);
    slot = GetNextCandidateSlot(*slot);
  }
}


1009 1010 1011 1012 1013 1014 1015
MarkCompactCollector::~MarkCompactCollector() {
  if (code_flusher_ != NULL) {
    delete code_flusher_;
    code_flusher_ = NULL;
  }
}

1016

1017
static inline HeapObject* ShortCircuitConsString(Object** p) {
1018
  // Optimization: If the heap object pointed to by p is a non-symbol
1019
  // cons string whose right substring is HEAP->empty_string, update
1020
  // it in place to its left substring.  Return the updated value.
1021 1022
  //
  // Here we assume that if we change *p, we replace it with a heap object
1023
  // (i.e., the left substring of a cons string is always a heap object).
1024 1025
  //
  // The check performed is:
1026
  //   object->IsConsString() && !object->IsSymbol() &&
1027
  //   (ConsString::cast(object)->second() == HEAP->empty_string())
1028 1029 1030
  // except the maps for the object and its possible substrings might be
  // marked.
  HeapObject* object = HeapObject::cast(*p);
1031
  if (!FLAG_clever_optimizations) return object;
1032 1033
  Map* map = object->map();
  InstanceType type = map->instance_type();
1034
  if ((type & kShortcutTypeMask) != kShortcutTypeTag) return object;
1035

1036
  Object* second = reinterpret_cast<ConsString*>(object)->unchecked_second();
1037 1038
  Heap* heap = map->GetHeap();
  if (second != heap->empty_string()) {
1039 1040
    return object;
  }
1041 1042

  // Since we don't have the object's start, it is impossible to update the
1043 1044
  // page dirty marks. Therefore, we only replace the string with its left
  // substring when page dirty marks do not change.
1045
  Object* first = reinterpret_cast<ConsString*>(object)->unchecked_first();
1046
  if (!heap->InNewSpace(object) && heap->InNewSpace(first)) return object;
1047 1048 1049 1050 1051 1052

  *p = first;
  return HeapObject::cast(first);
}


1053 1054
class MarkCompactMarkingVisitor
    : public StaticMarkingVisitor<MarkCompactMarkingVisitor> {
1055
 public:
1056 1057 1058 1059 1060 1061 1062 1063
  static void ObjectStatsVisitBase(StaticVisitorBase::VisitorId id,
                                   Map* map, HeapObject* obj);

  static void ObjectStatsCountFixedArray(
      FixedArrayBase* fixed_array,
      FixedArraySubInstanceType fast_type,
      FixedArraySubInstanceType dictionary_type);

1064
  template<MarkCompactMarkingVisitor::VisitorId id>
1065 1066
  class ObjectStatsTracker {
   public:
1067
    static inline void Visit(Map* map, HeapObject* obj);
1068 1069
  };

1070
  static void Initialize();
1071

1072
  INLINE(static void VisitPointer(Heap* heap, Object** p)) {
1073
    MarkObjectByPointer(heap->mark_compact_collector(), p, p);
1074 1075
  }

1076
  INLINE(static void VisitPointers(Heap* heap, Object** start, Object** end)) {
1077 1078 1079
    // Mark all objects pointed to in [start, end).
    const int kMinRangeForMarkingRecursion = 64;
    if (end - start >= kMinRangeForMarkingRecursion) {
1080
      if (VisitUnmarkedObjects(heap, start, end)) return;
1081 1082
      // We are close to a stack overflow, so just mark the objects.
    }
1083 1084
    MarkCompactCollector* collector = heap->mark_compact_collector();
    for (Object** p = start; p < end; p++) {
1085
      MarkObjectByPointer(collector, start, p);
1086 1087 1088
    }
  }

1089
  // Marks the object black and pushes it on the marking stack.
1090 1091 1092
  INLINE(static void MarkObject(Heap* heap, HeapObject* object)) {
    MarkBit mark = Marking::MarkBitFrom(object);
    heap->mark_compact_collector()->MarkObject(object, mark);
1093 1094
  }

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  // Marks the object black without pushing it on the marking stack.
  // Returns true if object needed marking and false otherwise.
  INLINE(static bool MarkObjectWithoutPush(Heap* heap, HeapObject* object)) {
    MarkBit mark_bit = Marking::MarkBitFrom(object);
    if (!mark_bit.Get()) {
      heap->mark_compact_collector()->SetMark(object, mark_bit);
      return true;
    }
    return false;
  }

1106
  // Mark object pointed to by p.
1107 1108 1109
  INLINE(static void MarkObjectByPointer(MarkCompactCollector* collector,
                                         Object** anchor_slot,
                                         Object** p)) {
1110 1111
    if (!(*p)->IsHeapObject()) return;
    HeapObject* object = ShortCircuitConsString(p);
1112 1113 1114
    collector->RecordSlot(anchor_slot, p, object);
    MarkBit mark = Marking::MarkBitFrom(object);
    collector->MarkObject(object, mark);
1115 1116
  }

1117

1118
  // Visit an unmarked object.
1119 1120
  INLINE(static void VisitUnmarkedObject(MarkCompactCollector* collector,
                                         HeapObject* obj)) {
1121
#ifdef DEBUG
1122
    ASSERT(Isolate::Current()->heap()->Contains(obj));
1123
    ASSERT(!HEAP->mark_compact_collector()->IsMarked(obj));
1124 1125
#endif
    Map* map = obj->map();
1126 1127 1128
    Heap* heap = obj->GetHeap();
    MarkBit mark = Marking::MarkBitFrom(obj);
    heap->mark_compact_collector()->SetMark(obj, mark);
1129
    // Mark the map pointer and the body.
1130 1131
    MarkBit map_mark = Marking::MarkBitFrom(map);
    heap->mark_compact_collector()->MarkObject(map, map_mark);
1132
    IterateBody(map, obj);
1133 1134
  }

1135
  // Visit all unmarked objects pointed to by [start, end).
1136
  // Returns false if the operation fails (lack of stack space).
1137
  static inline bool VisitUnmarkedObjects(Heap* heap,
1138 1139
                                          Object** start,
                                          Object** end) {
1140
    // Return false is we are close to the stack limit.
1141
    StackLimitCheck check(heap->isolate());
1142 1143
    if (check.HasOverflowed()) return false;

1144
    MarkCompactCollector* collector = heap->mark_compact_collector();
1145
    // Visit the unmarked objects.
1146
    for (Object** p = start; p < end; p++) {
1147 1148
      Object* o = *p;
      if (!o->IsHeapObject()) continue;
1149
      collector->RecordSlot(start, p, o);
1150 1151 1152
      HeapObject* obj = HeapObject::cast(o);
      MarkBit mark = Marking::MarkBitFrom(obj);
      if (mark.Get()) continue;
1153
      VisitUnmarkedObject(collector, obj);
1154 1155 1156
    }
    return true;
  }
1157

1158 1159 1160 1161 1162
  INLINE(static void BeforeVisitingSharedFunctionInfo(HeapObject* object)) {
    SharedFunctionInfo* shared = SharedFunctionInfo::cast(object);
    shared->BeforeVisitingPointers();
  }

1163
  static void VisitJSWeakMap(Map* map, HeapObject* object) {
1164
    MarkCompactCollector* collector = map->GetHeap()->mark_compact_collector();
1165 1166 1167
    JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(object);

    // Enqueue weak map in linked list of encountered weak maps.
1168 1169 1170 1171
    if (weak_map->next() == Smi::FromInt(0)) {
      weak_map->set_next(collector->encountered_weak_maps());
      collector->set_encountered_weak_maps(weak_map);
    }
1172 1173 1174

    // Skip visiting the backing hash table containing the mappings.
    int object_size = JSWeakMap::BodyDescriptor::SizeOf(map, object);
1175
    BodyVisitorBase<MarkCompactMarkingVisitor>::IteratePointers(
1176
        map->GetHeap(),
1177 1178 1179
        object,
        JSWeakMap::BodyDescriptor::kStartOffset,
        JSWeakMap::kTableOffset);
1180
    BodyVisitorBase<MarkCompactMarkingVisitor>::IteratePointers(
1181
        map->GetHeap(),
1182 1183 1184 1185 1186
        object,
        JSWeakMap::kTableOffset + kPointerSize,
        object_size);

    // Mark the backing hash table without pushing it on the marking stack.
1187 1188 1189 1190 1191 1192 1193 1194 1195
    Object* table_object = weak_map->table();
    if (!table_object->IsHashTable()) return;
    ObjectHashTable* table = ObjectHashTable::cast(table_object);
    Object** table_slot =
        HeapObject::RawField(weak_map, JSWeakMap::kTableOffset);
    MarkBit table_mark = Marking::MarkBitFrom(table);
    collector->RecordSlot(table_slot, table_slot, table);
    if (!table_mark.Get()) collector->SetMark(table, table_mark);
    // Recording the map slot can be skipped, because maps are not compacted.
1196 1197
    collector->MarkObject(table->map(), Marking::MarkBitFrom(table->map()));
    ASSERT(MarkCompactCollector::IsMarked(table->map()));
1198 1199
  }

1200 1201 1202
 private:
  template<int id>
  static inline void TrackObjectStatsAndVisit(Map* map, HeapObject* obj);
1203

1204 1205
  // Code flushing support.

1206 1207 1208 1209 1210 1211 1212
  static const int kRegExpCodeThreshold = 5;

  static void UpdateRegExpCodeAgeAndFlush(Heap* heap,
                                          JSRegExp* re,
                                          bool is_ascii) {
    // Make sure that the fixed array is in fact initialized on the RegExp.
    // We could potentially trigger a GC when initializing the RegExp.
1213 1214
    if (HeapObject::cast(re->data())->map()->instance_type() !=
            FIXED_ARRAY_TYPE) return;
1215 1216 1217 1218 1219

    // Make sure this is a RegExp that actually contains code.
    if (re->TypeTagUnchecked() != JSRegExp::IRREGEXP) return;

    Object* code = re->DataAtUnchecked(JSRegExp::code_index(is_ascii));
1220 1221
    if (!code->IsSmi() &&
        HeapObject::cast(code)->map()->instance_type() == CODE_TYPE) {
1222 1223 1224 1225
      // Save a copy that can be reinstated if we need the code again.
      re->SetDataAtUnchecked(JSRegExp::saved_code_index(is_ascii),
                             code,
                             heap);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235

      // Saving a copy might create a pointer into compaction candidate
      // that was not observed by marker.  This might happen if JSRegExp data
      // was marked through the compilation cache before marker reached JSRegExp
      // object.
      FixedArray* data = FixedArray::cast(re->data());
      Object** slot = data->data_start() + JSRegExp::saved_code_index(is_ascii);
      heap->mark_compact_collector()->
          RecordSlot(slot, slot, code);

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
      // Set a number in the 0-255 range to guarantee no smi overflow.
      re->SetDataAtUnchecked(JSRegExp::code_index(is_ascii),
                             Smi::FromInt(heap->sweep_generation() & 0xff),
                             heap);
    } else if (code->IsSmi()) {
      int value = Smi::cast(code)->value();
      // The regexp has not been compiled yet or there was a compilation error.
      if (value == JSRegExp::kUninitializedValue ||
          value == JSRegExp::kCompilationErrorValue) {
        return;
      }

      // Check if we should flush now.
      if (value == ((heap->sweep_generation() - kRegExpCodeThreshold) & 0xff)) {
        re->SetDataAtUnchecked(JSRegExp::code_index(is_ascii),
                               Smi::FromInt(JSRegExp::kUninitializedValue),
                               heap);
        re->SetDataAtUnchecked(JSRegExp::saved_code_index(is_ascii),
                               Smi::FromInt(JSRegExp::kUninitializedValue),
                               heap);
      }
    }
  }


  // Works by setting the current sweep_generation (as a smi) in the
  // code object place in the data array of the RegExp and keeps a copy
  // around that can be reinstated if we reuse the RegExp before flushing.
  // If we did not use the code for kRegExpCodeThreshold mark sweep GCs
  // we flush the code.
  static void VisitRegExpAndFlushCode(Map* map, HeapObject* object) {
1267
    Heap* heap = map->GetHeap();
1268 1269
    MarkCompactCollector* collector = heap->mark_compact_collector();
    if (!collector->is_code_flushing_enabled()) {
1270
      VisitJSRegExp(map, object);
1271 1272 1273
      return;
    }
    JSRegExp* re = reinterpret_cast<JSRegExp*>(object);
1274
    // Flush code or set age on both ASCII and two byte code.
1275 1276 1277
    UpdateRegExpCodeAgeAndFlush(heap, re, true);
    UpdateRegExpCodeAgeAndFlush(heap, re, false);
    // Visit the fields of the RegExp, including the updated FixedArray.
1278
    VisitJSRegExp(map, object);
1279 1280
  }

1281
  static VisitorDispatchTable<Callback> non_count_table_;
1282 1283 1284
};


1285
void MarkCompactMarkingVisitor::ObjectStatsCountFixedArray(
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    FixedArrayBase* fixed_array,
    FixedArraySubInstanceType fast_type,
    FixedArraySubInstanceType dictionary_type) {
  Heap* heap = fixed_array->map()->GetHeap();
  if (fixed_array->map() != heap->fixed_cow_array_map() &&
      fixed_array->map() != heap->fixed_double_array_map() &&
      fixed_array != heap->empty_fixed_array()) {
    if (fixed_array->IsDictionary()) {
      heap->RecordObjectStats(FIXED_ARRAY_TYPE,
                              dictionary_type,
                              fixed_array->Size());
    } else {
      heap->RecordObjectStats(FIXED_ARRAY_TYPE,
                              fast_type,
                              fixed_array->Size());
    }
  }
}


1306 1307
void MarkCompactMarkingVisitor::ObjectStatsVisitBase(
    MarkCompactMarkingVisitor::VisitorId id, Map* map, HeapObject* obj) {
1308 1309 1310
  Heap* heap = map->GetHeap();
  int object_size = obj->Size();
  heap->RecordObjectStats(map->instance_type(), -1, object_size);
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
  non_count_table_.GetVisitorById(id)(map, obj);
  if (obj->IsJSObject()) {
    JSObject* object = JSObject::cast(obj);
    ObjectStatsCountFixedArray(object->elements(),
                               DICTIONARY_ELEMENTS_SUB_TYPE,
                               FAST_ELEMENTS_SUB_TYPE);
    ObjectStatsCountFixedArray(object->properties(),
                               DICTIONARY_PROPERTIES_SUB_TYPE,
                               FAST_PROPERTIES_SUB_TYPE);
  }
}


1324 1325
template<MarkCompactMarkingVisitor::VisitorId id>
void MarkCompactMarkingVisitor::ObjectStatsTracker<id>::Visit(
1326 1327
    Map* map, HeapObject* obj) {
  ObjectStatsVisitBase(id, map, obj);
1328 1329 1330
}


1331
template<>
1332 1333
class MarkCompactMarkingVisitor::ObjectStatsTracker<
    MarkCompactMarkingVisitor::kVisitMap> {
1334 1335 1336 1337 1338 1339
 public:
  static inline void Visit(Map* map, HeapObject* obj) {
    Heap* heap = map->GetHeap();
    Map* map_obj = Map::cast(obj);
    ASSERT(map->instance_type() == MAP_TYPE);
    DescriptorArray* array = map_obj->instance_descriptors();
1340 1341
    if (map_obj->owns_descriptors() &&
        array != heap->empty_descriptor_array()) {
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
      int fixed_array_size = array->Size();
      heap->RecordObjectStats(FIXED_ARRAY_TYPE,
                              DESCRIPTOR_ARRAY_SUB_TYPE,
                              fixed_array_size);
    }
    if (map_obj->HasTransitionArray()) {
      int fixed_array_size = map_obj->transitions()->Size();
      heap->RecordObjectStats(FIXED_ARRAY_TYPE,
                              TRANSITION_ARRAY_SUB_TYPE,
                              fixed_array_size);
    }
    if (map_obj->code_cache() != heap->empty_fixed_array()) {
      heap->RecordObjectStats(
          FIXED_ARRAY_TYPE,
          MAP_CODE_CACHE_SUB_TYPE,
          FixedArray::cast(map_obj->code_cache())->Size());
    }
    ObjectStatsVisitBase(kVisitMap, map, obj);
  }
};


1364
template<>
1365 1366
class MarkCompactMarkingVisitor::ObjectStatsTracker<
    MarkCompactMarkingVisitor::kVisitCode> {
1367 1368 1369 1370 1371 1372
 public:
  static inline void Visit(Map* map, HeapObject* obj) {
    Heap* heap = map->GetHeap();
    int object_size = obj->Size();
    ASSERT(map->instance_type() == CODE_TYPE);
    heap->RecordObjectStats(CODE_TYPE, Code::cast(obj)->kind(), object_size);
1373 1374 1375 1376 1377 1378
    ObjectStatsVisitBase(kVisitCode, map, obj);
  }
};


template<>
1379 1380
class MarkCompactMarkingVisitor::ObjectStatsTracker<
    MarkCompactMarkingVisitor::kVisitSharedFunctionInfo> {
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
 public:
  static inline void Visit(Map* map, HeapObject* obj) {
    Heap* heap = map->GetHeap();
    SharedFunctionInfo* sfi = SharedFunctionInfo::cast(obj);
    if (sfi->scope_info() != heap->empty_fixed_array()) {
      heap->RecordObjectStats(
          FIXED_ARRAY_TYPE,
          SCOPE_INFO_SUB_TYPE,
          FixedArray::cast(sfi->scope_info())->Size());
    }
    ObjectStatsVisitBase(kVisitSharedFunctionInfo, map, obj);
  }
};


template<>
1397 1398
class MarkCompactMarkingVisitor::ObjectStatsTracker<
    MarkCompactMarkingVisitor::kVisitFixedArray> {
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
 public:
  static inline void Visit(Map* map, HeapObject* obj) {
    Heap* heap = map->GetHeap();
    FixedArray* fixed_array = FixedArray::cast(obj);
    if (fixed_array == heap->symbol_table()) {
      heap->RecordObjectStats(
          FIXED_ARRAY_TYPE,
          SYMBOL_TABLE_SUB_TYPE,
          fixed_array->Size());
    }
    ObjectStatsVisitBase(kVisitFixedArray, map, obj);
1410 1411 1412 1413
  }
};


1414 1415
void MarkCompactMarkingVisitor::Initialize() {
  StaticMarkingVisitor<MarkCompactMarkingVisitor>::Initialize();
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430

  table_.Register(kVisitJSRegExp,
                  &VisitRegExpAndFlushCode);

  if (FLAG_track_gc_object_stats) {
    // Copy the visitor table to make call-through possible.
    non_count_table_.CopyFrom(&table_);
#define VISITOR_ID_COUNT_FUNCTION(id)                                   \
    table_.Register(kVisit##id, ObjectStatsTracker<kVisit##id>::Visit);
    VISITOR_ID_LIST(VISITOR_ID_COUNT_FUNCTION)
#undef VISITOR_ID_COUNT_FUNCTION
  }
}


1431 1432
VisitorDispatchTable<MarkCompactMarkingVisitor::Callback>
    MarkCompactMarkingVisitor::non_count_table_;
1433 1434 1435 1436


class MarkingVisitor : public ObjectVisitor {
 public:
1437 1438
  explicit MarkingVisitor(Heap* heap) : heap_(heap) { }

1439
  void VisitPointer(Object** p) {
1440
    MarkCompactMarkingVisitor::VisitPointer(heap_, p);
1441 1442
  }

1443 1444
  void VisitPointers(Object** start, Object** end) {
    MarkCompactMarkingVisitor::VisitPointers(heap_, start, end);
1445 1446
  }

1447 1448
 private:
  Heap* heap_;
1449 1450 1451
};


1452 1453
class CodeMarkingVisitor : public ThreadVisitor {
 public:
1454 1455 1456
  explicit CodeMarkingVisitor(MarkCompactCollector* collector)
      : collector_(collector) {}

1457
  void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1458
    collector_->PrepareThreadForCodeFlushing(isolate, top);
1459
  }
1460 1461 1462

 private:
  MarkCompactCollector* collector_;
1463 1464 1465 1466 1467
};


class SharedFunctionInfoMarkingVisitor : public ObjectVisitor {
 public:
1468 1469 1470
  explicit SharedFunctionInfoMarkingVisitor(MarkCompactCollector* collector)
      : collector_(collector) {}

1471 1472
  void VisitPointers(Object** start, Object** end) {
    for (Object** p = start; p < end; p++) VisitPointer(p);
1473 1474 1475 1476
  }

  void VisitPointer(Object** slot) {
    Object* obj = *slot;
1477 1478
    if (obj->IsSharedFunctionInfo()) {
      SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(obj);
1479
      MarkBit shared_mark = Marking::MarkBitFrom(shared);
1480 1481
      MarkBit code_mark = Marking::MarkBitFrom(shared->code());
      collector_->MarkObject(shared->code(), code_mark);
1482
      collector_->MarkObject(shared, shared_mark);
1483 1484
    }
  }
1485 1486 1487

 private:
  MarkCompactCollector* collector_;
1488 1489 1490
};


1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
void MarkCompactCollector::PrepareThreadForCodeFlushing(Isolate* isolate,
                                                        ThreadLocalTop* top) {
  for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
    // Note: for the frame that has a pending lazy deoptimization
    // StackFrame::unchecked_code will return a non-optimized code object for
    // the outermost function and StackFrame::LookupCode will return
    // actual optimized code object.
    StackFrame* frame = it.frame();
    Code* code = frame->unchecked_code();
    MarkBit code_mark = Marking::MarkBitFrom(code);
    MarkObject(code, code_mark);
    if (frame->is_optimized()) {
1503 1504
      MarkCompactMarkingVisitor::MarkInlinedFunctionsCode(heap(),
                                                          frame->LookupCode());
1505 1506 1507 1508 1509
    }
  }
}


1510
void MarkCompactCollector::PrepareForCodeFlushing() {
1511
  ASSERT(heap() == Isolate::Current()->heap());
1512

1513 1514 1515 1516 1517
  // Enable code flushing for non-incremental cycles.
  if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
    EnableCodeFlushing(!was_marked_incrementally_);
  }

1518 1519
  // If code flushing is disabled, there is no need to prepare for it.
  if (!is_code_flushing_enabled()) return;
1520

1521 1522
  // Ensure that empty descriptor array is marked. Method MarkDescriptorArray
  // relies on it being marked before any other descriptor array.
1523 1524 1525
  HeapObject* descriptor_array = heap()->empty_descriptor_array();
  MarkBit descriptor_array_mark = Marking::MarkBitFrom(descriptor_array);
  MarkObject(descriptor_array, descriptor_array_mark);
1526

1527
  // Make sure we are not referencing the code from the stack.
1528
  ASSERT(this == heap()->mark_compact_collector());
1529 1530
  PrepareThreadForCodeFlushing(heap()->isolate(),
                               heap()->isolate()->thread_local_top());
1531 1532 1533

  // Iterate the archived stacks in all threads to check if
  // the code is referenced.
1534
  CodeMarkingVisitor code_marking_visitor(this);
1535
  heap()->isolate()->thread_manager()->IterateArchivedThreads(
1536
      &code_marking_visitor);
1537

1538
  SharedFunctionInfoMarkingVisitor visitor(this);
1539 1540
  heap()->isolate()->compilation_cache()->IterateFunctions(&visitor);
  heap()->isolate()->handle_scope_implementer()->Iterate(&visitor);
1541

1542
  ProcessMarkingDeque();
1543 1544 1545
}


1546 1547 1548
// Visitor class for marking heap roots.
class RootMarkingVisitor : public ObjectVisitor {
 public:
1549 1550 1551
  explicit RootMarkingVisitor(Heap* heap)
    : collector_(heap->mark_compact_collector()) { }

1552 1553 1554 1555
  void VisitPointer(Object** p) {
    MarkObjectByPointer(p);
  }

1556 1557
  void VisitPointers(Object** start, Object** end) {
    for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
1558 1559 1560 1561 1562 1563 1564 1565
  }

 private:
  void MarkObjectByPointer(Object** p) {
    if (!(*p)->IsHeapObject()) return;

    // Replace flat cons strings in place.
    HeapObject* object = ShortCircuitConsString(p);
1566 1567
    MarkBit mark_bit = Marking::MarkBitFrom(object);
    if (mark_bit.Get()) return;
1568 1569 1570

    Map* map = object->map();
    // Mark the object.
1571
    collector_->SetMark(object, mark_bit);
1572

1573
    // Mark the map pointer and body, and push them on the marking stack.
1574 1575
    MarkBit map_mark = Marking::MarkBitFrom(map);
    collector_->MarkObject(map, map_mark);
1576
    MarkCompactMarkingVisitor::IterateBody(map, object);
1577 1578 1579

    // Mark all the objects reachable from the map and body.  May leave
    // overflowed objects in the heap.
1580
    collector_->EmptyMarkingDeque();
1581
  }
1582 1583

  MarkCompactCollector* collector_;
1584 1585 1586
};


1587 1588 1589
// Helper class for pruning the symbol table.
class SymbolTableCleaner : public ObjectVisitor {
 public:
1590 1591
  explicit SymbolTableCleaner(Heap* heap)
    : heap_(heap), pointers_removed_(0) { }
1592

1593 1594 1595
  virtual void VisitPointers(Object** start, Object** end) {
    // Visit all HeapObject pointers in [start, end).
    for (Object** p = start; p < end; p++) {
1596 1597 1598
      Object* o = *p;
      if (o->IsHeapObject() &&
          !Marking::MarkBitFrom(HeapObject::cast(o)).Get()) {
1599 1600 1601 1602 1603
        // Check if the symbol being pruned is an external symbol. We need to
        // delete the associated external data as this symbol is going away.

        // Since no objects have yet been moved we can safely access the map of
        // the object.
1604
        if (o->IsExternalString()) {
1605
          heap_->FinalizeExternalString(String::cast(*p));
1606
        }
1607 1608
        // Set the entry to the_hole_value (as deleted).
        *p = heap_->the_hole_value();
1609 1610 1611 1612 1613 1614 1615 1616
        pointers_removed_++;
      }
    }
  }

  int PointersRemoved() {
    return pointers_removed_;
  }
1617

1618
 private:
1619
  Heap* heap_;
1620 1621 1622 1623
  int pointers_removed_;
};


1624 1625 1626 1627 1628
// Implementation of WeakObjectRetainer for mark compact GCs. All marked objects
// are retained.
class MarkCompactWeakObjectRetainer : public WeakObjectRetainer {
 public:
  virtual Object* RetainAs(Object* object) {
1629
    if (Marking::MarkBitFrom(HeapObject::cast(object)).Get()) {
1630 1631 1632 1633 1634 1635 1636 1637
      return object;
    } else {
      return NULL;
    }
  }
};


1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
// Fill the marking stack with overflowed objects returned by the given
// iterator.  Stop when the marking stack is filled or the end of the space
// is reached, whichever comes first.
template<class T>
static void DiscoverGreyObjectsWithIterator(Heap* heap,
                                            MarkingDeque* marking_deque,
                                            T* it) {
  // The caller should ensure that the marking stack is initially not full,
  // so that we don't waste effort pointlessly scanning for objects.
  ASSERT(!marking_deque->IsFull());

  Map* filler_map = heap->one_pointer_filler_map();
  for (HeapObject* object = it->Next();
       object != NULL;
       object = it->Next()) {
    MarkBit markbit = Marking::MarkBitFrom(object);
    if ((object->map() != filler_map) && Marking::IsGrey(markbit)) {
      Marking::GreyToBlack(markbit);
1656
      MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
      marking_deque->PushBlack(object);
      if (marking_deque->IsFull()) return;
    }
  }
}


static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts);


static void DiscoverGreyObjectsOnPage(MarkingDeque* marking_deque, Page* p) {
1668
  ASSERT(!marking_deque->IsFull());
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
  ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
  ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
  ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
  ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);

  MarkBit::CellType* cells = p->markbits()->cells();

  int last_cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
1679 1680 1681 1682 1683 1684
              p->AddressToMarkbitIndex(p->area_end())));

  Address cell_base = p->area_start();
  int cell_index = Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
              p->AddressToMarkbitIndex(cell_base)));
1685 1686


1687
  for (;
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
       cell_index < last_cell_index;
       cell_index++, cell_base += 32 * kPointerSize) {
    ASSERT((unsigned)cell_index ==
        Bitmap::IndexToCell(
            Bitmap::CellAlignIndex(
                p->AddressToMarkbitIndex(cell_base))));

    const MarkBit::CellType current_cell = cells[cell_index];
    if (current_cell == 0) continue;

    const MarkBit::CellType next_cell = cells[cell_index + 1];
    MarkBit::CellType grey_objects = current_cell &
        ((current_cell >> 1) | (next_cell << (Bitmap::kBitsPerCell - 1)));

    int offset = 0;
    while (grey_objects != 0) {
      int trailing_zeros = CompilerIntrinsics::CountTrailingZeros(grey_objects);
      grey_objects >>= trailing_zeros;
      offset += trailing_zeros;
      MarkBit markbit(&cells[cell_index], 1 << offset, false);
      ASSERT(Marking::IsGrey(markbit));
      Marking::GreyToBlack(markbit);
      Address addr = cell_base + offset * kPointerSize;
1711
      HeapObject* object = HeapObject::FromAddress(addr);
1712
      MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1713
      marking_deque->PushBlack(object);
1714 1715 1716 1717 1718 1719 1720
      if (marking_deque->IsFull()) return;
      offset += 2;
      grey_objects >>= 2;
    }

    grey_objects >>= (Bitmap::kBitsPerCell - 1);
  }
1721 1722 1723
}


1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
static void DiscoverGreyObjectsInSpace(Heap* heap,
                                       MarkingDeque* marking_deque,
                                       PagedSpace* space) {
  if (!space->was_swept_conservatively()) {
    HeapObjectIterator it(space);
    DiscoverGreyObjectsWithIterator(heap, marking_deque, &it);
  } else {
    PageIterator it(space);
    while (it.has_next()) {
      Page* p = it.next();
      DiscoverGreyObjectsOnPage(marking_deque, p);
      if (marking_deque->IsFull()) return;
1736 1737
    }
  }
1738
}
1739 1740


1741
bool MarkCompactCollector::IsUnmarkedHeapObject(Object** p) {
1742 1743 1744 1745 1746
  Object* o = *p;
  if (!o->IsHeapObject()) return false;
  HeapObject* heap_object = HeapObject::cast(o);
  MarkBit mark = Marking::MarkBitFrom(heap_object);
  return !mark.Get();
1747 1748 1749
}


1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
bool MarkCompactCollector::IsUnmarkedHeapObjectWithHeap(Heap* heap,
                                                        Object** p) {
  Object* o = *p;
  ASSERT(o->IsHeapObject());
  HeapObject* heap_object = HeapObject::cast(o);
  MarkBit mark = Marking::MarkBitFrom(heap_object);
  return !mark.Get();
}


1760
void MarkCompactCollector::MarkSymbolTable() {
1761
  SymbolTable* symbol_table = heap()->symbol_table();
1762
  // Mark the symbol table itself.
1763 1764
  MarkBit symbol_table_mark = Marking::MarkBitFrom(symbol_table);
  SetMark(symbol_table, symbol_table_mark);
1765
  // Explicitly mark the prefix.
1766
  MarkingVisitor marker(heap());
1767
  symbol_table->IteratePrefix(&marker);
1768
  ProcessMarkingDeque();
1769 1770
}

1771

1772
void MarkCompactCollector::MarkRoots(RootMarkingVisitor* visitor) {
1773 1774
  // Mark the heap roots including global variables, stack variables,
  // etc., and all objects reachable from them.
1775
  heap()->IterateStrongRoots(visitor, VISIT_ONLY_STRONG);
1776

1777 1778 1779
  // Handle the symbol table specially.
  MarkSymbolTable();

1780
  // There may be overflowed objects in the heap.  Visit them now.
1781 1782 1783
  while (marking_deque_.overflowed()) {
    RefillMarkingDeque();
    EmptyMarkingDeque();
1784
  }
1785 1786 1787
}


1788
void MarkCompactCollector::MarkImplicitRefGroups() {
1789
  List<ImplicitRefGroup*>* ref_groups =
1790
      heap()->isolate()->global_handles()->implicit_ref_groups();
1791

1792
  int last = 0;
1793 1794
  for (int i = 0; i < ref_groups->length(); i++) {
    ImplicitRefGroup* entry = ref_groups->at(i);
1795
    ASSERT(entry != NULL);
1796

1797
    if (!IsMarked(*entry->parent_)) {
1798 1799 1800
      (*ref_groups)[last++] = entry;
      continue;
    }
1801

1802 1803 1804
    Object*** children = entry->children_;
    // A parent object is marked, so mark all child heap objects.
    for (size_t j = 0; j < entry->length_; ++j) {
1805
      if ((*children[j])->IsHeapObject()) {
1806 1807 1808
        HeapObject* child = HeapObject::cast(*children[j]);
        MarkBit mark = Marking::MarkBitFrom(child);
        MarkObject(child, mark);
1809 1810 1811
      }
    }

1812 1813 1814
    // Once the entire group has been marked, dispose it because it's
    // not needed anymore.
    entry->Dispose();
1815
  }
1816
  ref_groups->Rewind(last);
1817 1818 1819
}


1820 1821 1822 1823
// Mark all objects reachable from the objects on the marking stack.
// Before: the marking stack contains zero or more heap object pointers.
// After: the marking stack is empty, and all objects reachable from the
// marking stack have been marked, or are overflowed in the heap.
1824 1825 1826 1827
void MarkCompactCollector::EmptyMarkingDeque() {
  while (!marking_deque_.IsEmpty()) {
    while (!marking_deque_.IsEmpty()) {
      HeapObject* object = marking_deque_.Pop();
1828 1829
      ASSERT(object->IsHeapObject());
      ASSERT(heap()->Contains(object));
1830
      ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
1831

1832 1833 1834
      Map* map = object->map();
      MarkBit map_mark = Marking::MarkBitFrom(map);
      MarkObject(map, map_mark);
1835

1836
      MarkCompactMarkingVisitor::IterateBody(map, object);
1837
    }
1838

1839 1840 1841
    // Process encountered weak maps, mark objects only reachable by those
    // weak maps and repeat until fix-point is reached.
    ProcessWeakMaps();
1842 1843 1844
  }
}

1845

1846 1847 1848 1849 1850
// Sweep the heap for overflowed objects, clear their overflow bits, and
// push them on the marking stack.  Stop early if the marking stack fills
// before sweeping completes.  If sweeping completes, there are no remaining
// overflowed objects in the heap so the overflow flag on the markings stack
// is cleared.
1851 1852
void MarkCompactCollector::RefillMarkingDeque() {
  ASSERT(marking_deque_.overflowed());
1853

1854 1855 1856
  SemiSpaceIterator new_it(heap()->new_space());
  DiscoverGreyObjectsWithIterator(heap(), &marking_deque_, &new_it);
  if (marking_deque_.IsFull()) return;
1857

1858 1859 1860 1861
  DiscoverGreyObjectsInSpace(heap(),
                             &marking_deque_,
                             heap()->old_pointer_space());
  if (marking_deque_.IsFull()) return;
1862

1863 1864 1865 1866
  DiscoverGreyObjectsInSpace(heap(),
                             &marking_deque_,
                             heap()->old_data_space());
  if (marking_deque_.IsFull()) return;
1867

1868 1869 1870 1871
  DiscoverGreyObjectsInSpace(heap(),
                             &marking_deque_,
                             heap()->code_space());
  if (marking_deque_.IsFull()) return;
1872

1873 1874 1875 1876
  DiscoverGreyObjectsInSpace(heap(),
                             &marking_deque_,
                             heap()->map_space());
  if (marking_deque_.IsFull()) return;
1877

1878 1879 1880 1881
  DiscoverGreyObjectsInSpace(heap(),
                             &marking_deque_,
                             heap()->cell_space());
  if (marking_deque_.IsFull()) return;
1882

1883 1884 1885 1886 1887
  LargeObjectIterator lo_it(heap()->lo_space());
  DiscoverGreyObjectsWithIterator(heap(),
                                  &marking_deque_,
                                  &lo_it);
  if (marking_deque_.IsFull()) return;
1888

1889
  marking_deque_.ClearOverflowed();
1890 1891 1892 1893 1894 1895 1896
}


// Mark all objects reachable (transitively) from objects on the marking
// stack.  Before: the marking stack contains zero or more heap object
// pointers.  After: the marking stack is empty and there are no overflowed
// objects in the heap.
1897 1898 1899 1900 1901
void MarkCompactCollector::ProcessMarkingDeque() {
  EmptyMarkingDeque();
  while (marking_deque_.overflowed()) {
    RefillMarkingDeque();
    EmptyMarkingDeque();
1902
  }
1903 1904 1905
}


1906
void MarkCompactCollector::ProcessExternalMarking(RootMarkingVisitor* visitor) {
1907
  bool work_to_do = true;
1908
  ASSERT(marking_deque_.IsEmpty());
1909
  while (work_to_do) {
1910 1911
    heap()->isolate()->global_handles()->IterateObjectGroups(
        visitor, &IsUnmarkedHeapObjectWithHeap);
1912
    MarkImplicitRefGroups();
1913 1914
    work_to_do = !marking_deque_.IsEmpty();
    ProcessMarkingDeque();
1915 1916 1917 1918 1919
  }
}


void MarkCompactCollector::MarkLiveObjects() {
1920
  GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_MARK);
1921 1922 1923
  // The recursive GC marker detects when it is nearing stack overflow,
  // and switches to a different marking system.  JS interrupts interfere
  // with the C stack limit check.
1924
  PostponeInterruptsScope postpone(heap()->isolate());
1925

1926 1927
  bool incremental_marking_overflowed = false;
  IncrementalMarking* incremental_marking = heap_->incremental_marking();
1928
  if (was_marked_incrementally_) {
1929 1930 1931 1932 1933
    // Finalize the incremental marking and check whether we had an overflow.
    // Both markers use grey color to mark overflowed objects so
    // non-incremental marker can deal with them as if overflow
    // occured during normal marking.
    // But incremental marker uses a separate marking deque
1934
    // so we have to explicitly copy its overflow state.
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    incremental_marking->Finalize();
    incremental_marking_overflowed =
        incremental_marking->marking_deque()->overflowed();
    incremental_marking->marking_deque()->ClearOverflowed();
  } else {
    // Abort any pending incremental activities e.g. incremental sweeping.
    incremental_marking->Abort();
  }

#ifdef DEBUG
  ASSERT(state_ == PREPARE_GC);
1946 1947
  state_ = MARK_LIVE_OBJECTS;
#endif
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
  // The to space contains live objects, a page in from space is used as a
  // marking stack.
  Address marking_deque_start = heap()->new_space()->FromSpacePageLow();
  Address marking_deque_end = heap()->new_space()->FromSpacePageHigh();
  if (FLAG_force_marking_deque_overflows) {
    marking_deque_end = marking_deque_start + 64 * kPointerSize;
  }
  marking_deque_.Initialize(marking_deque_start,
                            marking_deque_end);
  ASSERT(!marking_deque_.overflowed());
1958

1959 1960 1961 1962
  if (incremental_marking_overflowed) {
    // There are overflowed objects left in the heap after incremental marking.
    marking_deque_.SetOverflowed();
  }
1963

1964 1965
  PrepareForCodeFlushing();

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
  if (was_marked_incrementally_) {
    // There is no write barrier on cells so we have to scan them now at the end
    // of the incremental marking.
    {
      HeapObjectIterator cell_iterator(heap()->cell_space());
      HeapObject* cell;
      while ((cell = cell_iterator.Next()) != NULL) {
        ASSERT(cell->IsJSGlobalPropertyCell());
        if (IsMarked(cell)) {
          int offset = JSGlobalPropertyCell::kValueOffset;
1976
          MarkCompactMarkingVisitor::VisitPointer(
1977 1978 1979 1980 1981 1982 1983
              heap(),
              reinterpret_cast<Object**>(cell->address() + offset));
        }
      }
    }
  }

1984
  RootMarkingVisitor root_visitor(heap());
1985
  MarkRoots(&root_visitor);
1986

1987
  // The objects reachable from the roots are marked, yet unreachable
1988 1989
  // objects are unmarked.  Mark objects reachable due to host
  // application specific logic.
1990
  ProcessExternalMarking(&root_visitor);
1991

1992 1993 1994
  // The objects reachable from the roots or object groups are marked,
  // yet unreachable objects are unmarked.  Mark objects reachable
  // only from weak global handles.
1995
  //
1996 1997
  // First we identify nonlive weak handles and mark them as pending
  // destruction.
1998
  heap()->isolate()->global_handles()->IdentifyWeakHandles(
1999
      &IsUnmarkedHeapObject);
2000
  // Then we mark the objects and process the transitive closure.
2001
  heap()->isolate()->global_handles()->IterateWeakRoots(&root_visitor);
2002 2003 2004
  while (marking_deque_.overflowed()) {
    RefillMarkingDeque();
    EmptyMarkingDeque();
2005
  }
2006

2007 2008
  // Repeat host application specific marking to mark unmarked objects
  // reachable from the weak roots.
2009
  ProcessExternalMarking(&root_visitor);
2010

2011 2012 2013 2014 2015
  AfterMarking();
}


void MarkCompactCollector::AfterMarking() {
2016 2017 2018 2019 2020 2021
  // Object literal map caches reference symbols (cache keys) and maps
  // (cache values). At this point still useful maps have already been
  // marked. Mark the keys for the alive values before we process the
  // symbol table.
  ProcessMapCaches();

2022
  // Prune the symbol table removing all symbols only pointed to by the
2023
  // symbol table.  Cannot use symbol_table() here because the symbol
2024
  // table is marked.
2025
  SymbolTable* symbol_table = heap()->symbol_table();
2026
  SymbolTableCleaner v(heap());
2027 2028
  symbol_table->IterateElements(&v);
  symbol_table->ElementsRemoved(v.PointersRemoved());
2029 2030
  heap()->external_string_table_.Iterate(&v);
  heap()->external_string_table_.CleanUp();
2031
  heap()->error_object_list_.RemoveUnmarked(heap());
2032

2033 2034
  // Process the weak references.
  MarkCompactWeakObjectRetainer mark_compact_object_retainer;
2035
  heap()->ProcessWeakReferences(&mark_compact_object_retainer);
2036

2037
  // Remove object groups after marking phase.
2038 2039
  heap()->isolate()->global_handles()->RemoveObjectGroups();
  heap()->isolate()->global_handles()->RemoveImplicitRefGroups();
2040 2041

  // Flush code from collected candidates.
2042 2043
  if (is_code_flushing_enabled()) {
    code_flusher_->ProcessCandidates();
2044 2045 2046 2047 2048
    // If incremental marker does not support code flushing, we need to
    // disable it before incremental marking steps for next cycle.
    if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
      EnableCodeFlushing(false);
    }
2049
  }
2050

2051
  if (!FLAG_watch_ic_patching) {
2052 2053 2054
    // Clean up dead objects from the runtime profiler.
    heap()->isolate()->runtime_profiler()->RemoveDeadSamples();
  }
2055 2056 2057 2058

  if (FLAG_track_gc_object_stats) {
    heap()->CheckpointObjectStats();
  }
2059 2060 2061
}


2062
void MarkCompactCollector::ProcessMapCaches() {
2063
  Object* raw_context = heap()->native_contexts_list_;
2064 2065
  while (raw_context != heap()->undefined_value()) {
    Context* context = reinterpret_cast<Context*>(raw_context);
2066
    if (IsMarked(context)) {
2067 2068 2069 2070 2071
      HeapObject* raw_map_cache =
          HeapObject::cast(context->get(Context::MAP_CACHE_INDEX));
      // A map cache may be reachable from the stack. In this case
      // it's already transitively marked and it's too late to clean
      // up its parts.
2072
      if (!IsMarked(raw_map_cache) &&
2073 2074 2075 2076 2077 2078 2079 2080 2081
          raw_map_cache != heap()->undefined_value()) {
        MapCache* map_cache = reinterpret_cast<MapCache*>(raw_map_cache);
        int existing_elements = map_cache->NumberOfElements();
        int used_elements = 0;
        for (int i = MapCache::kElementsStartIndex;
             i < map_cache->length();
             i += MapCache::kEntrySize) {
          Object* raw_key = map_cache->get(i);
          if (raw_key == heap()->undefined_value() ||
2082
              raw_key == heap()->the_hole_value()) continue;
2083 2084
          STATIC_ASSERT(MapCache::kEntrySize == 2);
          Object* raw_map = map_cache->get(i + 1);
2085
          if (raw_map->IsHeapObject() && IsMarked(raw_map)) {
2086 2087 2088 2089
            ++used_elements;
          } else {
            // Delete useless entries with unmarked maps.
            ASSERT(raw_map->IsMap());
2090 2091
            map_cache->set_the_hole(i);
            map_cache->set_the_hole(i + 1);
2092 2093 2094 2095 2096 2097 2098 2099 2100
          }
        }
        if (used_elements == 0) {
          context->set(Context::MAP_CACHE_INDEX, heap()->undefined_value());
        } else {
          // Note: we don't actually shrink the cache here to avoid
          // extra complexity during GC. We rely on subsequent cache
          // usages (EnsureCapacity) to do this.
          map_cache->ElementsRemoved(existing_elements - used_elements);
2101 2102
          MarkBit map_cache_markbit = Marking::MarkBitFrom(map_cache);
          MarkObject(map_cache, map_cache_markbit);
2103 2104 2105 2106 2107 2108
        }
      }
    }
    // Move to next element in the list.
    raw_context = context->get(Context::NEXT_CONTEXT_LINK);
  }
2109
  ProcessMarkingDeque();
2110 2111 2112
}


2113 2114 2115 2116 2117 2118 2119
void MarkCompactCollector::ReattachInitialMaps() {
  HeapObjectIterator map_iterator(heap()->map_space());
  for (HeapObject* obj = map_iterator.Next();
       obj != NULL;
       obj = map_iterator.Next()) {
    if (obj->IsFreeSpace()) continue;
    Map* map = Map::cast(obj);
2120

2121
    STATIC_ASSERT(LAST_TYPE == LAST_JS_RECEIVER_TYPE);
2122
    if (map->instance_type() < FIRST_JS_RECEIVER_TYPE) continue;
2123

2124 2125 2126 2127
    if (map->attached_to_shared_function_info()) {
      JSFunction::cast(map->constructor())->shared()->AttachInitialMap(map);
    }
  }
2128 2129
}

2130

2131
void MarkCompactCollector::ClearNonLiveTransitions() {
2132
  HeapObjectIterator map_iterator(heap()->map_space());
2133
  // Iterate over the map space, setting map transitions that go from
2134 2135
  // a marked map to an unmarked map to null transitions.  This action
  // is carried out only on maps of JSObjects and related subtypes.
2136 2137
  for (HeapObject* obj = map_iterator.Next();
       obj != NULL; obj = map_iterator.Next()) {
2138
    Map* map = reinterpret_cast<Map*>(obj);
2139 2140
    MarkBit map_mark = Marking::MarkBitFrom(map);
    if (map->IsFreeSpace()) continue;
2141

2142
    ASSERT(map->IsMap());
2143
    // Only JSObject and subtypes have map transitions and back pointers.
2144 2145
    STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
    if (map->instance_type() < FIRST_JS_OBJECT_TYPE) continue;
2146

2147 2148
    if (map_mark.Get() &&
        map->attached_to_shared_function_info()) {
2149 2150 2151 2152 2153 2154
      // This map is used for inobject slack tracking and has been detached
      // from SharedFunctionInfo during the mark phase.
      // Since it survived the GC, reattach it now.
      map->unchecked_constructor()->unchecked_shared()->AttachInitialMap(map);
    }

2155 2156 2157 2158 2159 2160 2161 2162
    ClearNonLivePrototypeTransitions(map);
    ClearNonLiveMapTransitions(map, map_mark);
  }
}


void MarkCompactCollector::ClearNonLivePrototypeTransitions(Map* map) {
  int number_of_transitions = map->NumberOfProtoTransitions();
2163
  FixedArray* prototype_transitions = map->GetPrototypeTransitions();
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186

  int new_number_of_transitions = 0;
  const int header = Map::kProtoTransitionHeaderSize;
  const int proto_offset = header + Map::kProtoTransitionPrototypeOffset;
  const int map_offset = header + Map::kProtoTransitionMapOffset;
  const int step = Map::kProtoTransitionElementsPerEntry;
  for (int i = 0; i < number_of_transitions; i++) {
    Object* prototype = prototype_transitions->get(proto_offset + i * step);
    Object* cached_map = prototype_transitions->get(map_offset + i * step);
    if (IsMarked(prototype) && IsMarked(cached_map)) {
      int proto_index = proto_offset + new_number_of_transitions * step;
      int map_index = map_offset + new_number_of_transitions * step;
      if (new_number_of_transitions != i) {
        prototype_transitions->set_unchecked(
            heap_,
            proto_index,
            prototype,
            UPDATE_WRITE_BARRIER);
        prototype_transitions->set_unchecked(
            heap_,
            map_index,
            cached_map,
            SKIP_WRITE_BARRIER);
2187
      }
2188 2189 2190 2191 2192
      Object** slot =
          HeapObject::RawField(prototype_transitions,
                               FixedArray::OffsetOfElementAt(proto_index));
      RecordSlot(slot, slot, prototype);
      new_number_of_transitions++;
2193
    }
2194
  }
2195

2196 2197 2198
  if (new_number_of_transitions != number_of_transitions) {
    map->SetNumberOfProtoTransitions(new_number_of_transitions);
  }
2199

2200 2201 2202 2203 2204 2205 2206
  // Fill slots that became free with undefined value.
  for (int i = new_number_of_transitions * step;
       i < number_of_transitions * step;
       i++) {
    prototype_transitions->set_undefined(heap_, header + i);
  }
}
2207

2208

2209 2210
void MarkCompactCollector::ClearNonLiveMapTransitions(Map* map,
                                                      MarkBit map_mark) {
2211 2212 2213
  Object* potential_parent = map->GetBackPointer();
  if (!potential_parent->IsMap()) return;
  Map* parent = Map::cast(potential_parent);
2214

2215 2216
  // Follow back pointer, check whether we are dealing with a map transition
  // from a live map to a dead path and in case clear transitions of parent.
2217
  bool current_is_alive = map_mark.Get();
2218 2219 2220
  bool parent_is_alive = Marking::MarkBitFrom(parent).Get();
  if (!current_is_alive && parent_is_alive) {
    parent->ClearNonLiveTransitions(heap());
2221 2222
  }
}
2223

2224 2225 2226 2227

void MarkCompactCollector::ProcessWeakMaps() {
  Object* weak_map_obj = encountered_weak_maps();
  while (weak_map_obj != Smi::FromInt(0)) {
2228
    ASSERT(MarkCompactCollector::IsMarked(HeapObject::cast(weak_map_obj)));
2229
    JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(weak_map_obj);
2230
    ObjectHashTable* table = ObjectHashTable::cast(weak_map->table());
2231
    Object** anchor = reinterpret_cast<Object**>(table->address());
2232
    for (int i = 0; i < table->Capacity(); i++) {
2233
      if (MarkCompactCollector::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
2234 2235 2236 2237 2238 2239 2240
        Object** key_slot =
            HeapObject::RawField(table, FixedArray::OffsetOfElementAt(
                ObjectHashTable::EntryToIndex(i)));
        RecordSlot(anchor, key_slot, *key_slot);
        Object** value_slot =
            HeapObject::RawField(table, FixedArray::OffsetOfElementAt(
                ObjectHashTable::EntryToValueIndex(i)));
2241 2242
        MarkCompactMarkingVisitor::MarkObjectByPointer(
            this, anchor, value_slot);
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
      }
    }
    weak_map_obj = weak_map->next();
  }
}


void MarkCompactCollector::ClearWeakMaps() {
  Object* weak_map_obj = encountered_weak_maps();
  while (weak_map_obj != Smi::FromInt(0)) {
2253
    ASSERT(MarkCompactCollector::IsMarked(HeapObject::cast(weak_map_obj)));
2254
    JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(weak_map_obj);
2255
    ObjectHashTable* table = ObjectHashTable::cast(weak_map->table());
2256
    for (int i = 0; i < table->Capacity(); i++) {
2257
      if (!MarkCompactCollector::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
2258
        table->RemoveEntry(i);
2259 2260 2261 2262 2263 2264 2265 2266
      }
    }
    weak_map_obj = weak_map->next();
    weak_map->set_next(Smi::FromInt(0));
  }
  set_encountered_weak_maps(Smi::FromInt(0));
}

2267 2268 2269

// We scavange new space simultaneously with sweeping. This is done in two
// passes.
2270
//
2271 2272 2273 2274
// The first pass migrates all alive objects from one semispace to another or
// promotes them to old space.  Forwarding address is written directly into
// first word of object without any encoding.  If object is dead we write
// NULL as a forwarding address.
2275
//
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
// The second pass updates pointers to new space in all spaces.  It is possible
// to encounter pointers to dead new space objects during traversal of pointers
// to new space.  We should clear them to avoid encountering them during next
// pointer iteration.  This is an issue if the store buffer overflows and we
// have to scan the entire old space, including dead objects, looking for
// pointers to new space.
void MarkCompactCollector::MigrateObject(Address dst,
                                         Address src,
                                         int size,
                                         AllocationSpace dest) {
2286
  HEAP_PROFILE(heap(), ObjectMoveEvent(src, dst));
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
  if (dest == OLD_POINTER_SPACE || dest == LO_SPACE) {
    Address src_slot = src;
    Address dst_slot = dst;
    ASSERT(IsAligned(size, kPointerSize));

    for (int remaining = size / kPointerSize; remaining > 0; remaining--) {
      Object* value = Memory::Object_at(src_slot);

      Memory::Object_at(dst_slot) = value;

      if (heap_->InNewSpace(value)) {
        heap_->store_buffer()->Mark(dst_slot);
      } else if (value->IsHeapObject() && IsOnEvacuationCandidate(value)) {
        SlotsBuffer::AddTo(&slots_buffer_allocator_,
                           &migration_slots_buffer_,
                           reinterpret_cast<Object**>(dst_slot),
                           SlotsBuffer::IGNORE_OVERFLOW);
      }
2305

2306 2307
      src_slot += kPointerSize;
      dst_slot += kPointerSize;
2308
    }
2309

2310 2311 2312
    if (compacting_ && HeapObject::FromAddress(dst)->IsJSFunction()) {
      Address code_entry_slot = dst + JSFunction::kCodeEntryOffset;
      Address code_entry = Memory::Address_at(code_entry_slot);
2313

2314 2315 2316 2317 2318 2319
      if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
        SlotsBuffer::AddTo(&slots_buffer_allocator_,
                           &migration_slots_buffer_,
                           SlotsBuffer::CODE_ENTRY_SLOT,
                           code_entry_slot,
                           SlotsBuffer::IGNORE_OVERFLOW);
2320 2321
      }
    }
2322 2323 2324 2325 2326 2327 2328 2329 2330
  } else if (dest == CODE_SPACE) {
    PROFILE(heap()->isolate(), CodeMoveEvent(src, dst));
    heap()->MoveBlock(dst, src, size);
    SlotsBuffer::AddTo(&slots_buffer_allocator_,
                       &migration_slots_buffer_,
                       SlotsBuffer::RELOCATED_CODE_OBJECT,
                       dst,
                       SlotsBuffer::IGNORE_OVERFLOW);
    Code::cast(HeapObject::FromAddress(dst))->Relocate(dst - src);
2331
  } else {
2332 2333
    ASSERT(dest == OLD_DATA_SPACE || dest == NEW_SPACE);
    heap()->MoveBlock(dst, src, size);
2334
  }
2335 2336 2337 2338 2339 2340
  Memory::Address_at(src) = dst;
}


// Visitor for updating pointers from live objects in old spaces to new space.
// It does not expect to encounter pointers to dead objects.
2341
class PointersUpdatingVisitor: public ObjectVisitor {
2342
 public:
2343
  explicit PointersUpdatingVisitor(Heap* heap) : heap_(heap) { }
2344

2345
  void VisitPointer(Object** p) {
2346
    UpdatePointer(p);
2347 2348
  }

2349 2350
  void VisitPointers(Object** start, Object** end) {
    for (Object** p = start; p < end; p++) UpdatePointer(p);
2351 2352
  }

2353 2354 2355
  void VisitEmbeddedPointer(RelocInfo* rinfo) {
    ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
    Object* target = rinfo->target_object();
2356
    Object* old_target = target;
2357
    VisitPointer(&target);
2358 2359 2360 2361 2362
    // Avoid unnecessary changes that might unnecessary flush the instruction
    // cache.
    if (target != old_target) {
      rinfo->set_target_object(target);
    }
2363 2364
  }

2365 2366 2367
  void VisitCodeTarget(RelocInfo* rinfo) {
    ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
    Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
2368
    Object* old_target = target;
2369
    VisitPointer(&target);
2370 2371 2372
    if (target != old_target) {
      rinfo->set_target_address(Code::cast(target)->instruction_start());
    }
2373 2374
  }

2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
  void VisitCodeAgeSequence(RelocInfo* rinfo) {
    ASSERT(RelocInfo::IsCodeAgeSequence(rinfo->rmode()));
    Object* stub = rinfo->code_age_stub();
    ASSERT(stub != NULL);
    VisitPointer(&stub);
    if (stub != rinfo->code_age_stub()) {
      rinfo->set_code_age_stub(Code::cast(stub));
    }
  }

2385
  void VisitDebugTarget(RelocInfo* rinfo) {
2386 2387 2388 2389
    ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
            rinfo->IsPatchedReturnSequence()) ||
           (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
            rinfo->IsPatchedDebugBreakSlotSequence()));
2390 2391 2392 2393
    Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
    VisitPointer(&target);
    rinfo->set_call_address(Code::cast(target)->instruction_start());
  }
2394

2395 2396 2397 2398
  static inline void UpdateSlot(Heap* heap, Object** slot) {
    Object* obj = *slot;

    if (!obj->IsHeapObject()) return;
2399

2400
    HeapObject* heap_obj = HeapObject::cast(obj);
2401

2402
    MapWord map_word = heap_obj->map_word();
2403
    if (map_word.IsForwardingAddress()) {
2404 2405 2406 2407 2408 2409
      ASSERT(heap->InFromSpace(heap_obj) ||
             MarkCompactCollector::IsOnEvacuationCandidate(heap_obj));
      HeapObject* target = map_word.ToForwardingAddress();
      *slot = target;
      ASSERT(!heap->InFromSpace(target) &&
             !MarkCompactCollector::IsOnEvacuationCandidate(target));
2410 2411 2412
    }
  }

2413 2414 2415 2416 2417
 private:
  inline void UpdatePointer(Object** p) {
    UpdateSlot(heap_, p);
  }

2418
  Heap* heap_;
2419 2420
};

2421

2422 2423
static void UpdatePointer(HeapObject** p, HeapObject* object) {
  ASSERT(*p == object);
2424

2425
  Address old_addr = object->address();
2426 2427 2428

  Address new_addr = Memory::Address_at(old_addr);

2429 2430 2431 2432
  // The new space sweep will overwrite the map word of dead objects
  // with NULL. In this case we do not need to transfer this entry to
  // the store buffer which we are rebuilding.
  if (new_addr != NULL) {
2433
    *p = HeapObject::FromAddress(new_addr);
2434 2435 2436 2437
  } else {
    // We have to zap this pointer, because the store buffer may overflow later,
    // and then we have to scan the entire heap and we don't want to find
    // spurious newspace pointers in the old space.
2438 2439
    // TODO(mstarzinger): This was changed to a sentinel value to track down
    // rare crashes, change it back to Smi::FromInt(0) later.
2440
    *p = reinterpret_cast<HeapObject*>(Smi::FromInt(0x0f100d00 >> 1));  // flood
2441
  }
2442 2443 2444
}


2445 2446 2447 2448 2449 2450 2451 2452 2453
static String* UpdateReferenceInExternalStringTableEntry(Heap* heap,
                                                         Object** p) {
  MapWord map_word = HeapObject::cast(*p)->map_word();

  if (map_word.IsForwardingAddress()) {
    return String::cast(map_word.ToForwardingAddress());
  }

  return String::cast(*p);
2454 2455 2456
}


2457 2458
bool MarkCompactCollector::TryPromoteObject(HeapObject* object,
                                            int object_size) {
2459 2460
  Object* result;

2461
  if (object_size > Page::kMaxNonCodeHeapObjectSize) {
2462
    MaybeObject* maybe_result =
2463
        heap()->lo_space()->AllocateRaw(object_size, NOT_EXECUTABLE);
2464
    if (maybe_result->ToObject(&result)) {
2465
      HeapObject* target = HeapObject::cast(result);
2466 2467 2468 2469 2470
      MigrateObject(target->address(),
                    object->address(),
                    object_size,
                    LO_SPACE);
      heap()->mark_compact_collector()->tracer()->
2471
          increment_promoted_objects_size(object_size);
2472 2473 2474
      return true;
    }
  } else {
2475
    OldSpace* target_space = heap()->TargetSpace(object);
2476

2477 2478
    ASSERT(target_space == heap()->old_pointer_space() ||
           target_space == heap()->old_data_space());
2479 2480
    MaybeObject* maybe_result = target_space->AllocateRaw(object_size);
    if (maybe_result->ToObject(&result)) {
2481
      HeapObject* target = HeapObject::cast(result);
2482
      MigrateObject(target->address(),
2483 2484
                    object->address(),
                    object_size,
2485 2486
                    target_space->identity());
      heap()->mark_compact_collector()->tracer()->
2487
          increment_promoted_objects_size(object_size);
2488 2489 2490 2491 2492 2493 2494 2495
      return true;
    }
  }

  return false;
}


2496
void MarkCompactCollector::EvacuateNewSpace() {
2497 2498 2499 2500
  // There are soft limits in the allocation code, designed trigger a mark
  // sweep collection by failing allocations.  But since we are already in
  // a mark-sweep allocation, there is no sense in trying to trigger one.
  AlwaysAllocateScope scope;
2501 2502 2503
  heap()->CheckNewSpaceExpansionCriteria();

  NewSpace* new_space = heap()->new_space();
2504

2505 2506 2507
  // Store allocation range before flipping semispaces.
  Address from_bottom = new_space->bottom();
  Address from_top = new_space->top();
2508 2509 2510

  // Flip the semispaces.  After flipping, to space is empty, from space has
  // live objects.
2511 2512
  new_space->Flip();
  new_space->ResetAllocationInfo();
2513 2514 2515 2516

  int survivors_size = 0;

  // First pass: traverse all objects in inactive semispace, remove marks,
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
  // migrate live objects and write forwarding addresses.  This stage puts
  // new entries in the store buffer and may cause some pages to be marked
  // scan-on-scavenge.
  SemiSpaceIterator from_it(from_bottom, from_top);
  for (HeapObject* object = from_it.Next();
       object != NULL;
       object = from_it.Next()) {
    MarkBit mark_bit = Marking::MarkBitFrom(object);
    if (mark_bit.Get()) {
      mark_bit.Clear();
2527 2528
      // Don't bother decrementing live bytes count. We'll discard the
      // entire page at the end.
2529
      int size = object->Size();
2530 2531
      survivors_size += size;

2532
      // Aggressively promote young survivors to the old space.
2533
      if (TryPromoteObject(object, size)) {
2534 2535 2536
        continue;
      }

2537
      // Promotion failed. Just migrate object to another semispace.
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
      MaybeObject* allocation = new_space->AllocateRaw(size);
      if (allocation->IsFailure()) {
        if (!new_space->AddFreshPage()) {
          // Shouldn't happen. We are sweeping linearly, and to-space
          // has the same number of pages as from-space, so there is
          // always room.
          UNREACHABLE();
        }
        allocation = new_space->AllocateRaw(size);
        ASSERT(!allocation->IsFailure());
      }
      Object* target = allocation->ToObjectUnchecked();
2550

2551 2552
      MigrateObject(HeapObject::cast(target)->address(),
                    object->address(),
2553
                    size,
2554
                    NEW_SPACE);
2555
    } else {
2556 2557 2558
      // Process the dead object before we write a NULL into its header.
      LiveObjectList::ProcessNonLive(object);

2559 2560
      // Mark dead objects in the new space with null in their map field.
      Memory::Address_at(object->address()) = NULL;
2561 2562
    }
  }
2563

2564 2565
  heap_->IncrementYoungSurvivorsCounter(survivors_size);
  new_space->set_age_mark(new_space->top());
2566 2567 2568
}


2569 2570 2571 2572 2573 2574
void MarkCompactCollector::EvacuateLiveObjectsFromPage(Page* p) {
  AlwaysAllocateScope always_allocate;
  PagedSpace* space = static_cast<PagedSpace*>(p->owner());
  ASSERT(p->IsEvacuationCandidate() && !p->WasSwept());
  MarkBit::CellType* cells = p->markbits()->cells();
  p->MarkSweptPrecisely();
2575

2576 2577 2578
  int last_cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
2579 2580 2581 2582 2583 2584
              p->AddressToMarkbitIndex(p->area_end())));

  Address cell_base = p->area_start();
  int cell_index = Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
              p->AddressToMarkbitIndex(cell_base)));
2585

2586
  int offsets[16];
2587

2588
  for (;
2589 2590 2591 2592 2593 2594 2595
       cell_index < last_cell_index;
       cell_index++, cell_base += 32 * kPointerSize) {
    ASSERT((unsigned)cell_index ==
        Bitmap::IndexToCell(
            Bitmap::CellAlignIndex(
                p->AddressToMarkbitIndex(cell_base))));
    if (cells[cell_index] == 0) continue;
2596

2597 2598 2599 2600 2601
    int live_objects = MarkWordToObjectStarts(cells[cell_index], offsets);
    for (int i = 0; i < live_objects; i++) {
      Address object_addr = cell_base + offsets[i] * kPointerSize;
      HeapObject* object = HeapObject::FromAddress(object_addr);
      ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
2602

2603
      int size = object->Size();
2604

2605 2606 2607 2608 2609
      MaybeObject* target = space->AllocateRaw(size);
      if (target->IsFailure()) {
        // OS refused to give us memory.
        V8::FatalProcessOutOfMemory("Evacuation");
        return;
2610 2611
      }

2612
      Object* target_object = target->ToObjectUnchecked();
2613

2614 2615 2616 2617 2618
      MigrateObject(HeapObject::cast(target_object)->address(),
                    object_addr,
                    size,
                    space->identity());
      ASSERT(object->map_word().IsForwardingAddress());
2619
    }
2620

2621 2622
    // Clear marking bits for current cell.
    cells[cell_index] = 0;
2623
  }
2624
  p->ResetLiveBytes();
2625
}
2626 2627


2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
void MarkCompactCollector::EvacuatePages() {
  int npages = evacuation_candidates_.length();
  for (int i = 0; i < npages; i++) {
    Page* p = evacuation_candidates_[i];
    ASSERT(p->IsEvacuationCandidate() ||
           p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
    if (p->IsEvacuationCandidate()) {
      // During compaction we might have to request a new page.
      // Check that space still have room for that.
      if (static_cast<PagedSpace*>(p->owner())->CanExpand()) {
        EvacuateLiveObjectsFromPage(p);
      } else {
        // Without room for expansion evacuation is not guaranteed to succeed.
        // Pessimistically abandon unevacuated pages.
        for (int j = i; j < npages; j++) {
2643 2644 2645 2646
          Page* page = evacuation_candidates_[j];
          slots_buffer_allocator_.DeallocateChain(page->slots_buffer_address());
          page->ClearEvacuationCandidate();
          page->SetFlag(Page::RESCAN_ON_EVACUATION);
2647 2648 2649
        }
        return;
      }
2650
    }
2651 2652 2653 2654
  }
}


2655
class EvacuationWeakObjectRetainer : public WeakObjectRetainer {
2656
 public:
2657 2658 2659 2660 2661 2662 2663 2664 2665
  virtual Object* RetainAs(Object* object) {
    if (object->IsHeapObject()) {
      HeapObject* heap_object = HeapObject::cast(object);
      MapWord map_word = heap_object->map_word();
      if (map_word.IsForwardingAddress()) {
        return map_word.ToForwardingAddress();
      }
    }
    return object;
2666 2667 2668 2669
  }
};


2670 2671 2672 2673 2674
static inline void UpdateSlot(ObjectVisitor* v,
                              SlotsBuffer::SlotType slot_type,
                              Address addr) {
  switch (slot_type) {
    case SlotsBuffer::CODE_TARGET_SLOT: {
2675
      RelocInfo rinfo(addr, RelocInfo::CODE_TARGET, 0, NULL);
2676 2677
      rinfo.Visit(v);
      break;
2678
    }
2679 2680 2681
    case SlotsBuffer::CODE_ENTRY_SLOT: {
      v->VisitCodeEntry(addr);
      break;
2682
    }
2683 2684 2685 2686
    case SlotsBuffer::RELOCATED_CODE_OBJECT: {
      HeapObject* obj = HeapObject::FromAddress(addr);
      Code::cast(obj)->CodeIterateBody(v);
      break;
2687
    }
2688
    case SlotsBuffer::DEBUG_TARGET_SLOT: {
2689
      RelocInfo rinfo(addr, RelocInfo::DEBUG_BREAK_SLOT, 0, NULL);
2690 2691
      if (rinfo.IsPatchedDebugBreakSlotSequence()) rinfo.Visit(v);
      break;
2692
    }
2693
    case SlotsBuffer::JS_RETURN_SLOT: {
2694
      RelocInfo rinfo(addr, RelocInfo::JS_RETURN, 0, NULL);
2695 2696
      if (rinfo.IsPatchedReturnSequence()) rinfo.Visit(v);
      break;
2697
    }
2698 2699 2700 2701 2702
    case SlotsBuffer::EMBEDDED_OBJECT_SLOT: {
      RelocInfo rinfo(addr, RelocInfo::EMBEDDED_OBJECT, 0, NULL);
      rinfo.Visit(v);
      break;
    }
2703 2704 2705
    default:
      UNREACHABLE();
      break;
2706
  }
2707
}
2708 2709


2710 2711 2712
enum SweepingMode {
  SWEEP_ONLY,
  SWEEP_AND_VISIT_LIVE_OBJECTS
2713 2714 2715
};


2716 2717 2718 2719
enum SkipListRebuildingMode {
  REBUILD_SKIP_LIST,
  IGNORE_SKIP_LIST
};
2720 2721


2722 2723 2724 2725 2726 2727
// Sweep a space precisely.  After this has been done the space can
// be iterated precisely, hitting only the live objects.  Code space
// is always swept precisely because we want to be able to iterate
// over it.  Map space is swept precisely, because it is not compacted.
// Slots in live objects pointing into evacuation candidates are updated
// if requested.
2728
template<SweepingMode sweeping_mode, SkipListRebuildingMode skip_list_mode>
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
static void SweepPrecisely(PagedSpace* space,
                           Page* p,
                           ObjectVisitor* v) {
  ASSERT(!p->IsEvacuationCandidate() && !p->WasSwept());
  ASSERT_EQ(skip_list_mode == REBUILD_SKIP_LIST,
            space->identity() == CODE_SPACE);
  ASSERT((p->skip_list() == NULL) || (skip_list_mode == REBUILD_SKIP_LIST));

  MarkBit::CellType* cells = p->markbits()->cells();
  p->MarkSweptPrecisely();

  int last_cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
2743 2744 2745 2746 2747 2748 2749
              p->AddressToMarkbitIndex(p->area_end())));

  Address free_start = p->area_start();
  int cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
              p->AddressToMarkbitIndex(free_start)));
2750 2751

  ASSERT(reinterpret_cast<intptr_t>(free_start) % (32 * kPointerSize) == 0);
2752
  Address object_address = free_start;
2753 2754 2755 2756 2757 2758 2759 2760
  int offsets[16];

  SkipList* skip_list = p->skip_list();
  int curr_region = -1;
  if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list) {
    skip_list->Clear();
  }

2761
  for (;
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
       cell_index < last_cell_index;
       cell_index++, object_address += 32 * kPointerSize) {
    ASSERT((unsigned)cell_index ==
        Bitmap::IndexToCell(
            Bitmap::CellAlignIndex(
                p->AddressToMarkbitIndex(object_address))));
    int live_objects = MarkWordToObjectStarts(cells[cell_index], offsets);
    int live_index = 0;
    for ( ; live_objects != 0; live_objects--) {
      Address free_end = object_address + offsets[live_index++] * kPointerSize;
      if (free_end != free_start) {
2773
        space->Free(free_start, static_cast<int>(free_end - free_start));
2774 2775 2776 2777 2778
      }
      HeapObject* live_object = HeapObject::FromAddress(free_end);
      ASSERT(Marking::IsBlack(Marking::MarkBitFrom(live_object)));
      Map* map = live_object->map();
      int size = live_object->SizeFromMap(map);
2779
      if (sweeping_mode == SWEEP_AND_VISIT_LIVE_OBJECTS) {
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
        live_object->IterateBody(map->instance_type(), size, v);
      }
      if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list != NULL) {
        int new_region_start =
            SkipList::RegionNumber(free_end);
        int new_region_end =
            SkipList::RegionNumber(free_end + size - kPointerSize);
        if (new_region_start != curr_region ||
            new_region_end != curr_region) {
          skip_list->AddObject(free_end, size);
          curr_region = new_region_end;
        }
      }
      free_start = free_end + size;
2794
    }
2795 2796
    // Clear marking bits for current cell.
    cells[cell_index] = 0;
2797
  }
2798 2799
  if (free_start != p->area_end()) {
    space->Free(free_start, static_cast<int>(p->area_end() - free_start));
2800
  }
2801
  p->ResetLiveBytes();
2802 2803 2804
}


2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
static bool SetMarkBitsUnderInvalidatedCode(Code* code, bool value) {
  Page* p = Page::FromAddress(code->address());

  if (p->IsEvacuationCandidate() ||
      p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
    return false;
  }

  Address code_start = code->address();
  Address code_end = code_start + code->Size();

  uint32_t start_index = MemoryChunk::FastAddressToMarkbitIndex(code_start);
  uint32_t end_index =
      MemoryChunk::FastAddressToMarkbitIndex(code_end - kPointerSize);

  Bitmap* b = p->markbits();

  MarkBit start_mark_bit = b->MarkBitFromIndex(start_index);
  MarkBit end_mark_bit = b->MarkBitFromIndex(end_index);

  MarkBit::CellType* start_cell = start_mark_bit.cell();
  MarkBit::CellType* end_cell = end_mark_bit.cell();

  if (value) {
    MarkBit::CellType start_mask = ~(start_mark_bit.mask() - 1);
    MarkBit::CellType end_mask = (end_mark_bit.mask() << 1) - 1;

    if (start_cell == end_cell) {
      *start_cell |= start_mask & end_mask;
    } else {
      *start_cell |= start_mask;
      for (MarkBit::CellType* cell = start_cell + 1; cell < end_cell; cell++) {
        *cell = ~0;
      }
      *end_cell |= end_mask;
    }
  } else {
    for (MarkBit::CellType* cell = start_cell ; cell <= end_cell; cell++) {
      *cell = 0;
    }
  }

  return true;
}


static bool IsOnInvalidatedCodeObject(Address addr) {
  // We did not record any slots in large objects thus
  // we can safely go to the page from the slot address.
  Page* p = Page::FromAddress(addr);

  // First check owner's identity because old pointer and old data spaces
  // are swept lazily and might still have non-zero mark-bits on some
  // pages.
  if (p->owner()->identity() != CODE_SPACE) return false;

  // In code space only bits on evacuation candidates (but we don't record
  // any slots on them) and under invalidated code objects are non-zero.
  MarkBit mark_bit =
      p->markbits()->MarkBitFromIndex(Page::FastAddressToMarkbitIndex(addr));

  return mark_bit.Get();
}


void MarkCompactCollector::InvalidateCode(Code* code) {
  if (heap_->incremental_marking()->IsCompacting() &&
      !ShouldSkipEvacuationSlotRecording(code)) {
    ASSERT(compacting_);

    // If the object is white than no slots were recorded on it yet.
    MarkBit mark_bit = Marking::MarkBitFrom(code);
    if (Marking::IsWhite(mark_bit)) return;

    invalidated_code_.Add(code);
  }
}


bool MarkCompactCollector::MarkInvalidatedCode() {
  bool code_marked = false;

  int length = invalidated_code_.length();
  for (int i = 0; i < length; i++) {
    Code* code = invalidated_code_[i];

    if (SetMarkBitsUnderInvalidatedCode(code, true)) {
      code_marked = true;
    }
  }

  return code_marked;
}


void MarkCompactCollector::RemoveDeadInvalidatedCode() {
  int length = invalidated_code_.length();
  for (int i = 0; i < length; i++) {
    if (!IsMarked(invalidated_code_[i])) invalidated_code_[i] = NULL;
  }
}


void MarkCompactCollector::ProcessInvalidatedCode(ObjectVisitor* visitor) {
  int length = invalidated_code_.length();
  for (int i = 0; i < length; i++) {
    Code* code = invalidated_code_[i];
    if (code != NULL) {
      code->Iterate(visitor);
      SetMarkBitsUnderInvalidatedCode(code, false);
    }
  }
  invalidated_code_.Rewind(0);
}


2921
void MarkCompactCollector::EvacuateNewSpaceAndCandidates() {
2922 2923
  Heap::RelocationLock relocation_lock(heap());

2924 2925 2926 2927 2928 2929
  bool code_slots_filtering_required;
  { GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP_NEWSPACE);
    code_slots_filtering_required = MarkInvalidatedCode();

    EvacuateNewSpace();
  }
2930

2931 2932 2933 2934

  { GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_EVACUATE_PAGES);
    EvacuatePages();
  }
2935

2936 2937
  // Second pass: find pointers to new space and update them.
  PointersUpdatingVisitor updating_visitor(heap());
2938

2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
  { GCTracer::Scope gc_scope(tracer_,
                             GCTracer::Scope::MC_UPDATE_NEW_TO_NEW_POINTERS);
    // Update pointers in to space.
    SemiSpaceIterator to_it(heap()->new_space()->bottom(),
                            heap()->new_space()->top());
    for (HeapObject* object = to_it.Next();
         object != NULL;
         object = to_it.Next()) {
      Map* map = object->map();
      object->IterateBody(map->instance_type(),
                          object->SizeFromMap(map),
                          &updating_visitor);
    }
2952 2953
  }

2954 2955 2956 2957 2958 2959
  { GCTracer::Scope gc_scope(tracer_,
                             GCTracer::Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS);
    // Update roots.
    heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_SWEEP_NEWSPACE);
    LiveObjectList::IterateElements(&updating_visitor);
  }
2960

2961 2962
  { GCTracer::Scope gc_scope(tracer_,
                             GCTracer::Scope::MC_UPDATE_OLD_TO_NEW_POINTERS);
2963 2964 2965 2966
    StoreBufferRebuildScope scope(heap_,
                                  heap_->store_buffer(),
                                  &Heap::ScavengeStoreBufferCallback);
    heap_->store_buffer()->IteratePointersToNewSpace(&UpdatePointer);
2967 2968
  }

2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
  { GCTracer::Scope gc_scope(tracer_,
                             GCTracer::Scope::MC_UPDATE_POINTERS_TO_EVACUATED);
    SlotsBuffer::UpdateSlotsRecordedIn(heap_,
                                       migration_slots_buffer_,
                                       code_slots_filtering_required);
    if (FLAG_trace_fragmentation) {
      PrintF("  migration slots buffer: %d\n",
             SlotsBuffer::SizeOfChain(migration_slots_buffer_));
    }

    if (compacting_ && was_marked_incrementally_) {
      // It's difficult to filter out slots recorded for large objects.
      LargeObjectIterator it(heap_->lo_space());
      for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
        // LargeObjectSpace is not swept yet thus we have to skip
        // dead objects explicitly.
        if (!IsMarked(obj)) continue;

        Page* p = Page::FromAddress(obj->address());
        if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
          obj->Iterate(&updating_visitor);
          p->ClearFlag(Page::RESCAN_ON_EVACUATION);
        }
2992 2993 2994 2995
      }
    }
  }

2996
  int npages = evacuation_candidates_.length();
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
  { GCTracer::Scope gc_scope(
      tracer_, GCTracer::Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED);
    for (int i = 0; i < npages; i++) {
      Page* p = evacuation_candidates_[i];
      ASSERT(p->IsEvacuationCandidate() ||
             p->IsFlagSet(Page::RESCAN_ON_EVACUATION));

      if (p->IsEvacuationCandidate()) {
        SlotsBuffer::UpdateSlotsRecordedIn(heap_,
                                           p->slots_buffer(),
                                           code_slots_filtering_required);
        if (FLAG_trace_fragmentation) {
          PrintF("  page %p slots buffer: %d\n",
                 reinterpret_cast<void*>(p),
                 SlotsBuffer::SizeOfChain(p->slots_buffer()));
        }
3013

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
        // Important: skip list should be cleared only after roots were updated
        // because root iteration traverses the stack and might have to find
        // code objects from non-updated pc pointing into evacuation candidate.
        SkipList* list = p->skip_list();
        if (list != NULL) list->Clear();
      } else {
        if (FLAG_gc_verbose) {
          PrintF("Sweeping 0x%" V8PRIxPTR " during evacuation.\n",
                 reinterpret_cast<intptr_t>(p));
        }
        PagedSpace* space = static_cast<PagedSpace*>(p->owner());
        p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);

        switch (space->identity()) {
          case OLD_DATA_SPACE:
            SweepConservatively(space, p);
            break;
          case OLD_POINTER_SPACE:
            SweepPrecisely<SWEEP_AND_VISIT_LIVE_OBJECTS, IGNORE_SKIP_LIST>(
                space, p, &updating_visitor);
            break;
          case CODE_SPACE:
            SweepPrecisely<SWEEP_AND_VISIT_LIVE_OBJECTS, REBUILD_SKIP_LIST>(
                space, p, &updating_visitor);
            break;
          default:
            UNREACHABLE();
            break;
        }
3043
      }
3044
    }
3045
  }
3046

3047 3048
  GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_UPDATE_MISC_POINTERS);

3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
  // Update pointers from cells.
  HeapObjectIterator cell_iterator(heap_->cell_space());
  for (HeapObject* cell = cell_iterator.Next();
       cell != NULL;
       cell = cell_iterator.Next()) {
    if (cell->IsJSGlobalPropertyCell()) {
      Address value_address =
          reinterpret_cast<Address>(cell) +
          (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
      updating_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
3059
    }
3060
  }
3061

3062 3063
  // Update pointer from the native contexts list.
  updating_visitor.VisitPointer(heap_->native_contexts_list_address());
3064

3065
  heap_->symbol_table()->Iterate(&updating_visitor);
3066

3067 3068 3069 3070
  // Update pointers from external string table.
  heap_->UpdateReferencesInExternalStringTable(
      &UpdateReferenceInExternalStringTableEntry);

3071 3072 3073
  // Update pointers in the new error object list.
  heap_->error_object_list()->UpdateReferences();

3074
  if (!FLAG_watch_ic_patching) {
3075 3076 3077 3078
    // Update JSFunction pointers from the runtime profiler.
    heap()->isolate()->runtime_profiler()->UpdateSamplesAfterCompact(
        &updating_visitor);
  }
3079

3080 3081
  EvacuationWeakObjectRetainer evacuation_object_retainer;
  heap()->ProcessWeakReferences(&evacuation_object_retainer);
3082

3083 3084 3085 3086
  // Visit invalidated code (we ignored all slots on it) and clear mark-bits
  // under it.
  ProcessInvalidatedCode(&updating_visitor);

3087 3088
  heap_->isolate()->inner_pointer_to_code_cache()->Flush();

3089
#ifdef VERIFY_HEAP
3090 3091
  if (FLAG_verify_heap) {
    VerifyEvacuation(heap_);
3092 3093 3094
  }
#endif

3095 3096 3097 3098 3099 3100
  slots_buffer_allocator_.DeallocateChain(&migration_slots_buffer_);
  ASSERT(migration_slots_buffer_ == NULL);
  for (int i = 0; i < npages; i++) {
    Page* p = evacuation_candidates_[i];
    if (!p->IsEvacuationCandidate()) continue;
    PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3101
    space->Free(p->area_start(), p->area_size());
3102 3103
    p->set_scan_on_scavenge(false);
    slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
3104 3105
    p->ResetLiveBytes();
    space->ReleasePage(p);
3106
  }
3107 3108
  evacuation_candidates_.Rewind(0);
  compacting_ = false;
3109 3110 3111
}


3112 3113 3114 3115
static const int kStartTableEntriesPerLine = 5;
static const int kStartTableLines = 171;
static const int kStartTableInvalidLine = 127;
static const int kStartTableUnusedEntry = 126;
3116

3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
#define _ kStartTableUnusedEntry
#define X kStartTableInvalidLine
// Mark-bit to object start offset table.
//
// The line is indexed by the mark bits in a byte.  The first number on
// the line describes the number of live object starts for the line and the
// other numbers on the line describe the offsets (in words) of the object
// starts.
//
// Since objects are at least 2 words large we don't have entries for two
// consecutive 1 bits.  All entries after 170 have at least 2 consecutive bits.
char kStartTable[kStartTableLines * kStartTableEntriesPerLine] = {
  0, _, _, _, _,  // 0
  1, 0, _, _, _,  // 1
  1, 1, _, _, _,  // 2
  X, _, _, _, _,  // 3
  1, 2, _, _, _,  // 4
  2, 0, 2, _, _,  // 5
  X, _, _, _, _,  // 6
  X, _, _, _, _,  // 7
  1, 3, _, _, _,  // 8
  2, 0, 3, _, _,  // 9
  2, 1, 3, _, _,  // 10
  X, _, _, _, _,  // 11
  X, _, _, _, _,  // 12
  X, _, _, _, _,  // 13
  X, _, _, _, _,  // 14
  X, _, _, _, _,  // 15
  1, 4, _, _, _,  // 16
  2, 0, 4, _, _,  // 17
  2, 1, 4, _, _,  // 18
  X, _, _, _, _,  // 19
  2, 2, 4, _, _,  // 20
  3, 0, 2, 4, _,  // 21
  X, _, _, _, _,  // 22
  X, _, _, _, _,  // 23
  X, _, _, _, _,  // 24
  X, _, _, _, _,  // 25
  X, _, _, _, _,  // 26
  X, _, _, _, _,  // 27
  X, _, _, _, _,  // 28
  X, _, _, _, _,  // 29
  X, _, _, _, _,  // 30
  X, _, _, _, _,  // 31
  1, 5, _, _, _,  // 32
  2, 0, 5, _, _,  // 33
  2, 1, 5, _, _,  // 34
  X, _, _, _, _,  // 35
  2, 2, 5, _, _,  // 36
  3, 0, 2, 5, _,  // 37
  X, _, _, _, _,  // 38
  X, _, _, _, _,  // 39
  2, 3, 5, _, _,  // 40
  3, 0, 3, 5, _,  // 41
  3, 1, 3, 5, _,  // 42
  X, _, _, _, _,  // 43
  X, _, _, _, _,  // 44
  X, _, _, _, _,  // 45
  X, _, _, _, _,  // 46
  X, _, _, _, _,  // 47
  X, _, _, _, _,  // 48
  X, _, _, _, _,  // 49
  X, _, _, _, _,  // 50
  X, _, _, _, _,  // 51
  X, _, _, _, _,  // 52
  X, _, _, _, _,  // 53
  X, _, _, _, _,  // 54
  X, _, _, _, _,  // 55
  X, _, _, _, _,  // 56
  X, _, _, _, _,  // 57
  X, _, _, _, _,  // 58
  X, _, _, _, _,  // 59
  X, _, _, _, _,  // 60
  X, _, _, _, _,  // 61
  X, _, _, _, _,  // 62
  X, _, _, _, _,  // 63
  1, 6, _, _, _,  // 64
  2, 0, 6, _, _,  // 65
  2, 1, 6, _, _,  // 66
  X, _, _, _, _,  // 67
  2, 2, 6, _, _,  // 68
  3, 0, 2, 6, _,  // 69
  X, _, _, _, _,  // 70
  X, _, _, _, _,  // 71
  2, 3, 6, _, _,  // 72
  3, 0, 3, 6, _,  // 73
  3, 1, 3, 6, _,  // 74
  X, _, _, _, _,  // 75
  X, _, _, _, _,  // 76
  X, _, _, _, _,  // 77
  X, _, _, _, _,  // 78
  X, _, _, _, _,  // 79
  2, 4, 6, _, _,  // 80
  3, 0, 4, 6, _,  // 81
  3, 1, 4, 6, _,  // 82
  X, _, _, _, _,  // 83
  3, 2, 4, 6, _,  // 84
  4, 0, 2, 4, 6,  // 85
  X, _, _, _, _,  // 86
  X, _, _, _, _,  // 87
  X, _, _, _, _,  // 88
  X, _, _, _, _,  // 89
  X, _, _, _, _,  // 90
  X, _, _, _, _,  // 91
  X, _, _, _, _,  // 92
  X, _, _, _, _,  // 93
  X, _, _, _, _,  // 94
  X, _, _, _, _,  // 95
  X, _, _, _, _,  // 96
  X, _, _, _, _,  // 97
  X, _, _, _, _,  // 98
  X, _, _, _, _,  // 99
  X, _, _, _, _,  // 100
  X, _, _, _, _,  // 101
  X, _, _, _, _,  // 102
  X, _, _, _, _,  // 103
  X, _, _, _, _,  // 104
  X, _, _, _, _,  // 105
  X, _, _, _, _,  // 106
  X, _, _, _, _,  // 107
  X, _, _, _, _,  // 108
  X, _, _, _, _,  // 109
  X, _, _, _, _,  // 110
  X, _, _, _, _,  // 111
  X, _, _, _, _,  // 112
  X, _, _, _, _,  // 113
  X, _, _, _, _,  // 114
  X, _, _, _, _,  // 115
  X, _, _, _, _,  // 116
  X, _, _, _, _,  // 117
  X, _, _, _, _,  // 118
  X, _, _, _, _,  // 119
  X, _, _, _, _,  // 120
  X, _, _, _, _,  // 121
  X, _, _, _, _,  // 122
  X, _, _, _, _,  // 123
  X, _, _, _, _,  // 124
  X, _, _, _, _,  // 125
  X, _, _, _, _,  // 126
  X, _, _, _, _,  // 127
  1, 7, _, _, _,  // 128
  2, 0, 7, _, _,  // 129
  2, 1, 7, _, _,  // 130
  X, _, _, _, _,  // 131
  2, 2, 7, _, _,  // 132
  3, 0, 2, 7, _,  // 133
  X, _, _, _, _,  // 134
  X, _, _, _, _,  // 135
  2, 3, 7, _, _,  // 136
  3, 0, 3, 7, _,  // 137
  3, 1, 3, 7, _,  // 138
  X, _, _, _, _,  // 139
  X, _, _, _, _,  // 140
  X, _, _, _, _,  // 141
  X, _, _, _, _,  // 142
  X, _, _, _, _,  // 143
  2, 4, 7, _, _,  // 144
  3, 0, 4, 7, _,  // 145
  3, 1, 4, 7, _,  // 146
  X, _, _, _, _,  // 147
  3, 2, 4, 7, _,  // 148
  4, 0, 2, 4, 7,  // 149
  X, _, _, _, _,  // 150
  X, _, _, _, _,  // 151
  X, _, _, _, _,  // 152
  X, _, _, _, _,  // 153
  X, _, _, _, _,  // 154
  X, _, _, _, _,  // 155
  X, _, _, _, _,  // 156
  X, _, _, _, _,  // 157
  X, _, _, _, _,  // 158
  X, _, _, _, _,  // 159
  2, 5, 7, _, _,  // 160
  3, 0, 5, 7, _,  // 161
  3, 1, 5, 7, _,  // 162
  X, _, _, _, _,  // 163
  3, 2, 5, 7, _,  // 164
  4, 0, 2, 5, 7,  // 165
  X, _, _, _, _,  // 166
  X, _, _, _, _,  // 167
  3, 3, 5, 7, _,  // 168
  4, 0, 3, 5, 7,  // 169
  4, 1, 3, 5, 7   // 170
};
#undef _
#undef X


// Takes a word of mark bits.  Returns the number of objects that start in the
// range.  Puts the offsets of the words in the supplied array.
static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts) {
  int objects = 0;
  int offset = 0;

  // No consecutive 1 bits.
  ASSERT((mark_bits & 0x180) != 0x180);
  ASSERT((mark_bits & 0x18000) != 0x18000);
  ASSERT((mark_bits & 0x1800000) != 0x1800000);

  while (mark_bits != 0) {
    int byte = (mark_bits & 0xff);
    mark_bits >>= 8;
    if (byte != 0) {
      ASSERT(byte < kStartTableLines);  // No consecutive 1 bits.
      char* table = kStartTable + byte * kStartTableEntriesPerLine;
      int objects_in_these_8_words = table[0];
      ASSERT(objects_in_these_8_words != kStartTableInvalidLine);
      ASSERT(objects_in_these_8_words < kStartTableEntriesPerLine);
      for (int i = 0; i < objects_in_these_8_words; i++) {
        starts[objects++] = offset + table[1 + i];
      }
    }
    offset += 8;
  }
  return objects;
}
3333 3334


3335 3336 3337
static inline Address DigestFreeStart(Address approximate_free_start,
                                      uint32_t free_start_cell) {
  ASSERT(free_start_cell != 0);
3338

3339 3340 3341
  // No consecutive 1 bits.
  ASSERT((free_start_cell & (free_start_cell << 1)) == 0);

3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371
  int offsets[16];
  uint32_t cell = free_start_cell;
  int offset_of_last_live;
  if ((cell & 0x80000000u) != 0) {
    // This case would overflow below.
    offset_of_last_live = 31;
  } else {
    // Remove all but one bit, the most significant.  This is an optimization
    // that may or may not be worthwhile.
    cell |= cell >> 16;
    cell |= cell >> 8;
    cell |= cell >> 4;
    cell |= cell >> 2;
    cell |= cell >> 1;
    cell = (cell + 1) >> 1;
    int live_objects = MarkWordToObjectStarts(cell, offsets);
    ASSERT(live_objects == 1);
    offset_of_last_live = offsets[live_objects - 1];
  }
  Address last_live_start =
      approximate_free_start + offset_of_last_live * kPointerSize;
  HeapObject* last_live = HeapObject::FromAddress(last_live_start);
  Address free_start = last_live_start + last_live->Size();
  return free_start;
}


static inline Address StartOfLiveObject(Address block_address, uint32_t cell) {
  ASSERT(cell != 0);

3372 3373 3374
  // No consecutive 1 bits.
  ASSERT((cell & (cell << 1)) == 0);

3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402
  int offsets[16];
  if (cell == 0x80000000u) {  // Avoid overflow below.
    return block_address + 31 * kPointerSize;
  }
  uint32_t first_set_bit = ((cell ^ (cell - 1)) + 1) >> 1;
  ASSERT((first_set_bit & cell) == first_set_bit);
  int live_objects = MarkWordToObjectStarts(first_set_bit, offsets);
  ASSERT(live_objects == 1);
  USE(live_objects);
  return block_address + offsets[0] * kPointerSize;
}


// Sweeps a space conservatively.  After this has been done the larger free
// spaces have been put on the free list and the smaller ones have been
// ignored and left untouched.  A free space is always either ignored or put
// on the free list, never split up into two parts.  This is important
// because it means that any FreeSpace maps left actually describe a region of
// memory that can be ignored when scanning.  Dead objects other than free
// spaces will not contain the free space map.
intptr_t MarkCompactCollector::SweepConservatively(PagedSpace* space, Page* p) {
  ASSERT(!p->IsEvacuationCandidate() && !p->WasSwept());
  MarkBit::CellType* cells = p->markbits()->cells();
  p->MarkSweptConservatively();

  int last_cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
3403 3404 3405 3406 3407 3408
              p->AddressToMarkbitIndex(p->area_end())));

  int cell_index =
      Bitmap::IndexToCell(
          Bitmap::CellAlignIndex(
              p->AddressToMarkbitIndex(p->area_start())));
3409 3410 3411 3412

  intptr_t freed_bytes = 0;

  // This is the start of the 32 word block that we are currently looking at.
3413
  Address block_address = p->area_start();
3414 3415

  // Skip over all the dead objects at the start of the page and mark them free.
3416
  for (;
3417 3418 3419 3420
       cell_index < last_cell_index;
       cell_index++, block_address += 32 * kPointerSize) {
    if (cells[cell_index] != 0) break;
  }
3421
  size_t size = block_address - p->area_start();
3422
  if (cell_index == last_cell_index) {
3423
    freed_bytes += static_cast<int>(space->Free(p->area_start(),
3424
                                                static_cast<int>(size)));
3425
    ASSERT_EQ(0, p->LiveBytes());
3426 3427 3428 3429 3430 3431
    return freed_bytes;
  }
  // Grow the size of the start-of-page free space a little to get up to the
  // first live object.
  Address free_end = StartOfLiveObject(block_address, cells[cell_index]);
  // Free the first free space.
3432 3433
  size = free_end - p->area_start();
  freed_bytes += space->Free(p->area_start(),
3434
                             static_cast<int>(size));
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
  // The start of the current free area is represented in undigested form by
  // the address of the last 32-word section that contained a live object and
  // the marking bitmap for that cell, which describes where the live object
  // started.  Unless we find a large free space in the bitmap we will not
  // digest this pair into a real address.  We start the iteration here at the
  // first word in the marking bit map that indicates a live object.
  Address free_start = block_address;
  uint32_t free_start_cell = cells[cell_index];

  for ( ;
       cell_index < last_cell_index;
       cell_index++, block_address += 32 * kPointerSize) {
    ASSERT((unsigned)cell_index ==
        Bitmap::IndexToCell(
            Bitmap::CellAlignIndex(
                p->AddressToMarkbitIndex(block_address))));
    uint32_t cell = cells[cell_index];
    if (cell != 0) {
      // We have a live object.  Check approximately whether it is more than 32
      // words since the last live object.
      if (block_address - free_start > 32 * kPointerSize) {
        free_start = DigestFreeStart(free_start, free_start_cell);
        if (block_address - free_start > 32 * kPointerSize) {
          // Now that we know the exact start of the free space it still looks
          // like we have a large enough free space to be worth bothering with.
          // so now we need to find the start of the first live object at the
          // end of the free space.
          free_end = StartOfLiveObject(block_address, cell);
3463 3464
          freed_bytes += space->Free(free_start,
                                     static_cast<int>(free_end - free_start));
3465 3466 3467 3468 3469 3470 3471 3472
        }
      }
      // Update our undigested record of where the current free area started.
      free_start = block_address;
      free_start_cell = cell;
      // Clear marking bits for current cell.
      cells[cell_index] = 0;
    }
3473 3474
  }

3475 3476 3477
  // Handle the free space at the end of the page.
  if (block_address - free_start > 32 * kPointerSize) {
    free_start = DigestFreeStart(free_start, free_start_cell);
3478 3479
    freed_bytes += space->Free(free_start,
                               static_cast<int>(block_address - free_start));
3480 3481
  }

3482
  p->ResetLiveBytes();
3483
  return freed_bytes;
3484 3485 3486
}


3487
void MarkCompactCollector::SweepSpace(PagedSpace* space, SweeperType sweeper) {
3488 3489
  space->set_was_swept_conservatively(sweeper == CONSERVATIVE ||
                                      sweeper == LAZY_CONSERVATIVE);
3490

3491
  space->ClearStats();
3492

3493
  PageIterator it(space);
3494

3495
  intptr_t freed_bytes = 0;
3496
  int pages_swept = 0;
3497
  bool lazy_sweeping_active = false;
3498
  bool unused_page_present = false;
3499

3500 3501
  while (it.has_next()) {
    Page* p = it.next();
3502

3503 3504 3505
    // Clear sweeping flags indicating that marking bits are still intact.
    p->ClearSweptPrecisely();
    p->ClearSweptConservatively();
3506

3507 3508 3509 3510
    if (p->IsEvacuationCandidate()) {
      ASSERT(evacuation_candidates_.length() > 0);
      continue;
    }
3511

3512 3513 3514 3515
    if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
      // Will be processed in EvacuateNewSpaceAndCandidates.
      continue;
    }
3516

3517 3518 3519 3520 3521 3522 3523
    // One unused page is kept, all further are released before sweeping them.
    if (p->LiveBytes() == 0) {
      if (unused_page_present) {
        if (FLAG_gc_verbose) {
          PrintF("Sweeping 0x%" V8PRIxPTR " released page.\n",
                 reinterpret_cast<intptr_t>(p));
        }
3524 3525 3526
        // Adjust unswept free bytes because releasing a page expects said
        // counter to be accurate for unswept pages.
        space->IncreaseUnsweptFreeBytes(p);
3527 3528 3529 3530 3531 3532
        space->ReleasePage(p);
        continue;
      }
      unused_page_present = true;
    }

3533 3534 3535 3536 3537
    if (lazy_sweeping_active) {
      if (FLAG_gc_verbose) {
        PrintF("Sweeping 0x%" V8PRIxPTR " lazily postponed.\n",
               reinterpret_cast<intptr_t>(p));
      }
3538
      space->IncreaseUnsweptFreeBytes(p);
3539 3540 3541
      continue;
    }

3542 3543
    switch (sweeper) {
      case CONSERVATIVE: {
3544 3545 3546 3547
        if (FLAG_gc_verbose) {
          PrintF("Sweeping 0x%" V8PRIxPTR " conservatively.\n",
                 reinterpret_cast<intptr_t>(p));
        }
3548
        SweepConservatively(space, p);
3549
        pages_swept++;
3550 3551 3552
        break;
      }
      case LAZY_CONSERVATIVE: {
3553 3554 3555 3556
        if (FLAG_gc_verbose) {
          PrintF("Sweeping 0x%" V8PRIxPTR " conservatively as needed.\n",
                 reinterpret_cast<intptr_t>(p));
        }
3557
        freed_bytes += SweepConservatively(space, p);
3558
        pages_swept++;
3559 3560
        space->SetPagesToSweep(p->next_page());
        lazy_sweeping_active = true;
3561 3562 3563
        break;
      }
      case PRECISE: {
3564 3565 3566 3567
        if (FLAG_gc_verbose) {
          PrintF("Sweeping 0x%" V8PRIxPTR " precisely.\n",
                 reinterpret_cast<intptr_t>(p));
        }
3568
        if (space->identity() == CODE_SPACE) {
3569
          SweepPrecisely<SWEEP_ONLY, REBUILD_SKIP_LIST>(space, p, NULL);
3570
        } else {
3571
          SweepPrecisely<SWEEP_ONLY, IGNORE_SKIP_LIST>(space, p, NULL);
3572
        }
3573
        pages_swept++;
3574 3575 3576 3577 3578
        break;
      }
      default: {
        UNREACHABLE();
      }
3579
    }
3580
  }
3581

3582 3583 3584 3585 3586 3587
  if (FLAG_gc_verbose) {
    PrintF("SweepSpace: %s (%d pages swept)\n",
           AllocationSpaceName(space->identity()),
           pages_swept);
  }

3588 3589
  // Give pages that are queued to be freed back to the OS.
  heap()->FreeQueuedChunks();
3590
}
3591

3592

3593 3594 3595 3596 3597 3598 3599
void MarkCompactCollector::SweepSpaces() {
  GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP);
#ifdef DEBUG
  state_ = SWEEP_SPACES;
#endif
  SweeperType how_to_sweep =
      FLAG_lazy_sweeping ? LAZY_CONSERVATIVE : CONSERVATIVE;
3600
  if (FLAG_expose_gc) how_to_sweep = CONSERVATIVE;
3601 3602 3603 3604 3605 3606 3607 3608
  if (sweep_precisely_) how_to_sweep = PRECISE;
  // Noncompacting collections simply sweep the spaces to clear the mark
  // bits and free the nonlive blocks (for old and map spaces).  We sweep
  // the map space last because freeing non-live maps overwrites them and
  // the other spaces rely on possibly non-live maps to get the sizes for
  // non-live objects.
  SweepSpace(heap()->old_pointer_space(), how_to_sweep);
  SweepSpace(heap()->old_data_space(), how_to_sweep);
3609 3610

  RemoveDeadInvalidatedCode();
3611
  SweepSpace(heap()->code_space(), PRECISE);
3612

3613
  SweepSpace(heap()->cell_space(), PRECISE);
3614

3615
  EvacuateNewSpaceAndCandidates();
3616

3617 3618 3619 3620
  // ClearNonLiveTransitions depends on precise sweeping of map space to
  // detect whether unmarked map became dead in this collection or in one
  // of the previous ones.
  SweepSpace(heap()->map_space(), PRECISE);
3621

3622 3623
  // Deallocate unmarked objects and clear marked bits for marked objects.
  heap_->lo_space()->FreeUnmarkedObjects();
3624 3625 3626
}


3627
void MarkCompactCollector::EnableCodeFlushing(bool enable) {
3628 3629 3630 3631 3632 3633 3634
#ifdef ENABLE_DEBUGGER_SUPPORT
  if (heap()->isolate()->debug()->IsLoaded() ||
      heap()->isolate()->debug()->has_break_points()) {
    enable = false;
  }
#endif

3635 3636 3637 3638 3639
  if (enable) {
    if (code_flusher_ != NULL) return;
    code_flusher_ = new CodeFlusher(heap()->isolate());
  } else {
    if (code_flusher_ == NULL) return;
3640
    code_flusher_->EvictAllCandidates();
3641 3642 3643
    delete code_flusher_;
    code_flusher_ = NULL;
  }
3644 3645 3646
}


3647 3648 3649
// TODO(1466) ReportDeleteIfNeeded is not called currently.
// Our profiling tools do not expect intersections between
// code objects. We should either reenable it or change our tools.
3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
void MarkCompactCollector::ReportDeleteIfNeeded(HeapObject* obj,
                                                Isolate* isolate) {
#ifdef ENABLE_GDB_JIT_INTERFACE
  if (obj->IsCode()) {
    GDBJITInterface::RemoveCode(reinterpret_cast<Code*>(obj));
  }
#endif
  if (obj->IsCode()) {
    PROFILE(isolate, CodeDeleteEvent(obj->address()));
  }
3660 3661 3662
}


3663
void MarkCompactCollector::Initialize() {
3664 3665
  MarkCompactMarkingVisitor::Initialize();
  IncrementalMarking::Initialize();
3666
}
3667

3668

3669 3670 3671
bool SlotsBuffer::IsTypedSlot(ObjectSlot slot) {
  return reinterpret_cast<uintptr_t>(slot) < NUMBER_OF_SLOT_TYPES;
}
3672

3673

3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
bool SlotsBuffer::AddTo(SlotsBufferAllocator* allocator,
                        SlotsBuffer** buffer_address,
                        SlotType type,
                        Address addr,
                        AdditionMode mode) {
  SlotsBuffer* buffer = *buffer_address;
  if (buffer == NULL || !buffer->HasSpaceForTypedSlot()) {
    if (mode == FAIL_ON_OVERFLOW && ChainLengthThresholdReached(buffer)) {
      allocator->DeallocateChain(buffer_address);
      return false;
    }
    buffer = allocator->AllocateBuffer(buffer);
    *buffer_address = buffer;
3687
  }
3688 3689 3690 3691
  ASSERT(buffer->HasSpaceForTypedSlot());
  buffer->Add(reinterpret_cast<ObjectSlot>(type));
  buffer->Add(reinterpret_cast<ObjectSlot>(addr));
  return true;
3692 3693 3694
}


3695 3696 3697
static inline SlotsBuffer::SlotType SlotTypeForRMode(RelocInfo::Mode rmode) {
  if (RelocInfo::IsCodeTarget(rmode)) {
    return SlotsBuffer::CODE_TARGET_SLOT;
3698 3699
  } else if (RelocInfo::IsEmbeddedObject(rmode)) {
    return SlotsBuffer::EMBEDDED_OBJECT_SLOT;
3700 3701 3702 3703 3704 3705 3706 3707
  } else if (RelocInfo::IsDebugBreakSlot(rmode)) {
    return SlotsBuffer::DEBUG_TARGET_SLOT;
  } else if (RelocInfo::IsJSReturn(rmode)) {
    return SlotsBuffer::JS_RETURN_SLOT;
  }
  UNREACHABLE();
  return SlotsBuffer::NUMBER_OF_SLOT_TYPES;
}
3708 3709


3710 3711
void MarkCompactCollector::RecordRelocSlot(RelocInfo* rinfo, Object* target) {
  Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721
  if (target_page->IsEvacuationCandidate() &&
      (rinfo->host() == NULL ||
       !ShouldSkipEvacuationSlotRecording(rinfo->host()))) {
    if (!SlotsBuffer::AddTo(&slots_buffer_allocator_,
                            target_page->slots_buffer_address(),
                            SlotTypeForRMode(rinfo->rmode()),
                            rinfo->pc(),
                            SlotsBuffer::FAIL_ON_OVERFLOW)) {
      EvictEvacuationCandidate(target_page);
    }
3722
  }
3723
}
3724 3725


3726
void MarkCompactCollector::RecordCodeEntrySlot(Address slot, Code* target) {
3727
  Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
3728 3729 3730 3731 3732 3733 3734 3735 3736
  if (target_page->IsEvacuationCandidate() &&
      !ShouldSkipEvacuationSlotRecording(reinterpret_cast<Object**>(slot))) {
    if (!SlotsBuffer::AddTo(&slots_buffer_allocator_,
                            target_page->slots_buffer_address(),
                            SlotsBuffer::CODE_ENTRY_SLOT,
                            slot,
                            SlotsBuffer::FAIL_ON_OVERFLOW)) {
      EvictEvacuationCandidate(target_page);
    }
3737
  }
3738
}
3739

3740

3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
void MarkCompactCollector::RecordCodeTargetPatch(Address pc, Code* target) {
  ASSERT(heap()->gc_state() == Heap::MARK_COMPACT);
  if (is_compacting()) {
    Code* host = heap()->isolate()->inner_pointer_to_code_cache()->
        GcSafeFindCodeForInnerPointer(pc);
    MarkBit mark_bit = Marking::MarkBitFrom(host);
    if (Marking::IsBlack(mark_bit)) {
      RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
      RecordRelocSlot(&rinfo, target);
    }
  }
}


3755 3756 3757
static inline SlotsBuffer::SlotType DecodeSlotType(
    SlotsBuffer::ObjectSlot slot) {
  return static_cast<SlotsBuffer::SlotType>(reinterpret_cast<intptr_t>(slot));
3758 3759 3760
}


3761 3762 3763 3764 3765 3766
void SlotsBuffer::UpdateSlots(Heap* heap) {
  PointersUpdatingVisitor v(heap);

  for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
    ObjectSlot slot = slots_[slot_idx];
    if (!IsTypedSlot(slot)) {
3767
      PointersUpdatingVisitor::UpdateSlot(heap, slot);
3768 3769 3770 3771 3772 3773 3774
    } else {
      ++slot_idx;
      ASSERT(slot_idx < idx_);
      UpdateSlot(&v,
                 DecodeSlotType(slot),
                 reinterpret_cast<Address>(slots_[slot_idx]));
    }
3775 3776 3777 3778
  }
}


3779 3780 3781 3782 3783 3784 3785
void SlotsBuffer::UpdateSlotsWithFilter(Heap* heap) {
  PointersUpdatingVisitor v(heap);

  for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
    ObjectSlot slot = slots_[slot_idx];
    if (!IsTypedSlot(slot)) {
      if (!IsOnInvalidatedCodeObject(reinterpret_cast<Address>(slot))) {
3786
        PointersUpdatingVisitor::UpdateSlot(heap, slot);
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
      }
    } else {
      ++slot_idx;
      ASSERT(slot_idx < idx_);
      Address pc = reinterpret_cast<Address>(slots_[slot_idx]);
      if (!IsOnInvalidatedCodeObject(pc)) {
        UpdateSlot(&v,
                   DecodeSlotType(slot),
                   reinterpret_cast<Address>(slots_[slot_idx]));
      }
    }
  }
}


3802 3803
SlotsBuffer* SlotsBufferAllocator::AllocateBuffer(SlotsBuffer* next_buffer) {
  return new SlotsBuffer(next_buffer);
3804 3805
}

3806

3807 3808
void SlotsBufferAllocator::DeallocateBuffer(SlotsBuffer* buffer) {
  delete buffer;
3809 3810 3811
}


3812 3813 3814 3815 3816 3817 3818 3819
void SlotsBufferAllocator::DeallocateChain(SlotsBuffer** buffer_address) {
  SlotsBuffer* buffer = *buffer_address;
  while (buffer != NULL) {
    SlotsBuffer* next_buffer = buffer->next();
    DeallocateBuffer(buffer);
    buffer = next_buffer;
  }
  *buffer_address = NULL;
3820 3821 3822
}


3823
} }  // namespace v8::internal