e81829c38d01892bf6f9390b72b47fa20e3a33d5
[platform/upstream/nodejs.git] / deps / v8 / src / heap / heap-inl.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_HEAP_HEAP_INL_H_
6 #define V8_HEAP_HEAP_INL_H_
7
8 #include <cmath>
9
10 #include "src/base/platform/platform.h"
11 #include "src/cpu-profiler.h"
12 #include "src/heap/heap.h"
13 #include "src/heap/store-buffer.h"
14 #include "src/heap/store-buffer-inl.h"
15 #include "src/heap-profiler.h"
16 #include "src/isolate.h"
17 #include "src/list-inl.h"
18 #include "src/msan.h"
19 #include "src/objects.h"
20
21 namespace v8 {
22 namespace internal {
23
24 void PromotionQueue::insert(HeapObject* target, int size) {
25   if (emergency_stack_ != NULL) {
26     emergency_stack_->Add(Entry(target, size));
27     return;
28   }
29
30   if ((rear_ - 2) < limit_) {
31     RelocateQueueHead();
32     emergency_stack_->Add(Entry(target, size));
33     return;
34   }
35
36   *(--rear_) = reinterpret_cast<intptr_t>(target);
37   *(--rear_) = size;
38 // Assert no overflow into live objects.
39 #ifdef DEBUG
40   SemiSpace::AssertValidRange(target->GetIsolate()->heap()->new_space()->top(),
41                               reinterpret_cast<Address>(rear_));
42 #endif
43 }
44
45
46 template <>
47 bool inline Heap::IsOneByte(Vector<const char> str, int chars) {
48   // TODO(dcarney): incorporate Latin-1 check when Latin-1 is supported?
49   return chars == str.length();
50 }
51
52
53 template <>
54 bool inline Heap::IsOneByte(String* str, int chars) {
55   return str->IsOneByteRepresentation();
56 }
57
58
59 AllocationResult Heap::AllocateInternalizedStringFromUtf8(
60     Vector<const char> str, int chars, uint32_t hash_field) {
61   if (IsOneByte(str, chars)) {
62     return AllocateOneByteInternalizedString(Vector<const uint8_t>::cast(str),
63                                              hash_field);
64   }
65   return AllocateInternalizedStringImpl<false>(str, chars, hash_field);
66 }
67
68
69 template <typename T>
70 AllocationResult Heap::AllocateInternalizedStringImpl(T t, int chars,
71                                                       uint32_t hash_field) {
72   if (IsOneByte(t, chars)) {
73     return AllocateInternalizedStringImpl<true>(t, chars, hash_field);
74   }
75   return AllocateInternalizedStringImpl<false>(t, chars, hash_field);
76 }
77
78
79 AllocationResult Heap::AllocateOneByteInternalizedString(
80     Vector<const uint8_t> str, uint32_t hash_field) {
81   CHECK_GE(String::kMaxLength, str.length());
82   // Compute map and object size.
83   Map* map = one_byte_internalized_string_map();
84   int size = SeqOneByteString::SizeFor(str.length());
85   AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, TENURED);
86
87   // Allocate string.
88   HeapObject* result;
89   {
90     AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE);
91     if (!allocation.To(&result)) return allocation;
92   }
93
94   // String maps are all immortal immovable objects.
95   result->set_map_no_write_barrier(map);
96   // Set length and hash fields of the allocated string.
97   String* answer = String::cast(result);
98   answer->set_length(str.length());
99   answer->set_hash_field(hash_field);
100
101   DCHECK_EQ(size, answer->Size());
102
103   // Fill in the characters.
104   MemCopy(answer->address() + SeqOneByteString::kHeaderSize, str.start(),
105           str.length());
106
107   return answer;
108 }
109
110
111 AllocationResult Heap::AllocateTwoByteInternalizedString(Vector<const uc16> str,
112                                                          uint32_t hash_field) {
113   CHECK_GE(String::kMaxLength, str.length());
114   // Compute map and object size.
115   Map* map = internalized_string_map();
116   int size = SeqTwoByteString::SizeFor(str.length());
117   AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, TENURED);
118
119   // Allocate string.
120   HeapObject* result;
121   {
122     AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE);
123     if (!allocation.To(&result)) return allocation;
124   }
125
126   result->set_map(map);
127   // Set length and hash fields of the allocated string.
128   String* answer = String::cast(result);
129   answer->set_length(str.length());
130   answer->set_hash_field(hash_field);
131
132   DCHECK_EQ(size, answer->Size());
133
134   // Fill in the characters.
135   MemCopy(answer->address() + SeqTwoByteString::kHeaderSize, str.start(),
136           str.length() * kUC16Size);
137
138   return answer;
139 }
140
141 AllocationResult Heap::CopyFixedArray(FixedArray* src) {
142   if (src->length() == 0) return src;
143   return CopyFixedArrayWithMap(src, src->map());
144 }
145
146
147 AllocationResult Heap::CopyFixedDoubleArray(FixedDoubleArray* src) {
148   if (src->length() == 0) return src;
149   return CopyFixedDoubleArrayWithMap(src, src->map());
150 }
151
152
153 AllocationResult Heap::CopyConstantPoolArray(ConstantPoolArray* src) {
154   if (src->length() == 0) return src;
155   return CopyConstantPoolArrayWithMap(src, src->map());
156 }
157
158
159 AllocationResult Heap::AllocateRaw(int size_in_bytes, AllocationSpace space,
160                                    AllocationSpace retry_space) {
161   DCHECK(AllowHandleAllocation::IsAllowed());
162   DCHECK(AllowHeapAllocation::IsAllowed());
163   DCHECK(gc_state_ == NOT_IN_GC);
164 #ifdef DEBUG
165   if (FLAG_gc_interval >= 0 && AllowAllocationFailure::IsAllowed(isolate_) &&
166       Heap::allocation_timeout_-- <= 0) {
167     return AllocationResult::Retry(space);
168   }
169   isolate_->counters()->objs_since_last_full()->Increment();
170   isolate_->counters()->objs_since_last_young()->Increment();
171 #endif
172
173   HeapObject* object;
174   AllocationResult allocation;
175   if (NEW_SPACE == space) {
176     allocation = new_space_.AllocateRaw(size_in_bytes);
177     if (always_allocate() && allocation.IsRetry() && retry_space != NEW_SPACE) {
178       space = retry_space;
179     } else {
180       if (allocation.To(&object)) {
181         OnAllocationEvent(object, size_in_bytes);
182       }
183       return allocation;
184     }
185   }
186
187   if (OLD_POINTER_SPACE == space) {
188     allocation = old_pointer_space_->AllocateRaw(size_in_bytes);
189   } else if (OLD_DATA_SPACE == space) {
190     allocation = old_data_space_->AllocateRaw(size_in_bytes);
191   } else if (CODE_SPACE == space) {
192     if (size_in_bytes <= code_space()->AreaSize()) {
193       allocation = code_space_->AllocateRaw(size_in_bytes);
194     } else {
195       // Large code objects are allocated in large object space.
196       allocation = lo_space_->AllocateRaw(size_in_bytes, EXECUTABLE);
197     }
198   } else if (LO_SPACE == space) {
199     allocation = lo_space_->AllocateRaw(size_in_bytes, NOT_EXECUTABLE);
200   } else if (CELL_SPACE == space) {
201     allocation = cell_space_->AllocateRaw(size_in_bytes);
202   } else if (PROPERTY_CELL_SPACE == space) {
203     allocation = property_cell_space_->AllocateRaw(size_in_bytes);
204   } else {
205     DCHECK(MAP_SPACE == space);
206     allocation = map_space_->AllocateRaw(size_in_bytes);
207   }
208   if (allocation.To(&object)) {
209     OnAllocationEvent(object, size_in_bytes);
210   } else {
211     old_gen_exhausted_ = true;
212   }
213   return allocation;
214 }
215
216
217 void Heap::OnAllocationEvent(HeapObject* object, int size_in_bytes) {
218   HeapProfiler* profiler = isolate_->heap_profiler();
219   if (profiler->is_tracking_allocations()) {
220     profiler->AllocationEvent(object->address(), size_in_bytes);
221   }
222
223   if (FLAG_verify_predictable) {
224     ++allocations_count_;
225
226     UpdateAllocationsHash(object);
227     UpdateAllocationsHash(size_in_bytes);
228
229     if ((FLAG_dump_allocations_digest_at_alloc > 0) &&
230         (--dump_allocations_hash_countdown_ == 0)) {
231       dump_allocations_hash_countdown_ = FLAG_dump_allocations_digest_at_alloc;
232       PrintAlloctionsHash();
233     }
234   }
235 }
236
237
238 void Heap::OnMoveEvent(HeapObject* target, HeapObject* source,
239                        int size_in_bytes) {
240   HeapProfiler* heap_profiler = isolate_->heap_profiler();
241   if (heap_profiler->is_tracking_object_moves()) {
242     heap_profiler->ObjectMoveEvent(source->address(), target->address(),
243                                    size_in_bytes);
244   }
245
246   if (isolate_->logger()->is_logging_code_events() ||
247       isolate_->cpu_profiler()->is_profiling()) {
248     if (target->IsSharedFunctionInfo()) {
249       PROFILE(isolate_, SharedFunctionInfoMoveEvent(source->address(),
250                                                     target->address()));
251     }
252   }
253
254   if (FLAG_verify_predictable) {
255     ++allocations_count_;
256
257     UpdateAllocationsHash(source);
258     UpdateAllocationsHash(target);
259     UpdateAllocationsHash(size_in_bytes);
260
261     if ((FLAG_dump_allocations_digest_at_alloc > 0) &&
262         (--dump_allocations_hash_countdown_ == 0)) {
263       dump_allocations_hash_countdown_ = FLAG_dump_allocations_digest_at_alloc;
264       PrintAlloctionsHash();
265     }
266   }
267 }
268
269
270 void Heap::UpdateAllocationsHash(HeapObject* object) {
271   Address object_address = object->address();
272   MemoryChunk* memory_chunk = MemoryChunk::FromAddress(object_address);
273   AllocationSpace allocation_space = memory_chunk->owner()->identity();
274
275   STATIC_ASSERT(kSpaceTagSize + kPageSizeBits <= 32);
276   uint32_t value =
277       static_cast<uint32_t>(object_address - memory_chunk->address()) |
278       (static_cast<uint32_t>(allocation_space) << kPageSizeBits);
279
280   UpdateAllocationsHash(value);
281 }
282
283
284 void Heap::UpdateAllocationsHash(uint32_t value) {
285   uint16_t c1 = static_cast<uint16_t>(value);
286   uint16_t c2 = static_cast<uint16_t>(value >> 16);
287   raw_allocations_hash_ =
288       StringHasher::AddCharacterCore(raw_allocations_hash_, c1);
289   raw_allocations_hash_ =
290       StringHasher::AddCharacterCore(raw_allocations_hash_, c2);
291 }
292
293
294 void Heap::PrintAlloctionsHash() {
295   uint32_t hash = StringHasher::GetHashCore(raw_allocations_hash_);
296   PrintF("\n### Allocations = %u, hash = 0x%08x\n", allocations_count_, hash);
297 }
298
299
300 void Heap::FinalizeExternalString(String* string) {
301   DCHECK(string->IsExternalString());
302   v8::String::ExternalStringResourceBase** resource_addr =
303       reinterpret_cast<v8::String::ExternalStringResourceBase**>(
304           reinterpret_cast<byte*>(string) + ExternalString::kResourceOffset -
305           kHeapObjectTag);
306
307   // Dispose of the C++ object if it has not already been disposed.
308   if (*resource_addr != NULL) {
309     (*resource_addr)->Dispose();
310     *resource_addr = NULL;
311   }
312 }
313
314
315 bool Heap::InNewSpace(Object* object) {
316   bool result = new_space_.Contains(object);
317   DCHECK(!result ||                 // Either not in new space
318          gc_state_ != NOT_IN_GC ||  // ... or in the middle of GC
319          InToSpace(object));        // ... or in to-space (where we allocate).
320   return result;
321 }
322
323
324 bool Heap::InNewSpace(Address address) { return new_space_.Contains(address); }
325
326
327 bool Heap::InFromSpace(Object* object) {
328   return new_space_.FromSpaceContains(object);
329 }
330
331
332 bool Heap::InToSpace(Object* object) {
333   return new_space_.ToSpaceContains(object);
334 }
335
336
337 bool Heap::InOldPointerSpace(Address address) {
338   return old_pointer_space_->Contains(address);
339 }
340
341
342 bool Heap::InOldPointerSpace(Object* object) {
343   return InOldPointerSpace(reinterpret_cast<Address>(object));
344 }
345
346
347 bool Heap::InOldDataSpace(Address address) {
348   return old_data_space_->Contains(address);
349 }
350
351
352 bool Heap::InOldDataSpace(Object* object) {
353   return InOldDataSpace(reinterpret_cast<Address>(object));
354 }
355
356
357 bool Heap::OldGenerationAllocationLimitReached() {
358   if (!incremental_marking()->IsStopped()) return false;
359   return OldGenerationSpaceAvailable() < 0;
360 }
361
362
363 bool Heap::ShouldBePromoted(Address old_address, int object_size) {
364   NewSpacePage* page = NewSpacePage::FromAddress(old_address);
365   Address age_mark = new_space_.age_mark();
366   return page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK) &&
367          (!page->ContainsLimit(age_mark) || old_address < age_mark);
368 }
369
370
371 void Heap::RecordWrite(Address address, int offset) {
372   if (!InNewSpace(address)) store_buffer_.Mark(address + offset);
373 }
374
375
376 void Heap::RecordWrites(Address address, int start, int len) {
377   if (!InNewSpace(address)) {
378     for (int i = 0; i < len; i++) {
379       store_buffer_.Mark(address + start + i * kPointerSize);
380     }
381   }
382 }
383
384
385 OldSpace* Heap::TargetSpace(HeapObject* object) {
386   InstanceType type = object->map()->instance_type();
387   AllocationSpace space = TargetSpaceId(type);
388   return (space == OLD_POINTER_SPACE) ? old_pointer_space_ : old_data_space_;
389 }
390
391
392 AllocationSpace Heap::TargetSpaceId(InstanceType type) {
393   // Heap numbers and sequential strings are promoted to old data space, all
394   // other object types are promoted to old pointer space.  We do not use
395   // object->IsHeapNumber() and object->IsSeqString() because we already
396   // know that object has the heap object tag.
397
398   // These objects are never allocated in new space.
399   DCHECK(type != MAP_TYPE);
400   DCHECK(type != CODE_TYPE);
401   DCHECK(type != ODDBALL_TYPE);
402   DCHECK(type != CELL_TYPE);
403   DCHECK(type != PROPERTY_CELL_TYPE);
404
405   if (type <= LAST_NAME_TYPE) {
406     if (type == SYMBOL_TYPE) return OLD_POINTER_SPACE;
407     DCHECK(type < FIRST_NONSTRING_TYPE);
408     // There are four string representations: sequential strings, external
409     // strings, cons strings, and sliced strings.
410     // Only the latter two contain non-map-word pointers to heap objects.
411     return ((type & kIsIndirectStringMask) == kIsIndirectStringTag)
412                ? OLD_POINTER_SPACE
413                : OLD_DATA_SPACE;
414   } else {
415     return (type <= LAST_DATA_TYPE) ? OLD_DATA_SPACE : OLD_POINTER_SPACE;
416   }
417 }
418
419
420 bool Heap::AllowedToBeMigrated(HeapObject* obj, AllocationSpace dst) {
421   // Object migration is governed by the following rules:
422   //
423   // 1) Objects in new-space can be migrated to one of the old spaces
424   //    that matches their target space or they stay in new-space.
425   // 2) Objects in old-space stay in the same space when migrating.
426   // 3) Fillers (two or more words) can migrate due to left-trimming of
427   //    fixed arrays in new-space, old-data-space and old-pointer-space.
428   // 4) Fillers (one word) can never migrate, they are skipped by
429   //    incremental marking explicitly to prevent invalid pattern.
430   // 5) Short external strings can end up in old pointer space when a cons
431   //    string in old pointer space is made external (String::MakeExternal).
432   //
433   // Since this function is used for debugging only, we do not place
434   // asserts here, but check everything explicitly.
435   if (obj->map() == one_pointer_filler_map()) return false;
436   InstanceType type = obj->map()->instance_type();
437   MemoryChunk* chunk = MemoryChunk::FromAddress(obj->address());
438   AllocationSpace src = chunk->owner()->identity();
439   switch (src) {
440     case NEW_SPACE:
441       return dst == src || dst == TargetSpaceId(type);
442     case OLD_POINTER_SPACE:
443       return dst == src && (dst == TargetSpaceId(type) || obj->IsFiller() ||
444                             obj->IsExternalString());
445     case OLD_DATA_SPACE:
446       return dst == src && dst == TargetSpaceId(type);
447     case CODE_SPACE:
448       return dst == src && type == CODE_TYPE;
449     case MAP_SPACE:
450     case CELL_SPACE:
451     case PROPERTY_CELL_SPACE:
452     case LO_SPACE:
453       return false;
454   }
455   UNREACHABLE();
456   return false;
457 }
458
459
460 void Heap::CopyBlock(Address dst, Address src, int byte_size) {
461   CopyWords(reinterpret_cast<Object**>(dst), reinterpret_cast<Object**>(src),
462             static_cast<size_t>(byte_size / kPointerSize));
463 }
464
465
466 void Heap::MoveBlock(Address dst, Address src, int byte_size) {
467   DCHECK(IsAligned(byte_size, kPointerSize));
468
469   int size_in_words = byte_size / kPointerSize;
470
471   if ((dst < src) || (dst >= (src + byte_size))) {
472     Object** src_slot = reinterpret_cast<Object**>(src);
473     Object** dst_slot = reinterpret_cast<Object**>(dst);
474     Object** end_slot = src_slot + size_in_words;
475
476     while (src_slot != end_slot) {
477       *dst_slot++ = *src_slot++;
478     }
479   } else {
480     MemMove(dst, src, static_cast<size_t>(byte_size));
481   }
482 }
483
484
485 void Heap::ScavengePointer(HeapObject** p) { ScavengeObject(p, *p); }
486
487
488 AllocationMemento* Heap::FindAllocationMemento(HeapObject* object) {
489   // Check if there is potentially a memento behind the object. If
490   // the last word of the memento is on another page we return
491   // immediately.
492   Address object_address = object->address();
493   Address memento_address = object_address + object->Size();
494   Address last_memento_word_address = memento_address + kPointerSize;
495   if (!NewSpacePage::OnSamePage(object_address, last_memento_word_address)) {
496     return NULL;
497   }
498
499   HeapObject* candidate = HeapObject::FromAddress(memento_address);
500   Map* candidate_map = candidate->map();
501   // This fast check may peek at an uninitialized word. However, the slow check
502   // below (memento_address == top) ensures that this is safe. Mark the word as
503   // initialized to silence MemorySanitizer warnings.
504   MSAN_MEMORY_IS_INITIALIZED(&candidate_map, sizeof(candidate_map));
505   if (candidate_map != allocation_memento_map()) return NULL;
506
507   // Either the object is the last object in the new space, or there is another
508   // object of at least word size (the header map word) following it, so
509   // suffices to compare ptr and top here. Note that technically we do not have
510   // to compare with the current top pointer of the from space page during GC,
511   // since we always install filler objects above the top pointer of a from
512   // space page when performing a garbage collection. However, always performing
513   // the test makes it possible to have a single, unified version of
514   // FindAllocationMemento that is used both by the GC and the mutator.
515   Address top = NewSpaceTop();
516   DCHECK(memento_address == top ||
517          memento_address + HeapObject::kHeaderSize <= top ||
518          !NewSpacePage::OnSamePage(memento_address, top));
519   if (memento_address == top) return NULL;
520
521   AllocationMemento* memento = AllocationMemento::cast(candidate);
522   if (!memento->IsValid()) return NULL;
523   return memento;
524 }
525
526
527 void Heap::UpdateAllocationSiteFeedback(HeapObject* object,
528                                         ScratchpadSlotMode mode) {
529   Heap* heap = object->GetHeap();
530   DCHECK(heap->InFromSpace(object));
531
532   if (!FLAG_allocation_site_pretenuring ||
533       !AllocationSite::CanTrack(object->map()->instance_type()))
534     return;
535
536   AllocationMemento* memento = heap->FindAllocationMemento(object);
537   if (memento == NULL) return;
538
539   if (memento->GetAllocationSite()->IncrementMementoFoundCount()) {
540     heap->AddAllocationSiteToScratchpad(memento->GetAllocationSite(), mode);
541   }
542 }
543
544
545 void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
546   DCHECK(object->GetIsolate()->heap()->InFromSpace(object));
547
548   // We use the first word (where the map pointer usually is) of a heap
549   // object to record the forwarding pointer.  A forwarding pointer can
550   // point to an old space, the code space, or the to space of the new
551   // generation.
552   MapWord first_word = object->map_word();
553
554   // If the first word is a forwarding address, the object has already been
555   // copied.
556   if (first_word.IsForwardingAddress()) {
557     HeapObject* dest = first_word.ToForwardingAddress();
558     DCHECK(object->GetIsolate()->heap()->InFromSpace(*p));
559     *p = dest;
560     return;
561   }
562
563   UpdateAllocationSiteFeedback(object, IGNORE_SCRATCHPAD_SLOT);
564
565   // AllocationMementos are unrooted and shouldn't survive a scavenge
566   DCHECK(object->map() != object->GetHeap()->allocation_memento_map());
567   // Call the slow part of scavenge object.
568   return ScavengeObjectSlow(p, object);
569 }
570
571
572 bool Heap::CollectGarbage(AllocationSpace space, const char* gc_reason,
573                           const v8::GCCallbackFlags callbackFlags) {
574   const char* collector_reason = NULL;
575   GarbageCollector collector = SelectGarbageCollector(space, &collector_reason);
576   return CollectGarbage(collector, gc_reason, collector_reason, callbackFlags);
577 }
578
579
580 Isolate* Heap::isolate() {
581   return reinterpret_cast<Isolate*>(
582       reinterpret_cast<intptr_t>(this) -
583       reinterpret_cast<size_t>(reinterpret_cast<Isolate*>(16)->heap()) + 16);
584 }
585
586
587 // Calls the FUNCTION_CALL function and retries it up to three times
588 // to guarantee that any allocations performed during the call will
589 // succeed if there's enough memory.
590
591 // Warning: Do not use the identifiers __object__, __maybe_object__ or
592 // __scope__ in a call to this macro.
593
594 #define RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE) \
595   if (__allocation__.To(&__object__)) {                   \
596     DCHECK(__object__ != (ISOLATE)->heap()->exception()); \
597     RETURN_VALUE;                                         \
598   }
599
600 #define CALL_AND_RETRY(ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY)    \
601   do {                                                                        \
602     AllocationResult __allocation__ = FUNCTION_CALL;                          \
603     Object* __object__ = NULL;                                                \
604     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
605     (ISOLATE)->heap()->CollectGarbage(__allocation__.RetrySpace(),            \
606                                       "allocation failure");                  \
607     __allocation__ = FUNCTION_CALL;                                           \
608     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
609     (ISOLATE)->counters()->gc_last_resort_from_handles()->Increment();        \
610     (ISOLATE)->heap()->CollectAllAvailableGarbage("last resort gc");          \
611     {                                                                         \
612       AlwaysAllocateScope __scope__(ISOLATE);                                 \
613       __allocation__ = FUNCTION_CALL;                                         \
614     }                                                                         \
615     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
616     /* TODO(1181417): Fix this. */                                            \
617     v8::internal::Heap::FatalProcessOutOfMemory("CALL_AND_RETRY_LAST", true); \
618     RETURN_EMPTY;                                                             \
619   } while (false)
620
621 #define CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL, RETURN_VALUE, \
622                               RETURN_EMPTY)                         \
623   CALL_AND_RETRY(ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY)
624
625 #define CALL_HEAP_FUNCTION(ISOLATE, FUNCTION_CALL, TYPE)                      \
626   CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL,                               \
627                         return Handle<TYPE>(TYPE::cast(__object__), ISOLATE), \
628                         return Handle<TYPE>())
629
630
631 #define CALL_HEAP_FUNCTION_VOID(ISOLATE, FUNCTION_CALL) \
632   CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL, return, return)
633
634
635 void ExternalStringTable::AddString(String* string) {
636   DCHECK(string->IsExternalString());
637   if (heap_->InNewSpace(string)) {
638     new_space_strings_.Add(string);
639   } else {
640     old_space_strings_.Add(string);
641   }
642 }
643
644
645 void ExternalStringTable::Iterate(ObjectVisitor* v) {
646   if (!new_space_strings_.is_empty()) {
647     Object** start = &new_space_strings_[0];
648     v->VisitPointers(start, start + new_space_strings_.length());
649   }
650   if (!old_space_strings_.is_empty()) {
651     Object** start = &old_space_strings_[0];
652     v->VisitPointers(start, start + old_space_strings_.length());
653   }
654 }
655
656
657 // Verify() is inline to avoid ifdef-s around its calls in release
658 // mode.
659 void ExternalStringTable::Verify() {
660 #ifdef DEBUG
661   for (int i = 0; i < new_space_strings_.length(); ++i) {
662     Object* obj = Object::cast(new_space_strings_[i]);
663     DCHECK(heap_->InNewSpace(obj));
664     DCHECK(obj != heap_->the_hole_value());
665   }
666   for (int i = 0; i < old_space_strings_.length(); ++i) {
667     Object* obj = Object::cast(old_space_strings_[i]);
668     DCHECK(!heap_->InNewSpace(obj));
669     DCHECK(obj != heap_->the_hole_value());
670   }
671 #endif
672 }
673
674
675 void ExternalStringTable::AddOldString(String* string) {
676   DCHECK(string->IsExternalString());
677   DCHECK(!heap_->InNewSpace(string));
678   old_space_strings_.Add(string);
679 }
680
681
682 void ExternalStringTable::ShrinkNewStrings(int position) {
683   new_space_strings_.Rewind(position);
684 #ifdef VERIFY_HEAP
685   if (FLAG_verify_heap) {
686     Verify();
687   }
688 #endif
689 }
690
691
692 void Heap::ClearInstanceofCache() {
693   set_instanceof_cache_function(Smi::FromInt(0));
694 }
695
696
697 Object* Heap::ToBoolean(bool condition) {
698   return condition ? true_value() : false_value();
699 }
700
701
702 void Heap::CompletelyClearInstanceofCache() {
703   set_instanceof_cache_map(Smi::FromInt(0));
704   set_instanceof_cache_function(Smi::FromInt(0));
705 }
706
707
708 AlwaysAllocateScope::AlwaysAllocateScope(Isolate* isolate)
709     : heap_(isolate->heap()), daf_(isolate) {
710   // We shouldn't hit any nested scopes, because that requires
711   // non-handle code to call handle code. The code still works but
712   // performance will degrade, so we want to catch this situation
713   // in debug mode.
714   DCHECK(heap_->always_allocate_scope_depth_ == 0);
715   heap_->always_allocate_scope_depth_++;
716 }
717
718
719 AlwaysAllocateScope::~AlwaysAllocateScope() {
720   heap_->always_allocate_scope_depth_--;
721   DCHECK(heap_->always_allocate_scope_depth_ == 0);
722 }
723
724
725 GCCallbacksScope::GCCallbacksScope(Heap* heap) : heap_(heap) {
726   heap_->gc_callbacks_depth_++;
727 }
728
729
730 GCCallbacksScope::~GCCallbacksScope() { heap_->gc_callbacks_depth_--; }
731
732
733 bool GCCallbacksScope::CheckReenter() {
734   return heap_->gc_callbacks_depth_ == 1;
735 }
736
737
738 void VerifyPointersVisitor::VisitPointers(Object** start, Object** end) {
739   for (Object** current = start; current < end; current++) {
740     if ((*current)->IsHeapObject()) {
741       HeapObject* object = HeapObject::cast(*current);
742       CHECK(object->GetIsolate()->heap()->Contains(object));
743       CHECK(object->map()->IsMap());
744     }
745   }
746 }
747
748
749 void VerifySmisVisitor::VisitPointers(Object** start, Object** end) {
750   for (Object** current = start; current < end; current++) {
751     CHECK((*current)->IsSmi());
752   }
753 }
754 }
755 }  // namespace v8::internal
756
757 #endif  // V8_HEAP_HEAP_INL_H_