1 // Copyright 2014 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.
5 #include "src/factory.h"
7 #include "src/allocation-site-scopes.h"
8 #include "src/conversions.h"
9 #include "src/isolate-inl.h"
10 #include "src/macro-assembler.h"
17 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
20 isolate()->heap()->Allocate(*map, space),
26 Handle<T> Factory::New(Handle<Map> map,
27 AllocationSpace space,
28 Handle<AllocationSite> allocation_site) {
31 isolate()->heap()->Allocate(*map, space, *allocation_site),
36 Handle<HeapObject> Factory::NewFillerObject(int size,
38 AllocationSpace space) {
41 isolate()->heap()->AllocateFillerObject(size, double_align, space),
46 Handle<Box> Factory::NewBox(Handle<Object> value) {
47 Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
48 result->set_value(*value);
53 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
54 const char* to_string,
55 Handle<Object> to_number,
57 Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
58 Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
63 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
67 isolate()->heap()->AllocateFixedArray(size, pretenure),
72 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
73 PretenureFlag pretenure) {
77 isolate()->heap()->AllocateFixedArrayWithFiller(size,
84 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
87 isolate()->heap()->AllocateUninitializedFixedArray(size),
92 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
93 PretenureFlag pretenure) {
97 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
102 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
104 PretenureFlag pretenure) {
106 Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
108 Handle<FixedDoubleArray> double_array =
109 Handle<FixedDoubleArray>::cast(array);
110 for (int i = 0; i < size; ++i) {
111 double_array->set_the_hole(i);
118 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
119 const ConstantPoolArray::NumberOfEntries& small) {
120 DCHECK(small.total_count() > 0);
123 isolate()->heap()->AllocateConstantPoolArray(small),
128 Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
129 const ConstantPoolArray::NumberOfEntries& small,
130 const ConstantPoolArray::NumberOfEntries& extended) {
131 DCHECK(small.total_count() > 0);
132 DCHECK(extended.total_count() > 0);
135 isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
140 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
141 return OrderedHashSet::Allocate(isolate(), 4);
145 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
146 return OrderedHashMap::Allocate(isolate(), 4);
150 Handle<AccessorPair> Factory::NewAccessorPair() {
151 Handle<AccessorPair> accessors =
152 Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
153 accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
154 accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
159 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
160 Handle<TypeFeedbackInfo> info =
161 Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
162 info->initialize_storage();
167 // Internalized strings are created in the old generation (data space).
168 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
169 Utf8StringKey key(string, isolate()->heap()->HashSeed());
170 return InternalizeStringWithKey(&key);
174 // Internalized strings are created in the old generation (data space).
175 Handle<String> Factory::InternalizeString(Handle<String> string) {
176 if (string->IsInternalizedString()) return string;
177 return StringTable::LookupString(isolate(), string);
181 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
182 OneByteStringKey key(string, isolate()->heap()->HashSeed());
183 return InternalizeStringWithKey(&key);
187 Handle<String> Factory::InternalizeOneByteString(
188 Handle<SeqOneByteString> string, int from, int length) {
189 SubStringKey<uint8_t> key(string, from, length);
190 return InternalizeStringWithKey(&key);
194 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
195 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
196 return InternalizeStringWithKey(&key);
200 template<class StringTableKey>
201 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
202 return StringTable::LookupKey(isolate(), key);
206 template Handle<String> Factory::InternalizeStringWithKey<
207 SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
208 template Handle<String> Factory::InternalizeStringWithKey<
209 SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
212 MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
213 PretenureFlag pretenure) {
214 int length = string.length();
215 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
216 Handle<SeqOneByteString> result;
217 ASSIGN_RETURN_ON_EXCEPTION(
220 NewRawOneByteString(string.length(), pretenure),
223 DisallowHeapAllocation no_gc;
224 // Copy the characters into the new object.
225 CopyChars(SeqOneByteString::cast(*result)->GetChars(),
231 MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
232 PretenureFlag pretenure) {
233 // Check for ASCII first since this is the common case.
234 const char* start = string.start();
235 int length = string.length();
236 int non_ascii_start = String::NonAsciiStart(start, length);
237 if (non_ascii_start >= length) {
238 // If the string is ASCII, we do not need to convert the characters
239 // since UTF8 is backwards compatible with ASCII.
240 return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
243 // Non-ASCII and we need to decode.
244 Access<UnicodeCache::Utf8Decoder>
245 decoder(isolate()->unicode_cache()->utf8_decoder());
246 decoder->Reset(string.start() + non_ascii_start,
247 length - non_ascii_start);
248 int utf16_length = decoder->Utf16Length();
249 DCHECK(utf16_length > 0);
251 Handle<SeqTwoByteString> result;
252 ASSIGN_RETURN_ON_EXCEPTION(
254 NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
256 // Copy ascii portion.
257 uint16_t* data = result->GetChars();
258 const char* ascii_data = string.start();
259 for (int i = 0; i < non_ascii_start; i++) {
260 *data++ = *ascii_data++;
262 // Now write the remainder.
263 decoder->WriteUtf16(data, utf16_length);
268 MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
269 PretenureFlag pretenure) {
270 int length = string.length();
271 const uc16* start = string.start();
272 if (String::IsOneByte(start, length)) {
273 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
274 Handle<SeqOneByteString> result;
275 ASSIGN_RETURN_ON_EXCEPTION(
278 NewRawOneByteString(length, pretenure),
280 CopyChars(result->GetChars(), start, length);
283 Handle<SeqTwoByteString> result;
284 ASSIGN_RETURN_ON_EXCEPTION(
287 NewRawTwoByteString(length, pretenure),
289 CopyChars(result->GetChars(), start, length);
295 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
297 uint32_t hash_field) {
300 isolate()->heap()->AllocateInternalizedStringFromUtf8(
301 str, chars, hash_field),
306 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
307 Vector<const uint8_t> str,
308 uint32_t hash_field) {
311 isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
316 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
317 Vector<const uc16> str,
318 uint32_t hash_field) {
321 isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
326 Handle<String> Factory::NewInternalizedStringImpl(
327 Handle<String> string, int chars, uint32_t hash_field) {
330 isolate()->heap()->AllocateInternalizedStringImpl(
331 *string, chars, hash_field),
336 MaybeHandle<Map> Factory::InternalizedStringMapForString(
337 Handle<String> string) {
338 // If the string is in new space it cannot be used as internalized.
339 if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
341 // Find the corresponding internalized string map for strings.
342 switch (string->map()->instance_type()) {
343 case STRING_TYPE: return internalized_string_map();
344 case ASCII_STRING_TYPE: return ascii_internalized_string_map();
345 case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
346 case EXTERNAL_ASCII_STRING_TYPE:
347 return external_ascii_internalized_string_map();
348 case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
349 return external_internalized_string_with_one_byte_data_map();
350 case SHORT_EXTERNAL_STRING_TYPE:
351 return short_external_internalized_string_map();
352 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
353 return short_external_ascii_internalized_string_map();
354 case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
355 return short_external_internalized_string_with_one_byte_data_map();
356 default: return MaybeHandle<Map>(); // No match found.
361 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
362 int length, PretenureFlag pretenure) {
363 if (length > String::kMaxLength || length < 0) {
364 return isolate()->Throw<SeqOneByteString>(NewInvalidStringLengthError());
368 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
373 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
374 int length, PretenureFlag pretenure) {
375 if (length > String::kMaxLength || length < 0) {
376 return isolate()->Throw<SeqTwoByteString>(NewInvalidStringLengthError());
380 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
385 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
386 if (code <= String::kMaxOneByteCharCodeU) {
388 DisallowHeapAllocation no_allocation;
389 Object* value = single_character_string_cache()->get(code);
390 if (value != *undefined_value()) {
391 return handle(String::cast(value), isolate());
395 buffer[0] = static_cast<uint8_t>(code);
396 Handle<String> result =
397 InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
398 single_character_string_cache()->set(code, *result);
401 DCHECK(code <= String::kMaxUtf16CodeUnitU);
403 Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
404 result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
409 // Returns true for a character in a range. Both limits are inclusive.
410 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
411 // This makes uses of the the unsigned wraparound.
412 return character - from <= to - from;
416 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
419 // Numeric strings have a different hash algorithm not known by
420 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
421 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
422 Handle<String> result;
423 if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
429 // Now we know the length is 2, we might as well make use of that fact
430 // when building the new string.
431 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
433 DCHECK(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
434 Handle<SeqOneByteString> str =
435 isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
436 uint8_t* dest = str->GetChars();
437 dest[0] = static_cast<uint8_t>(c1);
438 dest[1] = static_cast<uint8_t>(c2);
441 Handle<SeqTwoByteString> str =
442 isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
443 uc16* dest = str->GetChars();
451 template<typename SinkChar, typename StringType>
452 Handle<String> ConcatStringContent(Handle<StringType> result,
453 Handle<String> first,
454 Handle<String> second) {
455 DisallowHeapAllocation pointer_stays_valid;
456 SinkChar* sink = result->GetChars();
457 String::WriteToFlat(*first, sink, 0, first->length());
458 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
463 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
464 Handle<String> right) {
465 int left_length = left->length();
466 if (left_length == 0) return right;
467 int right_length = right->length();
468 if (right_length == 0) return left;
470 int length = left_length + right_length;
473 uint16_t c1 = left->Get(0);
474 uint16_t c2 = right->Get(0);
475 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
478 // Make sure that an out of memory exception is thrown if the length
479 // of the new cons string is too large.
480 if (length > String::kMaxLength || length < 0) {
481 return isolate()->Throw<String>(NewInvalidStringLengthError());
484 bool left_is_one_byte = left->IsOneByteRepresentation();
485 bool right_is_one_byte = right->IsOneByteRepresentation();
486 bool is_one_byte = left_is_one_byte && right_is_one_byte;
487 bool is_one_byte_data_in_two_byte_string = false;
489 // At least one of the strings uses two-byte representation so we
490 // can't use the fast case code for short ASCII strings below, but
491 // we can try to save memory if all chars actually fit in ASCII.
492 is_one_byte_data_in_two_byte_string =
493 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
494 if (is_one_byte_data_in_two_byte_string) {
495 isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
499 // If the resulting string is small make a flat string.
500 if (length < ConsString::kMinLength) {
501 // Note that neither of the two inputs can be a slice because:
502 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
503 DCHECK(left->IsFlat());
504 DCHECK(right->IsFlat());
506 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
508 Handle<SeqOneByteString> result =
509 NewRawOneByteString(length).ToHandleChecked();
510 DisallowHeapAllocation no_gc;
511 uint8_t* dest = result->GetChars();
513 const uint8_t* src = left->IsExternalString()
514 ? Handle<ExternalAsciiString>::cast(left)->GetChars()
515 : Handle<SeqOneByteString>::cast(left)->GetChars();
516 for (int i = 0; i < left_length; i++) *dest++ = src[i];
518 src = right->IsExternalString()
519 ? Handle<ExternalAsciiString>::cast(right)->GetChars()
520 : Handle<SeqOneByteString>::cast(right)->GetChars();
521 for (int i = 0; i < right_length; i++) *dest++ = src[i];
525 return (is_one_byte_data_in_two_byte_string)
526 ? ConcatStringContent<uint8_t>(
527 NewRawOneByteString(length).ToHandleChecked(), left, right)
528 : ConcatStringContent<uc16>(
529 NewRawTwoByteString(length).ToHandleChecked(), left, right);
532 Handle<Map> map = (is_one_byte || is_one_byte_data_in_two_byte_string)
533 ? cons_ascii_string_map() : cons_string_map();
534 Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
536 DisallowHeapAllocation no_gc;
537 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
539 result->set_hash_field(String::kEmptyHashField);
540 result->set_length(length);
541 result->set_first(*left, mode);
542 result->set_second(*right, mode);
547 Handle<String> Factory::NewProperSubString(Handle<String> str,
551 if (FLAG_verify_heap) str->StringVerify();
553 DCHECK(begin > 0 || end < str->length());
555 str = String::Flatten(str);
557 int length = end - begin;
558 if (length <= 0) return empty_string();
560 return LookupSingleCharacterStringFromCode(str->Get(begin));
563 // Optimization for 2-byte strings often used as keys in a decompression
564 // dictionary. Check whether we already have the string in the string
565 // table to prevent creation of many unnecessary strings.
566 uint16_t c1 = str->Get(begin);
567 uint16_t c2 = str->Get(begin + 1);
568 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
571 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
572 if (str->IsOneByteRepresentation()) {
573 Handle<SeqOneByteString> result =
574 NewRawOneByteString(length).ToHandleChecked();
575 uint8_t* dest = result->GetChars();
576 DisallowHeapAllocation no_gc;
577 String::WriteToFlat(*str, dest, begin, end);
580 Handle<SeqTwoByteString> result =
581 NewRawTwoByteString(length).ToHandleChecked();
582 uc16* dest = result->GetChars();
583 DisallowHeapAllocation no_gc;
584 String::WriteToFlat(*str, dest, begin, end);
591 if (str->IsSlicedString()) {
592 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
593 str = Handle<String>(slice->parent(), isolate());
594 offset += slice->offset();
597 DCHECK(str->IsSeqString() || str->IsExternalString());
598 Handle<Map> map = str->IsOneByteRepresentation() ? sliced_ascii_string_map()
599 : sliced_string_map();
600 Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
602 slice->set_hash_field(String::kEmptyHashField);
603 slice->set_length(length);
604 slice->set_parent(*str);
605 slice->set_offset(offset);
610 MaybeHandle<String> Factory::NewExternalStringFromAscii(
611 const ExternalAsciiString::Resource* resource) {
612 size_t length = resource->length();
613 if (length > static_cast<size_t>(String::kMaxLength)) {
614 return isolate()->Throw<String>(NewInvalidStringLengthError());
617 Handle<Map> map = external_ascii_string_map();
618 Handle<ExternalAsciiString> external_string =
619 New<ExternalAsciiString>(map, NEW_SPACE);
620 external_string->set_length(static_cast<int>(length));
621 external_string->set_hash_field(String::kEmptyHashField);
622 external_string->set_resource(resource);
624 return external_string;
628 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
629 const ExternalTwoByteString::Resource* resource) {
630 size_t length = resource->length();
631 if (length > static_cast<size_t>(String::kMaxLength)) {
632 return isolate()->Throw<String>(NewInvalidStringLengthError());
635 // For small strings we check whether the resource contains only
636 // one byte characters. If yes, we use a different string map.
637 static const size_t kOneByteCheckLengthLimit = 32;
638 bool is_one_byte = length <= kOneByteCheckLengthLimit &&
639 String::IsOneByte(resource->data(), static_cast<int>(length));
640 Handle<Map> map = is_one_byte ?
641 external_string_with_one_byte_data_map() : external_string_map();
642 Handle<ExternalTwoByteString> external_string =
643 New<ExternalTwoByteString>(map, NEW_SPACE);
644 external_string->set_length(static_cast<int>(length));
645 external_string->set_hash_field(String::kEmptyHashField);
646 external_string->set_resource(resource);
648 return external_string;
652 Handle<Symbol> Factory::NewSymbol() {
655 isolate()->heap()->AllocateSymbol(),
660 Handle<Symbol> Factory::NewPrivateSymbol() {
661 Handle<Symbol> symbol = NewSymbol();
662 symbol->set_is_private(true);
667 Handle<Context> Factory::NewNativeContext() {
668 Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
669 array->set_map_no_write_barrier(*native_context_map());
670 Handle<Context> context = Handle<Context>::cast(array);
671 context->set_js_array_maps(*undefined_value());
672 DCHECK(context->IsNativeContext());
677 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
678 Handle<ScopeInfo> scope_info) {
679 Handle<FixedArray> array =
680 NewFixedArray(scope_info->ContextLength(), TENURED);
681 array->set_map_no_write_barrier(*global_context_map());
682 Handle<Context> context = Handle<Context>::cast(array);
683 context->set_closure(*function);
684 context->set_previous(function->context());
685 context->set_extension(*scope_info);
686 context->set_global_object(function->context()->global_object());
687 DCHECK(context->IsGlobalContext());
692 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
693 Handle<FixedArray> array =
694 NewFixedArray(scope_info->ContextLength(), TENURED);
695 array->set_map_no_write_barrier(*module_context_map());
696 // Instance link will be set later.
697 Handle<Context> context = Handle<Context>::cast(array);
698 context->set_extension(Smi::FromInt(0));
703 Handle<Context> Factory::NewFunctionContext(int length,
704 Handle<JSFunction> function) {
705 DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
706 Handle<FixedArray> array = NewFixedArray(length);
707 array->set_map_no_write_barrier(*function_context_map());
708 Handle<Context> context = Handle<Context>::cast(array);
709 context->set_closure(*function);
710 context->set_previous(function->context());
711 context->set_extension(Smi::FromInt(0));
712 context->set_global_object(function->context()->global_object());
717 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
718 Handle<Context> previous,
720 Handle<Object> thrown_object) {
721 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
722 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
723 array->set_map_no_write_barrier(*catch_context_map());
724 Handle<Context> context = Handle<Context>::cast(array);
725 context->set_closure(*function);
726 context->set_previous(*previous);
727 context->set_extension(*name);
728 context->set_global_object(previous->global_object());
729 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
734 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
735 Handle<Context> previous,
736 Handle<JSReceiver> extension) {
737 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
738 array->set_map_no_write_barrier(*with_context_map());
739 Handle<Context> context = Handle<Context>::cast(array);
740 context->set_closure(*function);
741 context->set_previous(*previous);
742 context->set_extension(*extension);
743 context->set_global_object(previous->global_object());
748 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
749 Handle<Context> previous,
750 Handle<ScopeInfo> scope_info) {
751 Handle<FixedArray> array =
752 NewFixedArrayWithHoles(scope_info->ContextLength());
753 array->set_map_no_write_barrier(*block_context_map());
754 Handle<Context> context = Handle<Context>::cast(array);
755 context->set_closure(*function);
756 context->set_previous(*previous);
757 context->set_extension(*scope_info);
758 context->set_global_object(previous->global_object());
763 Handle<Struct> Factory::NewStruct(InstanceType type) {
766 isolate()->heap()->AllocateStruct(type),
771 Handle<CodeCache> Factory::NewCodeCache() {
772 Handle<CodeCache> code_cache =
773 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
774 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
775 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
780 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
781 int aliased_context_slot) {
782 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
783 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
784 entry->set_aliased_context_slot(aliased_context_slot);
789 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
790 return Handle<DeclaredAccessorDescriptor>::cast(
791 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
795 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
796 Handle<DeclaredAccessorInfo> info =
797 Handle<DeclaredAccessorInfo>::cast(
798 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
799 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
804 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
805 Handle<ExecutableAccessorInfo> info =
806 Handle<ExecutableAccessorInfo>::cast(
807 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
808 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
813 Handle<Script> Factory::NewScript(Handle<String> source) {
814 // Generate id for this script.
815 Heap* heap = isolate()->heap();
816 int id = heap->last_script_id()->value() + 1;
817 if (!Smi::IsValid(id) || id < 0) id = 1;
818 heap->set_last_script_id(Smi::FromInt(id));
820 // Create and initialize script object.
821 Handle<Foreign> wrapper = NewForeign(0, TENURED);
822 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
823 script->set_source(*source);
824 script->set_name(heap->undefined_value());
825 script->set_id(Smi::FromInt(id));
826 script->set_line_offset(Smi::FromInt(0));
827 script->set_column_offset(Smi::FromInt(0));
828 script->set_context_data(heap->undefined_value());
829 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
830 script->set_wrapper(*wrapper);
831 script->set_line_ends(heap->undefined_value());
832 script->set_eval_from_shared(heap->undefined_value());
833 script->set_eval_from_instructions_offset(Smi::FromInt(0));
834 script->set_flags(Smi::FromInt(0));
840 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
841 CALL_HEAP_FUNCTION(isolate(),
842 isolate()->heap()->AllocateForeign(addr, pretenure),
847 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
848 return NewForeign((Address) desc, TENURED);
852 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
856 isolate()->heap()->AllocateByteArray(length, pretenure),
861 Handle<ExternalArray> Factory::NewExternalArray(int length,
862 ExternalArrayType array_type,
863 void* external_pointer,
864 PretenureFlag pretenure) {
865 DCHECK(0 <= length && length <= Smi::kMaxValue);
868 isolate()->heap()->AllocateExternalArray(length,
876 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
878 ExternalArrayType array_type,
879 PretenureFlag pretenure) {
880 DCHECK(0 <= length && length <= Smi::kMaxValue);
883 isolate()->heap()->AllocateFixedTypedArray(length,
886 FixedTypedArrayBase);
890 Handle<Cell> Factory::NewCell(Handle<Object> value) {
891 AllowDeferredHandleDereference convert_to_cell;
894 isolate()->heap()->AllocateCell(*value),
899 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
902 isolate()->heap()->AllocatePropertyCell(),
907 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
908 AllowDeferredHandleDereference convert_to_cell;
909 Handle<PropertyCell> cell = NewPropertyCellWithHole();
910 PropertyCell::SetValueInferType(cell, value);
915 Handle<AllocationSite> Factory::NewAllocationSite() {
916 Handle<Map> map = allocation_site_map();
917 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
921 site->set_weak_next(isolate()->heap()->allocation_sites_list());
922 isolate()->heap()->set_allocation_sites_list(*site);
927 Handle<Map> Factory::NewMap(InstanceType type,
929 ElementsKind elements_kind) {
932 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
937 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
938 CALL_HEAP_FUNCTION(isolate(),
939 isolate()->heap()->CopyJSObject(*object, NULL),
944 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
945 Handle<JSObject> object,
946 Handle<AllocationSite> site) {
947 CALL_HEAP_FUNCTION(isolate(),
948 isolate()->heap()->CopyJSObject(
950 site.is_null() ? NULL : *site),
955 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
957 CALL_HEAP_FUNCTION(isolate(),
958 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
963 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
964 CALL_HEAP_FUNCTION(isolate(),
965 isolate()->heap()->CopyFixedArray(*array),
970 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
971 Handle<FixedArray> array) {
972 DCHECK(isolate()->heap()->InNewSpace(*array));
973 CALL_HEAP_FUNCTION(isolate(),
974 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
979 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
980 Handle<FixedDoubleArray> array) {
981 CALL_HEAP_FUNCTION(isolate(),
982 isolate()->heap()->CopyFixedDoubleArray(*array),
987 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
988 Handle<ConstantPoolArray> array) {
989 CALL_HEAP_FUNCTION(isolate(),
990 isolate()->heap()->CopyConstantPoolArray(*array),
995 Handle<Object> Factory::NewNumber(double value,
996 PretenureFlag pretenure) {
997 // We need to distinguish the minus zero value and this cannot be
998 // done after conversion to int. Doing this by comparing bit
999 // patterns is faster than using fpclassify() et al.
1000 if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1002 int int_value = FastD2I(value);
1003 if (value == int_value && Smi::IsValid(int_value)) {
1004 return handle(Smi::FromInt(int_value), isolate());
1007 // Materialize the value in the heap.
1008 return NewHeapNumber(value, IMMUTABLE, pretenure);
1012 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1013 PretenureFlag pretenure) {
1014 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1015 // Bypass NewNumber to avoid various redundant checks.
1016 return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1020 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1021 PretenureFlag pretenure) {
1022 int32_t int32v = static_cast<int32_t>(value);
1023 if (int32v >= 0 && Smi::IsValid(int32v)) {
1024 return handle(Smi::FromInt(int32v), isolate());
1026 return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1030 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1032 PretenureFlag pretenure) {
1035 isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1040 Handle<Object> Factory::NewTypeError(const char* message,
1041 Vector< Handle<Object> > args) {
1042 return NewError("MakeTypeError", message, args);
1046 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1047 return NewError("$TypeError", message);
1051 Handle<Object> Factory::NewRangeError(const char* message,
1052 Vector< Handle<Object> > args) {
1053 return NewError("MakeRangeError", message, args);
1057 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1058 return NewError("$RangeError", message);
1062 Handle<Object> Factory::NewSyntaxError(const char* message,
1063 Handle<JSArray> args) {
1064 return NewError("MakeSyntaxError", message, args);
1068 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1069 return NewError("$SyntaxError", message);
1073 Handle<Object> Factory::NewReferenceError(const char* message,
1074 Vector< Handle<Object> > args) {
1075 return NewError("MakeReferenceError", message, args);
1079 Handle<Object> Factory::NewReferenceError(const char* message,
1080 Handle<JSArray> args) {
1081 return NewError("MakeReferenceError", message, args);
1085 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1086 return NewError("$ReferenceError", message);
1090 Handle<Object> Factory::NewError(const char* maker,
1091 const char* message,
1092 Vector< Handle<Object> > args) {
1093 // Instantiate a closeable HandleScope for EscapeFrom.
1094 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1095 Handle<FixedArray> array = NewFixedArray(args.length());
1096 for (int i = 0; i < args.length(); i++) {
1097 array->set(i, *args[i]);
1099 Handle<JSArray> object = NewJSArrayWithElements(array);
1100 Handle<Object> result = NewError(maker, message, object);
1101 return result.EscapeFrom(&scope);
1105 Handle<Object> Factory::NewEvalError(const char* message,
1106 Vector< Handle<Object> > args) {
1107 return NewError("MakeEvalError", message, args);
1111 Handle<Object> Factory::NewError(const char* message,
1112 Vector< Handle<Object> > args) {
1113 return NewError("MakeError", message, args);
1117 Handle<String> Factory::EmergencyNewError(const char* message,
1118 Handle<JSArray> args) {
1119 const int kBufferSize = 1000;
1120 char buffer[kBufferSize];
1121 size_t space = kBufferSize;
1122 char* p = &buffer[0];
1124 Vector<char> v(buffer, kBufferSize);
1125 StrNCpy(v, message, space);
1126 space -= Min(space, strlen(message));
1127 p = &buffer[kBufferSize] - space;
1129 for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1134 Handle<String> arg_str = Handle<String>::cast(
1135 Object::GetElement(isolate(), args, i).ToHandleChecked());
1136 SmartArrayPointer<char> arg = arg_str->ToCString();
1137 Vector<char> v2(p, static_cast<int>(space));
1138 StrNCpy(v2, arg.get(), space);
1139 space -= Min(space, strlen(arg.get()));
1140 p = &buffer[kBufferSize] - space;
1147 buffer[kBufferSize - 1] = '\0';
1149 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1153 Handle<Object> Factory::NewError(const char* maker,
1154 const char* message,
1155 Handle<JSArray> args) {
1156 Handle<String> make_str = InternalizeUtf8String(maker);
1157 Handle<Object> fun_obj = Object::GetProperty(
1158 isolate()->js_builtins_object(), make_str).ToHandleChecked();
1159 // If the builtins haven't been properly configured yet this error
1160 // constructor may not have been defined. Bail out.
1161 if (!fun_obj->IsJSFunction()) {
1162 return EmergencyNewError(message, args);
1164 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1165 Handle<Object> message_obj = InternalizeUtf8String(message);
1166 Handle<Object> argv[] = { message_obj, args };
1168 // Invoke the JavaScript factory method. If an exception is thrown while
1169 // running the factory method, use the exception as the result.
1170 Handle<Object> result;
1171 Handle<Object> exception;
1172 if (!Execution::TryCall(fun,
1173 isolate()->js_builtins_object(),
1176 &exception).ToHandle(&result)) {
1183 Handle<Object> Factory::NewError(Handle<String> message) {
1184 return NewError("$Error", message);
1188 Handle<Object> Factory::NewError(const char* constructor,
1189 Handle<String> message) {
1190 Handle<String> constr = InternalizeUtf8String(constructor);
1191 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1192 isolate()->js_builtins_object(), constr).ToHandleChecked());
1193 Handle<Object> argv[] = { message };
1195 // Invoke the JavaScript factory method. If an exception is thrown while
1196 // running the factory method, use the exception as the result.
1197 Handle<Object> result;
1198 Handle<Object> exception;
1199 if (!Execution::TryCall(fun,
1200 isolate()->js_builtins_object(),
1203 &exception).ToHandle(&result)) {
1210 void Factory::InitializeFunction(Handle<JSFunction> function,
1211 Handle<SharedFunctionInfo> info,
1212 Handle<Context> context) {
1213 function->initialize_properties();
1214 function->initialize_elements();
1215 function->set_shared(*info);
1216 function->set_code(info->code());
1217 function->set_context(*context);
1218 function->set_prototype_or_initial_map(*the_hole_value());
1219 function->set_literals_or_bindings(*empty_fixed_array());
1220 function->set_next_function_link(*undefined_value());
1221 if (info->is_arrow()) function->RemovePrototype();
1225 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1226 Handle<SharedFunctionInfo> info,
1227 Handle<Context> context,
1228 PretenureFlag pretenure) {
1229 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1230 Handle<JSFunction> result = New<JSFunction>(map, space);
1231 InitializeFunction(result, info, context);
1236 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1237 Handle<String> name,
1238 MaybeHandle<Code> code) {
1239 Handle<Context> context(isolate()->native_context());
1240 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1241 DCHECK((info->strict_mode() == SLOPPY) &&
1242 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1243 map.is_identical_to(
1244 isolate()->sloppy_function_without_prototype_map()) ||
1245 map.is_identical_to(
1246 isolate()->sloppy_function_with_readonly_prototype_map())));
1247 return NewFunction(map, info, context);
1251 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1253 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1257 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1258 Handle<Code> code) {
1260 isolate()->sloppy_function_without_prototype_map(), name, code);
1264 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1266 Handle<Object> prototype,
1267 bool read_only_prototype) {
1268 Handle<Map> map = read_only_prototype
1269 ? isolate()->sloppy_function_with_readonly_prototype_map()
1270 : isolate()->sloppy_function_map();
1271 Handle<JSFunction> result = NewFunction(map, name, code);
1272 result->set_prototype_or_initial_map(*prototype);
1277 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1279 Handle<Object> prototype,
1282 bool read_only_prototype) {
1283 // Allocate the function
1284 Handle<JSFunction> function = NewFunction(
1285 name, code, prototype, read_only_prototype);
1287 Handle<Map> initial_map = NewMap(
1288 type, instance_size, GetInitialFastElementsKind());
1289 if (prototype->IsTheHole() && !function->shared()->is_generator()) {
1290 prototype = NewFunctionPrototype(function);
1293 JSFunction::SetInitialMap(function, initial_map,
1294 Handle<JSReceiver>::cast(prototype));
1300 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1303 int instance_size) {
1304 return NewFunction(name, code, the_hole_value(), type, instance_size);
1308 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1309 // Make sure to use globals from the function's context, since the function
1310 // can be from a different context.
1311 Handle<Context> native_context(function->context()->native_context());
1312 Handle<Map> new_map;
1313 if (function->shared()->is_generator()) {
1314 // Generator prototypes can share maps since they don't have "constructor"
1316 new_map = handle(native_context->generator_object_prototype_map());
1318 // Each function prototype gets a fresh map to avoid unwanted sharing of
1319 // maps between prototypes of different constructors.
1320 Handle<JSFunction> object_function(native_context->object_function());
1321 DCHECK(object_function->has_initial_map());
1322 new_map = handle(object_function->initial_map());
1325 DCHECK(!new_map->is_prototype_map());
1326 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1328 if (!function->shared()->is_generator()) {
1329 JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1336 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1337 Handle<SharedFunctionInfo> info,
1338 Handle<Context> context,
1339 PretenureFlag pretenure) {
1340 int map_index = Context::FunctionMapIndex(info->strict_mode(),
1341 info->is_generator());
1342 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1343 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1345 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1346 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1349 int index = info->SearchOptimizedCodeMap(context->native_context(),
1351 if (!info->bound() && index < 0) {
1352 int number_of_literals = info->num_literals();
1353 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1354 if (number_of_literals > 0) {
1355 // Store the native context in the literals array prefix. This
1356 // context will be used when creating object, regexp and array
1357 // literals in this function.
1358 literals->set(JSFunction::kLiteralNativeContextIndex,
1359 context->native_context());
1361 result->set_literals(*literals);
1365 // Caching of optimized code enabled and optimized code found.
1366 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1367 if (literals != NULL) result->set_literals(literals);
1368 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1369 DCHECK(!code->marked_for_deoptimization());
1370 result->ReplaceCode(code);
1374 if (isolate()->use_crankshaft() &&
1376 result->is_compiled() &&
1377 !info->is_toplevel() &&
1378 info->allows_lazy_compilation() &&
1379 !info->optimization_disabled() &&
1380 !isolate()->DebuggerHasBreakPoints()) {
1381 result->MarkForOptimization();
1387 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1388 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1389 array->set_map_no_write_barrier(*scope_info_map());
1390 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1395 Handle<JSObject> Factory::NewExternal(void* value) {
1396 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1397 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1398 external->SetInternalField(0, *foreign);
1403 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1404 CALL_HEAP_FUNCTION(isolate(),
1405 isolate()->heap()->AllocateCode(object_size, immovable),
1410 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1412 Handle<Object> self_ref,
1415 int prologue_offset,
1417 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1418 Handle<ConstantPoolArray> constant_pool =
1419 desc.origin->NewConstantPool(isolate());
1422 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1423 int obj_size = Code::SizeFor(body_size);
1425 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1426 DCHECK(isolate()->code_range() == NULL ||
1427 !isolate()->code_range()->valid() ||
1428 isolate()->code_range()->contains(code->address()));
1430 // The code object has not been fully initialized yet. We rely on the
1431 // fact that no allocation will happen from this point on.
1432 DisallowHeapAllocation no_gc;
1433 code->set_gc_metadata(Smi::FromInt(0));
1434 code->set_ic_age(isolate()->heap()->global_ic_age());
1435 code->set_instruction_size(desc.instr_size);
1436 code->set_relocation_info(*reloc_info);
1437 code->set_flags(flags);
1438 code->set_raw_kind_specific_flags1(0);
1439 code->set_raw_kind_specific_flags2(0);
1440 code->set_is_crankshafted(crankshafted);
1441 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1442 code->set_raw_type_feedback_info(Smi::FromInt(0));
1443 code->set_next_code_link(*undefined_value());
1444 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1445 code->set_prologue_offset(prologue_offset);
1446 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1447 code->set_marked_for_deoptimization(false);
1451 DCHECK(code->kind() == Code::FUNCTION);
1452 code->set_has_debug_break_slots(true);
1455 desc.origin->PopulateConstantPool(*constant_pool);
1456 code->set_constant_pool(*constant_pool);
1458 // Allow self references to created code object by patching the handle to
1459 // point to the newly allocated Code object.
1460 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1462 // Migrate generated code.
1463 // The generated code can contain Object** values (typically from handles)
1464 // that are dereferenced during the copy to point directly to the actual heap
1465 // objects. These pointers can include references to the code object itself,
1466 // through the self_reference parameter.
1467 code->CopyFrom(desc);
1470 if (FLAG_verify_heap) code->ObjectVerify();
1476 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1477 CALL_HEAP_FUNCTION(isolate(),
1478 isolate()->heap()->CopyCode(*code),
1483 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1484 CALL_HEAP_FUNCTION(isolate(),
1485 isolate()->heap()->CopyCode(*code, reloc_info),
1490 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1491 PretenureFlag pretenure) {
1492 JSFunction::EnsureHasInitialMap(constructor);
1495 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1499 Handle<JSObject> Factory::NewJSObjectWithMemento(
1500 Handle<JSFunction> constructor,
1501 Handle<AllocationSite> site) {
1502 JSFunction::EnsureHasInitialMap(constructor);
1505 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1510 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1511 Handle<ScopeInfo> scope_info) {
1512 // Allocate a fresh map. Modules do not have a prototype.
1513 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1514 // Allocate the object based on the map.
1515 Handle<JSModule> module =
1516 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1517 module->set_context(*context);
1518 module->set_scope_info(*scope_info);
1523 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1524 DCHECK(constructor->has_initial_map());
1525 Handle<Map> map(constructor->initial_map());
1526 DCHECK(map->is_dictionary_map());
1528 // Make sure no field properties are described in the initial map.
1529 // This guarantees us that normalizing the properties does not
1530 // require us to change property values to PropertyCells.
1531 DCHECK(map->NextFreePropertyIndex() == 0);
1533 // Make sure we don't have a ton of pre-allocated slots in the
1534 // global objects. They will be unused once we normalize the object.
1535 DCHECK(map->unused_property_fields() == 0);
1536 DCHECK(map->inobject_properties() == 0);
1538 // Initial size of the backing store to avoid resize of the storage during
1539 // bootstrapping. The size differs between the JS global object ad the
1541 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1543 // Allocate a dictionary object for backing storage.
1544 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1545 Handle<NameDictionary> dictionary =
1546 NameDictionary::New(isolate(), at_least_space_for);
1548 // The global object might be created from an object template with accessors.
1549 // Fill these accessors into the dictionary.
1550 Handle<DescriptorArray> descs(map->instance_descriptors());
1551 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1552 PropertyDetails details = descs->GetDetails(i);
1553 DCHECK(details.type() == CALLBACKS); // Only accessors are expected.
1554 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1555 Handle<Name> name(descs->GetKey(i));
1556 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1557 Handle<PropertyCell> cell = NewPropertyCell(value);
1558 // |dictionary| already contains enough space for all properties.
1559 USE(NameDictionary::Add(dictionary, name, cell, d));
1562 // Allocate the global object and initialize it with the backing store.
1563 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1564 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1566 // Create a new map for the global object.
1567 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1568 new_map->set_dictionary_map(true);
1570 // Set up the global object as a normalized object.
1571 global->set_map(*new_map);
1572 global->set_properties(*dictionary);
1574 // Make sure result is a global object with properties in dictionary.
1575 DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1580 Handle<JSObject> Factory::NewJSObjectFromMap(
1582 PretenureFlag pretenure,
1584 Handle<AllocationSite> allocation_site) {
1587 isolate()->heap()->AllocateJSObjectFromMap(
1591 allocation_site.is_null() ? NULL : *allocation_site),
1596 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1597 PretenureFlag pretenure) {
1598 Context* native_context = isolate()->context()->native_context();
1599 JSFunction* array_function = native_context->array_function();
1600 Map* map = array_function->initial_map();
1601 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1602 if (transition_map != NULL) map = transition_map;
1603 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1607 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1610 ArrayStorageAllocationMode mode,
1611 PretenureFlag pretenure) {
1612 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1613 NewJSArrayStorage(array, length, capacity, mode);
1618 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1619 ElementsKind elements_kind,
1621 PretenureFlag pretenure) {
1622 DCHECK(length <= elements->length());
1623 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1625 array->set_elements(*elements);
1626 array->set_length(Smi::FromInt(length));
1627 JSObject::ValidateElements(array);
1632 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1635 ArrayStorageAllocationMode mode) {
1636 DCHECK(capacity >= length);
1638 if (capacity == 0) {
1639 array->set_length(Smi::FromInt(0));
1640 array->set_elements(*empty_fixed_array());
1644 Handle<FixedArrayBase> elms;
1645 ElementsKind elements_kind = array->GetElementsKind();
1646 if (IsFastDoubleElementsKind(elements_kind)) {
1647 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1648 elms = NewFixedDoubleArray(capacity);
1650 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1651 elms = NewFixedDoubleArrayWithHoles(capacity);
1654 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1655 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1656 elms = NewUninitializedFixedArray(capacity);
1658 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1659 elms = NewFixedArrayWithHoles(capacity);
1663 array->set_elements(*elms);
1664 array->set_length(Smi::FromInt(length));
1668 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1669 Handle<JSFunction> function) {
1670 DCHECK(function->shared()->is_generator());
1671 JSFunction::EnsureHasInitialMap(function);
1672 Handle<Map> map(function->initial_map());
1673 DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1676 isolate()->heap()->AllocateJSObjectFromMap(*map),
1681 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1682 Handle<JSFunction> array_buffer_fun(
1683 isolate()->native_context()->array_buffer_fun());
1686 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1691 Handle<JSDataView> Factory::NewJSDataView() {
1692 Handle<JSFunction> data_view_fun(
1693 isolate()->native_context()->data_view_fun());
1696 isolate()->heap()->AllocateJSObject(*data_view_fun),
1701 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1703 Context* native_context = isolate->context()->native_context();
1705 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1706 case kExternal##Type##Array: \
1707 return native_context->type##_array_fun();
1709 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1710 #undef TYPED_ARRAY_FUN
1719 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1720 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1724 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1729 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1730 Handle<Object> prototype) {
1732 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1733 // maps. Will probably depend on the identity of the handler object, too.
1734 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1735 map->set_prototype(*prototype);
1737 // Allocate the proxy object.
1738 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1739 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1740 result->set_handler(*handler);
1741 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1746 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1747 Handle<Object> call_trap,
1748 Handle<Object> construct_trap,
1749 Handle<Object> prototype) {
1751 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1752 // maps. Will probably depend on the identity of the handler object, too.
1753 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1754 map->set_prototype(*prototype);
1756 // Allocate the proxy object.
1757 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1758 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1759 result->set_handler(*handler);
1760 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1761 result->set_call_trap(*call_trap);
1762 result->set_construct_trap(*construct_trap);
1767 void Factory::ReinitializeJSReceiver(Handle<JSReceiver> object,
1770 DCHECK(type >= FIRST_JS_OBJECT_TYPE);
1772 // Allocate fresh map.
1773 // TODO(rossberg): Once we optimize proxies, cache these maps.
1774 Handle<Map> map = NewMap(type, size);
1776 // Check that the receiver has at least the size of the fresh object.
1777 int size_difference = object->map()->instance_size() - map->instance_size();
1778 DCHECK(size_difference >= 0);
1780 map->set_prototype(object->map()->prototype());
1782 // Allocate the backing storage for the properties.
1783 int prop_size = map->InitialPropertiesLength();
1784 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1786 Heap* heap = isolate()->heap();
1787 MaybeHandle<SharedFunctionInfo> shared;
1788 if (type == JS_FUNCTION_TYPE) {
1789 OneByteStringKey key(STATIC_ASCII_VECTOR("<freezing call trap>"),
1791 Handle<String> name = InternalizeStringWithKey(&key);
1792 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1795 // In order to keep heap in consistent state there must be no allocations
1796 // before object re-initialization is finished and filler object is installed.
1797 DisallowHeapAllocation no_allocation;
1799 // Put in filler if the new object is smaller than the old.
1800 if (size_difference > 0) {
1801 Address address = object->address();
1802 heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1803 heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1806 // Reset the map for the object.
1807 object->synchronized_set_map(*map);
1808 Handle<JSObject> jsobj = Handle<JSObject>::cast(object);
1810 // Reinitialize the object from the constructor map.
1811 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1813 // Functions require some minimal initialization.
1814 if (type == JS_FUNCTION_TYPE) {
1815 map->set_function_with_prototype(true);
1816 Handle<JSFunction> js_function = Handle<JSFunction>::cast(object);
1817 Handle<Context> context(isolate()->native_context());
1818 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1823 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1824 Handle<JSFunction> constructor) {
1825 DCHECK(constructor->has_initial_map());
1826 Handle<Map> map(constructor->initial_map(), isolate());
1828 // The proxy's hash should be retained across reinitialization.
1829 Handle<Object> hash(object->hash(), isolate());
1831 // Check that the already allocated object has the same size and type as
1832 // objects allocated using the constructor.
1833 DCHECK(map->instance_size() == object->map()->instance_size());
1834 DCHECK(map->instance_type() == object->map()->instance_type());
1836 // Allocate the backing storage for the properties.
1837 int prop_size = map->InitialPropertiesLength();
1838 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1840 // In order to keep heap in consistent state there must be no allocations
1841 // before object re-initialization is finished.
1842 DisallowHeapAllocation no_allocation;
1844 // Reset the map for the object.
1845 object->synchronized_set_map(*map);
1847 Heap* heap = isolate()->heap();
1848 // Reinitialize the object from the constructor map.
1849 heap->InitializeJSObjectFromMap(*object, *properties, *map);
1851 // Restore the saved hash.
1852 object->set_hash(*hash);
1856 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1857 ReinitializeJSReceiver(object, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1861 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1862 ReinitializeJSReceiver(object, JS_FUNCTION_TYPE, JSFunction::kSize);
1866 Handle<FixedArray> Factory::NewTypeFeedbackVector(int slot_count) {
1867 // Ensure we can skip the write barrier
1868 DCHECK_EQ(isolate()->heap()->uninitialized_symbol(),
1869 *TypeFeedbackInfo::UninitializedSentinel(isolate()));
1873 isolate()->heap()->AllocateFixedArrayWithFiller(
1876 *TypeFeedbackInfo::UninitializedSentinel(isolate())),
1881 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1882 Handle<String> name, int number_of_literals, bool is_generator,
1883 bool is_arrow, Handle<Code> code, Handle<ScopeInfo> scope_info,
1884 Handle<FixedArray> feedback_vector) {
1885 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
1886 shared->set_scope_info(*scope_info);
1887 shared->set_feedback_vector(*feedback_vector);
1888 shared->set_is_arrow(is_arrow);
1889 int literals_array_size = number_of_literals;
1890 // If the function contains object, regexp or array literals,
1891 // allocate extra space for a literals array prefix containing the
1893 if (number_of_literals > 0) {
1894 literals_array_size += JSFunction::kLiteralsPrefixSize;
1896 shared->set_num_literals(literals_array_size);
1898 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1899 shared->DisableOptimization(kGenerator);
1905 Handle<JSMessageObject> Factory::NewJSMessageObject(
1906 Handle<String> type,
1907 Handle<JSArray> arguments,
1910 Handle<Object> script,
1911 Handle<Object> stack_frames) {
1912 Handle<Map> map = message_object_map();
1913 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
1914 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1915 message->initialize_elements();
1916 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1917 message->set_type(*type);
1918 message->set_arguments(*arguments);
1919 message->set_start_position(start_position);
1920 message->set_end_position(end_position);
1921 message->set_script(*script);
1922 message->set_stack_frames(*stack_frames);
1927 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1928 Handle<String> name,
1929 MaybeHandle<Code> maybe_code) {
1930 Handle<Map> map = shared_function_info_map();
1931 Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
1934 // Set pointer fields.
1935 share->set_name(*name);
1937 if (!maybe_code.ToHandle(&code)) {
1938 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
1940 share->set_code(*code);
1941 share->set_optimized_code_map(Smi::FromInt(0));
1942 share->set_scope_info(ScopeInfo::Empty(isolate()));
1943 Code* construct_stub =
1944 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
1945 share->set_construct_stub(construct_stub);
1946 share->set_instance_class_name(*Object_string());
1947 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
1948 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
1949 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
1950 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
1951 share->set_feedback_vector(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1952 share->set_profiler_ticks(0);
1953 share->set_ast_node_count(0);
1954 share->set_counters(0);
1956 // Set integer fields (smi or int, depending on the architecture).
1957 share->set_length(0);
1958 share->set_formal_parameter_count(0);
1959 share->set_expected_nof_properties(0);
1960 share->set_num_literals(0);
1961 share->set_start_position_and_type(0);
1962 share->set_end_position(0);
1963 share->set_function_token_position(0);
1964 // All compiler hints default to false or 0.
1965 share->set_compiler_hints(0);
1966 share->set_opt_count_and_bailout_reason(0);
1972 static inline int NumberCacheHash(Handle<FixedArray> cache,
1973 Handle<Object> number) {
1974 int mask = (cache->length() >> 1) - 1;
1975 if (number->IsSmi()) {
1976 return Handle<Smi>::cast(number)->value() & mask;
1978 DoubleRepresentation rep(number->Number());
1980 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
1985 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
1986 DisallowHeapAllocation no_gc;
1987 int hash = NumberCacheHash(number_string_cache(), number);
1988 Object* key = number_string_cache()->get(hash * 2);
1989 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
1990 key->Number() == number->Number())) {
1991 return Handle<String>(
1992 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
1994 return undefined_value();
1998 void Factory::SetNumberStringCache(Handle<Object> number,
1999 Handle<String> string) {
2000 int hash = NumberCacheHash(number_string_cache(), number);
2001 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2002 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2003 if (number_string_cache()->length() != full_size) {
2004 // The first time we have a hash collision, we move to the full sized
2005 // number string cache. The idea is to have a small number string
2006 // cache in the snapshot to keep boot-time memory usage down.
2007 // If we expand the number string cache already while creating
2008 // the snapshot then that didn't work out.
2009 DCHECK(!isolate()->serializer_enabled() || FLAG_extra_code != NULL);
2010 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2011 isolate()->heap()->set_number_string_cache(*new_cache);
2015 number_string_cache()->set(hash * 2, *number);
2016 number_string_cache()->set(hash * 2 + 1, *string);
2020 Handle<String> Factory::NumberToString(Handle<Object> number,
2021 bool check_number_string_cache) {
2022 isolate()->counters()->number_to_string_runtime()->Increment();
2023 if (check_number_string_cache) {
2024 Handle<Object> cached = GetNumberStringCache(number);
2025 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2029 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2031 if (number->IsSmi()) {
2032 int num = Handle<Smi>::cast(number)->value();
2033 str = IntToCString(num, buffer);
2035 double num = Handle<HeapNumber>::cast(number)->value();
2036 str = DoubleToCString(num, buffer);
2039 // We tenure the allocated string since it is referenced from the
2040 // number-string cache which lives in the old space.
2041 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2042 SetNumberStringCache(number, js_string);
2047 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2048 // Get the original code of the function.
2049 Handle<Code> code(shared->code());
2051 // Create a copy of the code before allocating the debug info object to avoid
2052 // allocation while setting up the debug info object.
2053 Handle<Code> original_code(*Factory::CopyCode(code));
2055 // Allocate initial fixed array for active break points before allocating the
2056 // debug info object to avoid allocation while setting up the debug info
2058 Handle<FixedArray> break_points(
2059 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2061 // Create and set up the debug info object. Debug info contains function, a
2062 // copy of the original code, the executing code and initial fixed array for
2063 // active break points.
2064 Handle<DebugInfo> debug_info =
2065 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2066 debug_info->set_shared(*shared);
2067 debug_info->set_original_code(*original_code);
2068 debug_info->set_code(*code);
2069 debug_info->set_break_points(*break_points);
2071 // Link debug info to function.
2072 shared->set_debug_info(*debug_info);
2078 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2080 bool strict_mode_callee = callee->shared()->strict_mode() == STRICT;
2081 Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2082 : isolate()->sloppy_arguments_map();
2084 AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2086 DCHECK(!isolate()->has_pending_exception());
2087 Handle<JSObject> result = NewJSObjectFromMap(map);
2088 Handle<Smi> value(Smi::FromInt(length), isolate());
2089 Object::SetProperty(result, length_string(), value, STRICT).Assert();
2090 if (!strict_mode_callee) {
2091 Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2097 Handle<JSFunction> Factory::CreateApiFunction(
2098 Handle<FunctionTemplateInfo> obj,
2099 Handle<Object> prototype,
2100 ApiInstanceType instance_type) {
2101 Handle<Code> code = isolate()->builtins()->HandleApiCall();
2102 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
2104 Handle<JSFunction> result;
2105 if (obj->remove_prototype()) {
2106 result = NewFunctionWithoutPrototype(empty_string(), code);
2108 int internal_field_count = 0;
2109 if (!obj->instance_template()->IsUndefined()) {
2110 Handle<ObjectTemplateInfo> instance_template =
2111 Handle<ObjectTemplateInfo>(
2112 ObjectTemplateInfo::cast(obj->instance_template()));
2113 internal_field_count =
2114 Smi::cast(instance_template->internal_field_count())->value();
2117 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
2118 // JSObject::GetHeaderSize.
2119 int instance_size = kPointerSize * internal_field_count;
2121 switch (instance_type) {
2122 case JavaScriptObjectType:
2123 type = JS_OBJECT_TYPE;
2124 instance_size += JSObject::kHeaderSize;
2126 case GlobalObjectType:
2127 type = JS_GLOBAL_OBJECT_TYPE;
2128 instance_size += JSGlobalObject::kSize;
2130 case GlobalProxyType:
2131 type = JS_GLOBAL_PROXY_TYPE;
2132 instance_size += JSGlobalProxy::kSize;
2136 type = JS_OBJECT_TYPE; // Keep the compiler happy.
2140 result = NewFunction(empty_string(), code, prototype, type,
2141 instance_size, obj->read_only_prototype());
2144 result->shared()->set_length(obj->length());
2145 Handle<Object> class_name(obj->class_name(), isolate());
2146 if (class_name->IsString()) {
2147 result->shared()->set_instance_class_name(*class_name);
2148 result->shared()->set_name(*class_name);
2150 result->shared()->set_function_data(*obj);
2151 result->shared()->set_construct_stub(*construct_stub);
2152 result->shared()->DontAdaptArguments();
2154 if (obj->remove_prototype()) {
2155 DCHECK(result->shared()->IsApiFunction());
2156 DCHECK(!result->has_initial_map());
2157 DCHECK(!result->has_prototype());
2161 if (prototype->IsTheHole()) {
2163 LookupIterator it(handle(JSObject::cast(result->prototype())),
2164 constructor_string(),
2165 LookupIterator::CHECK_OWN_REAL);
2166 MaybeHandle<Object> maybe_prop = Object::GetProperty(&it);
2167 DCHECK(it.IsFound());
2168 DCHECK(maybe_prop.ToHandleChecked().is_identical_to(result));
2171 JSObject::AddProperty(handle(JSObject::cast(result->prototype())),
2172 constructor_string(), result, DONT_ENUM);
2175 // Down from here is only valid for API functions that can be used as a
2176 // constructor (don't set the "remove prototype" flag).
2178 Handle<Map> map(result->initial_map());
2180 // Mark as undetectable if needed.
2181 if (obj->undetectable()) {
2182 map->set_is_undetectable();
2185 // Mark as hidden for the __proto__ accessor if needed.
2186 if (obj->hidden_prototype()) {
2187 map->set_is_hidden_prototype();
2190 // Mark as needs_access_check if needed.
2191 if (obj->needs_access_check()) {
2192 map->set_is_access_check_needed(true);
2195 // Set interceptor information in the map.
2196 if (!obj->named_property_handler()->IsUndefined()) {
2197 map->set_has_named_interceptor();
2199 if (!obj->indexed_property_handler()->IsUndefined()) {
2200 map->set_has_indexed_interceptor();
2203 // Set instance call-as-function information in the map.
2204 if (!obj->instance_call_handler()->IsUndefined()) {
2205 map->set_has_instance_call_handler();
2208 // Recursively copy parent instance templates' accessors,
2209 // 'data' may be modified.
2210 int max_number_of_additional_properties = 0;
2211 int max_number_of_static_properties = 0;
2212 FunctionTemplateInfo* info = *obj;
2214 if (!info->instance_template()->IsUndefined()) {
2216 ObjectTemplateInfo::cast(
2217 info->instance_template())->property_accessors();
2218 if (!props->IsUndefined()) {
2219 Handle<Object> props_handle(props, isolate());
2220 NeanderArray props_array(props_handle);
2221 max_number_of_additional_properties += props_array.length();
2224 if (!info->property_accessors()->IsUndefined()) {
2225 Object* props = info->property_accessors();
2226 if (!props->IsUndefined()) {
2227 Handle<Object> props_handle(props, isolate());
2228 NeanderArray props_array(props_handle);
2229 max_number_of_static_properties += props_array.length();
2232 Object* parent = info->parent_template();
2233 if (parent->IsUndefined()) break;
2234 info = FunctionTemplateInfo::cast(parent);
2237 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
2239 // Use a temporary FixedArray to acculumate static accessors
2240 int valid_descriptors = 0;
2241 Handle<FixedArray> array;
2242 if (max_number_of_static_properties > 0) {
2243 array = NewFixedArray(max_number_of_static_properties);
2247 // Install instance descriptors
2248 if (!obj->instance_template()->IsUndefined()) {
2249 Handle<ObjectTemplateInfo> instance =
2250 Handle<ObjectTemplateInfo>(
2251 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
2252 Handle<Object> props = Handle<Object>(instance->property_accessors(),
2254 if (!props->IsUndefined()) {
2255 Map::AppendCallbackDescriptors(map, props);
2258 // Accumulate static accessors
2259 if (!obj->property_accessors()->IsUndefined()) {
2260 Handle<Object> props = Handle<Object>(obj->property_accessors(),
2263 AccessorInfo::AppendUnique(props, array, valid_descriptors);
2265 // Climb parent chain
2266 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
2267 if (parent->IsUndefined()) break;
2268 obj = Handle<FunctionTemplateInfo>::cast(parent);
2271 // Install accumulated static accessors
2272 for (int i = 0; i < valid_descriptors; i++) {
2273 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
2274 JSObject::SetAccessor(result, accessor).Assert();
2277 DCHECK(result->shared()->IsApiFunction());
2282 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
2283 Handle<FixedArray> keys,
2285 Handle<MapCache> map_cache = handle(MapCache::cast(context->map_cache()));
2286 Handle<MapCache> result = MapCache::Put(map_cache, keys, map);
2287 context->set_map_cache(*result);
2292 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2293 Handle<FixedArray> keys) {
2294 if (context->map_cache()->IsUndefined()) {
2295 // Allocate the new map cache for the native context.
2296 Handle<MapCache> new_cache = MapCache::New(isolate(), 24);
2297 context->set_map_cache(*new_cache);
2299 // Check to see whether there is a matching element in the cache.
2300 Handle<MapCache> cache =
2301 Handle<MapCache>(MapCache::cast(context->map_cache()));
2302 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
2303 if (result->IsMap()) return Handle<Map>::cast(result);
2304 // Create a new map and add it to the cache.
2305 Handle<Map> map = Map::Create(
2306 handle(context->object_function()), keys->length());
2307 AddToMapCache(context, keys, map);
2312 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2313 JSRegExp::Type type,
2314 Handle<String> source,
2315 JSRegExp::Flags flags,
2316 Handle<Object> data) {
2317 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2319 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2320 store->set(JSRegExp::kSourceIndex, *source);
2321 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2322 store->set(JSRegExp::kAtomPatternIndex, *data);
2323 regexp->set_data(*store);
2326 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2327 JSRegExp::Type type,
2328 Handle<String> source,
2329 JSRegExp::Flags flags,
2330 int capture_count) {
2331 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2332 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2333 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2334 store->set(JSRegExp::kSourceIndex, *source);
2335 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2336 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
2337 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2338 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
2339 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2340 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2341 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2342 Smi::FromInt(capture_count));
2343 regexp->set_data(*store);
2348 MaybeHandle<FunctionTemplateInfo> Factory::ConfigureInstance(
2349 Handle<FunctionTemplateInfo> desc, Handle<JSObject> instance) {
2350 // Configure the instance by adding the properties specified by the
2351 // instance template.
2352 Handle<Object> instance_template(desc->instance_template(), isolate());
2353 if (!instance_template->IsUndefined()) {
2354 RETURN_ON_EXCEPTION(
2356 Execution::ConfigureInstance(isolate(), instance, instance_template),
2357 FunctionTemplateInfo);
2363 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2364 if (String::Equals(name, undefined_string())) return undefined_value();
2365 if (String::Equals(name, nan_string())) return nan_value();
2366 if (String::Equals(name, infinity_string())) return infinity_value();
2367 return Handle<Object>::null();
2371 Handle<Object> Factory::ToBoolean(bool value) {
2372 return value ? true_value() : false_value();
2376 } } // namespace v8::internal