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/conversions.h"
8 #include "src/isolate-inl.h"
9 #include "src/macro-assembler.h"
16 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
19 isolate()->heap()->Allocate(*map, space),
25 Handle<T> Factory::New(Handle<Map> map,
26 AllocationSpace space,
27 Handle<AllocationSite> allocation_site) {
30 isolate()->heap()->Allocate(*map, space, *allocation_site),
35 Handle<HeapObject> Factory::NewFillerObject(int size,
37 AllocationSpace space) {
40 isolate()->heap()->AllocateFillerObject(size, double_align, space),
45 Handle<Box> Factory::NewBox(Handle<Object> value) {
46 Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
47 result->set_value(*value);
52 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
53 const char* to_string,
54 Handle<Object> to_number,
56 Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
57 Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
62 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
66 isolate()->heap()->AllocateFixedArray(size, pretenure),
71 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
72 PretenureFlag pretenure) {
76 isolate()->heap()->AllocateFixedArrayWithFiller(size,
83 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
86 isolate()->heap()->AllocateUninitializedFixedArray(size),
91 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
92 PretenureFlag pretenure) {
96 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
101 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
103 PretenureFlag pretenure) {
105 Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
107 Handle<FixedDoubleArray> double_array =
108 Handle<FixedDoubleArray>::cast(array);
109 for (int i = 0; i < size; ++i) {
110 double_array->set_the_hole(i);
117 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
118 const ConstantPoolArray::NumberOfEntries& small) {
119 ASSERT(small.total_count() > 0);
122 isolate()->heap()->AllocateConstantPoolArray(small),
127 Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
128 const ConstantPoolArray::NumberOfEntries& small,
129 const ConstantPoolArray::NumberOfEntries& extended) {
130 ASSERT(small.total_count() > 0);
131 ASSERT(extended.total_count() > 0);
134 isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
139 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
140 return OrderedHashSet::Allocate(isolate(), 4);
144 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
145 return OrderedHashMap::Allocate(isolate(), 4);
149 Handle<AccessorPair> Factory::NewAccessorPair() {
150 Handle<AccessorPair> accessors =
151 Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
152 accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
153 accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
154 accessors->set_access_flags(Smi::FromInt(0), 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 ASSERT(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 Handle<SeqOneByteString> result;
274 ASSIGN_RETURN_ON_EXCEPTION(
277 NewRawOneByteString(length, pretenure),
279 CopyChars(result->GetChars(), start, length);
282 Handle<SeqTwoByteString> result;
283 ASSIGN_RETURN_ON_EXCEPTION(
286 NewRawTwoByteString(length, pretenure),
288 CopyChars(result->GetChars(), start, length);
294 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
296 uint32_t hash_field) {
299 isolate()->heap()->AllocateInternalizedStringFromUtf8(
300 str, chars, hash_field),
305 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
306 Vector<const uint8_t> str,
307 uint32_t hash_field) {
310 isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
315 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
316 Vector<const uc16> str,
317 uint32_t hash_field) {
320 isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
325 Handle<String> Factory::NewInternalizedStringImpl(
326 Handle<String> string, int chars, uint32_t hash_field) {
329 isolate()->heap()->AllocateInternalizedStringImpl(
330 *string, chars, hash_field),
335 MaybeHandle<Map> Factory::InternalizedStringMapForString(
336 Handle<String> string) {
337 // If the string is in new space it cannot be used as internalized.
338 if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
340 // Find the corresponding internalized string map for strings.
341 switch (string->map()->instance_type()) {
342 case STRING_TYPE: return internalized_string_map();
343 case ASCII_STRING_TYPE: return ascii_internalized_string_map();
344 case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
345 case EXTERNAL_ASCII_STRING_TYPE:
346 return external_ascii_internalized_string_map();
347 case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
348 return external_internalized_string_with_one_byte_data_map();
349 case SHORT_EXTERNAL_STRING_TYPE:
350 return short_external_internalized_string_map();
351 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
352 return short_external_ascii_internalized_string_map();
353 case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
354 return short_external_internalized_string_with_one_byte_data_map();
355 default: return MaybeHandle<Map>(); // No match found.
360 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
361 int length, PretenureFlag pretenure) {
362 if (length > String::kMaxLength || length < 0) {
363 return isolate()->Throw<SeqOneByteString>(NewInvalidStringLengthError());
367 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
372 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
373 int length, PretenureFlag pretenure) {
374 if (length > String::kMaxLength || length < 0) {
375 return isolate()->Throw<SeqTwoByteString>(NewInvalidStringLengthError());
379 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
384 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
385 if (code <= String::kMaxOneByteCharCodeU) {
387 DisallowHeapAllocation no_allocation;
388 Object* value = single_character_string_cache()->get(code);
389 if (value != *undefined_value()) {
390 return handle(String::cast(value), isolate());
394 buffer[0] = static_cast<uint8_t>(code);
395 Handle<String> result =
396 InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
397 single_character_string_cache()->set(code, *result);
400 ASSERT(code <= String::kMaxUtf16CodeUnitU);
402 Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
403 result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
408 // Returns true for a character in a range. Both limits are inclusive.
409 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
410 // This makes uses of the the unsigned wraparound.
411 return character - from <= to - from;
415 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
418 // Numeric strings have a different hash algorithm not known by
419 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
420 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
421 Handle<String> result;
422 if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
428 // Now we know the length is 2, we might as well make use of that fact
429 // when building the new string.
430 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
432 ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
433 Handle<SeqOneByteString> str =
434 isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
435 uint8_t* dest = str->GetChars();
436 dest[0] = static_cast<uint8_t>(c1);
437 dest[1] = static_cast<uint8_t>(c2);
440 Handle<SeqTwoByteString> str =
441 isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
442 uc16* dest = str->GetChars();
450 template<typename SinkChar, typename StringType>
451 Handle<String> ConcatStringContent(Handle<StringType> result,
452 Handle<String> first,
453 Handle<String> second) {
454 DisallowHeapAllocation pointer_stays_valid;
455 SinkChar* sink = result->GetChars();
456 String::WriteToFlat(*first, sink, 0, first->length());
457 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
462 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
463 Handle<String> right) {
464 int left_length = left->length();
465 if (left_length == 0) return right;
466 int right_length = right->length();
467 if (right_length == 0) return left;
469 int length = left_length + right_length;
472 uint16_t c1 = left->Get(0);
473 uint16_t c2 = right->Get(0);
474 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
477 // Make sure that an out of memory exception is thrown if the length
478 // of the new cons string is too large.
479 if (length > String::kMaxLength || length < 0) {
480 return isolate()->Throw<String>(NewInvalidStringLengthError());
483 bool left_is_one_byte = left->IsOneByteRepresentation();
484 bool right_is_one_byte = right->IsOneByteRepresentation();
485 bool is_one_byte = left_is_one_byte && right_is_one_byte;
486 bool is_one_byte_data_in_two_byte_string = false;
488 // At least one of the strings uses two-byte representation so we
489 // can't use the fast case code for short ASCII strings below, but
490 // we can try to save memory if all chars actually fit in ASCII.
491 is_one_byte_data_in_two_byte_string =
492 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
493 if (is_one_byte_data_in_two_byte_string) {
494 isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
498 // If the resulting string is small make a flat string.
499 if (length < ConsString::kMinLength) {
500 // Note that neither of the two inputs can be a slice because:
501 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
502 ASSERT(left->IsFlat());
503 ASSERT(right->IsFlat());
505 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
507 Handle<SeqOneByteString> result =
508 NewRawOneByteString(length).ToHandleChecked();
509 DisallowHeapAllocation no_gc;
510 uint8_t* dest = result->GetChars();
512 const uint8_t* src = left->IsExternalString()
513 ? Handle<ExternalAsciiString>::cast(left)->GetChars()
514 : Handle<SeqOneByteString>::cast(left)->GetChars();
515 for (int i = 0; i < left_length; i++) *dest++ = src[i];
517 src = right->IsExternalString()
518 ? Handle<ExternalAsciiString>::cast(right)->GetChars()
519 : Handle<SeqOneByteString>::cast(right)->GetChars();
520 for (int i = 0; i < right_length; i++) *dest++ = src[i];
524 return (is_one_byte_data_in_two_byte_string)
525 ? ConcatStringContent<uint8_t>(
526 NewRawOneByteString(length).ToHandleChecked(), left, right)
527 : ConcatStringContent<uc16>(
528 NewRawTwoByteString(length).ToHandleChecked(), left, right);
531 Handle<Map> map = (is_one_byte || is_one_byte_data_in_two_byte_string)
532 ? cons_ascii_string_map() : cons_string_map();
533 Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
535 DisallowHeapAllocation no_gc;
536 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
538 result->set_hash_field(String::kEmptyHashField);
539 result->set_length(length);
540 result->set_first(*left, mode);
541 result->set_second(*right, mode);
546 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
547 Handle<String> second) {
548 int total_length = first->length() + second->length();
549 if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
550 return ConcatStringContent<uint8_t>(
551 NewRawOneByteString(total_length).ToHandleChecked(), first, second);
553 return ConcatStringContent<uc16>(
554 NewRawTwoByteString(total_length).ToHandleChecked(), first, second);
559 Handle<String> Factory::NewProperSubString(Handle<String> str,
563 if (FLAG_verify_heap) str->StringVerify();
565 ASSERT(begin > 0 || end < str->length());
567 str = String::Flatten(str);
569 int length = end - begin;
570 if (length <= 0) return empty_string();
572 return LookupSingleCharacterStringFromCode(str->Get(begin));
575 // Optimization for 2-byte strings often used as keys in a decompression
576 // dictionary. Check whether we already have the string in the string
577 // table to prevent creation of many unnecessary strings.
578 uint16_t c1 = str->Get(begin);
579 uint16_t c2 = str->Get(begin + 1);
580 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
583 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
584 if (str->IsOneByteRepresentation()) {
585 Handle<SeqOneByteString> result =
586 NewRawOneByteString(length).ToHandleChecked();
587 uint8_t* dest = result->GetChars();
588 DisallowHeapAllocation no_gc;
589 String::WriteToFlat(*str, dest, begin, end);
592 Handle<SeqTwoByteString> result =
593 NewRawTwoByteString(length).ToHandleChecked();
594 uc16* dest = result->GetChars();
595 DisallowHeapAllocation no_gc;
596 String::WriteToFlat(*str, dest, begin, end);
603 if (str->IsSlicedString()) {
604 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
605 str = Handle<String>(slice->parent(), isolate());
606 offset += slice->offset();
609 ASSERT(str->IsSeqString() || str->IsExternalString());
610 Handle<Map> map = str->IsOneByteRepresentation() ? sliced_ascii_string_map()
611 : sliced_string_map();
612 Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
614 slice->set_hash_field(String::kEmptyHashField);
615 slice->set_length(length);
616 slice->set_parent(*str);
617 slice->set_offset(offset);
622 MaybeHandle<String> Factory::NewExternalStringFromAscii(
623 const ExternalAsciiString::Resource* resource) {
624 size_t length = resource->length();
625 if (length > static_cast<size_t>(String::kMaxLength)) {
626 return isolate()->Throw<String>(NewInvalidStringLengthError());
629 Handle<Map> map = external_ascii_string_map();
630 Handle<ExternalAsciiString> external_string =
631 New<ExternalAsciiString>(map, NEW_SPACE);
632 external_string->set_length(static_cast<int>(length));
633 external_string->set_hash_field(String::kEmptyHashField);
634 external_string->set_resource(resource);
636 return external_string;
640 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
641 const ExternalTwoByteString::Resource* resource) {
642 size_t length = resource->length();
643 if (length > static_cast<size_t>(String::kMaxLength)) {
644 return isolate()->Throw<String>(NewInvalidStringLengthError());
647 // For small strings we check whether the resource contains only
648 // one byte characters. If yes, we use a different string map.
649 static const size_t kOneByteCheckLengthLimit = 32;
650 bool is_one_byte = length <= kOneByteCheckLengthLimit &&
651 String::IsOneByte(resource->data(), static_cast<int>(length));
652 Handle<Map> map = is_one_byte ?
653 external_string_with_one_byte_data_map() : external_string_map();
654 Handle<ExternalTwoByteString> external_string =
655 New<ExternalTwoByteString>(map, NEW_SPACE);
656 external_string->set_length(static_cast<int>(length));
657 external_string->set_hash_field(String::kEmptyHashField);
658 external_string->set_resource(resource);
660 return external_string;
664 Handle<Symbol> Factory::NewSymbol() {
667 isolate()->heap()->AllocateSymbol(),
672 Handle<Symbol> Factory::NewPrivateSymbol() {
673 Handle<Symbol> symbol = NewSymbol();
674 symbol->set_is_private(true);
679 Handle<Context> Factory::NewNativeContext() {
680 Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
681 array->set_map_no_write_barrier(*native_context_map());
682 Handle<Context> context = Handle<Context>::cast(array);
683 context->set_js_array_maps(*undefined_value());
684 ASSERT(context->IsNativeContext());
689 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
690 Handle<ScopeInfo> scope_info) {
691 Handle<FixedArray> array =
692 NewFixedArray(scope_info->ContextLength(), TENURED);
693 array->set_map_no_write_barrier(*global_context_map());
694 Handle<Context> context = Handle<Context>::cast(array);
695 context->set_closure(*function);
696 context->set_previous(function->context());
697 context->set_extension(*scope_info);
698 context->set_global_object(function->context()->global_object());
699 ASSERT(context->IsGlobalContext());
704 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
705 Handle<FixedArray> array =
706 NewFixedArray(scope_info->ContextLength(), TENURED);
707 array->set_map_no_write_barrier(*module_context_map());
708 // Instance link will be set later.
709 Handle<Context> context = Handle<Context>::cast(array);
710 context->set_extension(Smi::FromInt(0));
715 Handle<Context> Factory::NewFunctionContext(int length,
716 Handle<JSFunction> function) {
717 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
718 Handle<FixedArray> array = NewFixedArray(length);
719 array->set_map_no_write_barrier(*function_context_map());
720 Handle<Context> context = Handle<Context>::cast(array);
721 context->set_closure(*function);
722 context->set_previous(function->context());
723 context->set_extension(Smi::FromInt(0));
724 context->set_global_object(function->context()->global_object());
729 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
730 Handle<Context> previous,
732 Handle<Object> thrown_object) {
733 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
734 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
735 array->set_map_no_write_barrier(*catch_context_map());
736 Handle<Context> context = Handle<Context>::cast(array);
737 context->set_closure(*function);
738 context->set_previous(*previous);
739 context->set_extension(*name);
740 context->set_global_object(previous->global_object());
741 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
746 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
747 Handle<Context> previous,
748 Handle<JSReceiver> extension) {
749 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
750 array->set_map_no_write_barrier(*with_context_map());
751 Handle<Context> context = Handle<Context>::cast(array);
752 context->set_closure(*function);
753 context->set_previous(*previous);
754 context->set_extension(*extension);
755 context->set_global_object(previous->global_object());
760 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
761 Handle<Context> previous,
762 Handle<ScopeInfo> scope_info) {
763 Handle<FixedArray> array =
764 NewFixedArrayWithHoles(scope_info->ContextLength());
765 array->set_map_no_write_barrier(*block_context_map());
766 Handle<Context> context = Handle<Context>::cast(array);
767 context->set_closure(*function);
768 context->set_previous(*previous);
769 context->set_extension(*scope_info);
770 context->set_global_object(previous->global_object());
775 Handle<Struct> Factory::NewStruct(InstanceType type) {
778 isolate()->heap()->AllocateStruct(type),
783 Handle<CodeCache> Factory::NewCodeCache() {
784 Handle<CodeCache> code_cache =
785 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
786 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
787 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
792 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
793 int aliased_context_slot) {
794 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
795 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
796 entry->set_aliased_context_slot(aliased_context_slot);
801 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
802 return Handle<DeclaredAccessorDescriptor>::cast(
803 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
807 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
808 Handle<DeclaredAccessorInfo> info =
809 Handle<DeclaredAccessorInfo>::cast(
810 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
811 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
816 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
817 Handle<ExecutableAccessorInfo> info =
818 Handle<ExecutableAccessorInfo>::cast(
819 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
820 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
825 Handle<Script> Factory::NewScript(Handle<String> source) {
826 // Generate id for this script.
827 Heap* heap = isolate()->heap();
828 int id = heap->last_script_id()->value() + 1;
829 if (!Smi::IsValid(id) || id < 0) id = 1;
830 heap->set_last_script_id(Smi::FromInt(id));
832 // Create and initialize script object.
833 Handle<Foreign> wrapper = NewForeign(0, TENURED);
834 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
835 script->set_source(*source);
836 script->set_name(heap->undefined_value());
837 script->set_id(Smi::FromInt(id));
838 script->set_line_offset(Smi::FromInt(0));
839 script->set_column_offset(Smi::FromInt(0));
840 script->set_context_data(heap->undefined_value());
841 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
842 script->set_wrapper(*wrapper);
843 script->set_line_ends(heap->undefined_value());
844 script->set_eval_from_shared(heap->undefined_value());
845 script->set_eval_from_instructions_offset(Smi::FromInt(0));
846 script->set_flags(Smi::FromInt(0));
852 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
853 CALL_HEAP_FUNCTION(isolate(),
854 isolate()->heap()->AllocateForeign(addr, pretenure),
859 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
860 return NewForeign((Address) desc, TENURED);
864 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
868 isolate()->heap()->AllocateByteArray(length, pretenure),
873 Handle<ExternalArray> Factory::NewExternalArray(int length,
874 ExternalArrayType array_type,
875 void* external_pointer,
876 PretenureFlag pretenure) {
877 ASSERT(0 <= length && length <= Smi::kMaxValue);
880 isolate()->heap()->AllocateExternalArray(length,
888 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
890 ExternalArrayType array_type,
891 PretenureFlag pretenure) {
892 ASSERT(0 <= length && length <= Smi::kMaxValue);
895 isolate()->heap()->AllocateFixedTypedArray(length,
898 FixedTypedArrayBase);
902 Handle<Cell> Factory::NewCell(Handle<Object> value) {
903 AllowDeferredHandleDereference convert_to_cell;
906 isolate()->heap()->AllocateCell(*value),
911 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
914 isolate()->heap()->AllocatePropertyCell(),
919 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
920 AllowDeferredHandleDereference convert_to_cell;
921 Handle<PropertyCell> cell = NewPropertyCellWithHole();
922 PropertyCell::SetValueInferType(cell, value);
927 Handle<AllocationSite> Factory::NewAllocationSite() {
928 Handle<Map> map = allocation_site_map();
929 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
933 site->set_weak_next(isolate()->heap()->allocation_sites_list());
934 isolate()->heap()->set_allocation_sites_list(*site);
939 Handle<Map> Factory::NewMap(InstanceType type,
941 ElementsKind elements_kind) {
944 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
949 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
950 CALL_HEAP_FUNCTION(isolate(),
951 isolate()->heap()->CopyJSObject(*object, NULL),
956 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
957 Handle<JSObject> object,
958 Handle<AllocationSite> site) {
959 CALL_HEAP_FUNCTION(isolate(),
960 isolate()->heap()->CopyJSObject(
962 site.is_null() ? NULL : *site),
967 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
969 CALL_HEAP_FUNCTION(isolate(),
970 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
975 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
976 CALL_HEAP_FUNCTION(isolate(),
977 isolate()->heap()->CopyFixedArray(*array),
982 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
983 Handle<FixedArray> array) {
984 ASSERT(isolate()->heap()->InNewSpace(*array));
985 CALL_HEAP_FUNCTION(isolate(),
986 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
991 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
992 Handle<FixedDoubleArray> array) {
993 CALL_HEAP_FUNCTION(isolate(),
994 isolate()->heap()->CopyFixedDoubleArray(*array),
999 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1000 Handle<ConstantPoolArray> array) {
1001 CALL_HEAP_FUNCTION(isolate(),
1002 isolate()->heap()->CopyConstantPoolArray(*array),
1007 Handle<Object> Factory::NewNumber(double value,
1008 PretenureFlag pretenure) {
1009 // We need to distinguish the minus zero value and this cannot be
1010 // done after conversion to int. Doing this by comparing bit
1011 // patterns is faster than using fpclassify() et al.
1012 if (IsMinusZero(value)) return NewHeapNumber(-0.0, pretenure);
1014 int int_value = FastD2I(value);
1015 if (value == int_value && Smi::IsValid(int_value)) {
1016 return handle(Smi::FromInt(int_value), isolate());
1019 // Materialize the value in the heap.
1020 return NewHeapNumber(value, pretenure);
1024 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1025 PretenureFlag pretenure) {
1026 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1027 // Bypass NumberFromDouble to avoid various redundant checks.
1028 return NewHeapNumber(FastI2D(value), pretenure);
1032 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1033 PretenureFlag pretenure) {
1034 int32_t int32v = static_cast<int32_t>(value);
1035 if (int32v >= 0 && Smi::IsValid(int32v)) {
1036 return handle(Smi::FromInt(int32v), isolate());
1038 return NewHeapNumber(FastUI2D(value), pretenure);
1042 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1043 PretenureFlag pretenure) {
1046 isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1050 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1051 PretenureFlag pretenure) {
1054 isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1058 Handle<Float64x2> Factory::NewFloat64x2(float64x2_value_t value,
1059 PretenureFlag pretenure) {
1062 isolate()->heap()->AllocateFloat64x2(value, pretenure), Float64x2);
1066 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1067 PretenureFlag pretenure) {
1070 isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1074 Handle<Object> Factory::NewTypeError(const char* message,
1075 Vector< Handle<Object> > args) {
1076 return NewError("MakeTypeError", message, args);
1080 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1081 return NewError("$TypeError", message);
1085 Handle<Object> Factory::NewRangeError(const char* message,
1086 Vector< Handle<Object> > args) {
1087 return NewError("MakeRangeError", message, args);
1091 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1092 return NewError("$RangeError", message);
1096 Handle<Object> Factory::NewSyntaxError(const char* message,
1097 Handle<JSArray> args) {
1098 return NewError("MakeSyntaxError", message, args);
1102 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1103 return NewError("$SyntaxError", message);
1107 Handle<Object> Factory::NewReferenceError(const char* message,
1108 Vector< Handle<Object> > args) {
1109 return NewError("MakeReferenceError", message, args);
1113 Handle<Object> Factory::NewReferenceError(const char* message,
1114 Handle<JSArray> args) {
1115 return NewError("MakeReferenceError", message, args);
1119 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1120 return NewError("$ReferenceError", message);
1124 Handle<Object> Factory::NewError(const char* maker,
1125 const char* message,
1126 Vector< Handle<Object> > args) {
1127 // Instantiate a closeable HandleScope for EscapeFrom.
1128 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1129 Handle<FixedArray> array = NewFixedArray(args.length());
1130 for (int i = 0; i < args.length(); i++) {
1131 array->set(i, *args[i]);
1133 Handle<JSArray> object = NewJSArrayWithElements(array);
1134 Handle<Object> result = NewError(maker, message, object);
1135 return result.EscapeFrom(&scope);
1139 Handle<Object> Factory::NewEvalError(const char* message,
1140 Vector< Handle<Object> > args) {
1141 return NewError("MakeEvalError", message, args);
1145 Handle<Object> Factory::NewError(const char* message,
1146 Vector< Handle<Object> > args) {
1147 return NewError("MakeError", message, args);
1151 Handle<String> Factory::EmergencyNewError(const char* message,
1152 Handle<JSArray> args) {
1153 const int kBufferSize = 1000;
1154 char buffer[kBufferSize];
1155 size_t space = kBufferSize;
1156 char* p = &buffer[0];
1158 Vector<char> v(buffer, kBufferSize);
1159 StrNCpy(v, message, space);
1160 space -= Min(space, strlen(message));
1161 p = &buffer[kBufferSize] - space;
1163 for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1168 Handle<String> arg_str = Handle<String>::cast(
1169 Object::GetElement(isolate(), args, i).ToHandleChecked());
1170 SmartArrayPointer<char> arg = arg_str->ToCString();
1171 Vector<char> v2(p, static_cast<int>(space));
1172 StrNCpy(v2, arg.get(), space);
1173 space -= Min(space, strlen(arg.get()));
1174 p = &buffer[kBufferSize] - space;
1181 buffer[kBufferSize - 1] = '\0';
1183 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1187 Handle<Object> Factory::NewError(const char* maker,
1188 const char* message,
1189 Handle<JSArray> args) {
1190 Handle<String> make_str = InternalizeUtf8String(maker);
1191 Handle<Object> fun_obj = Object::GetProperty(
1192 isolate()->js_builtins_object(), make_str).ToHandleChecked();
1193 // If the builtins haven't been properly configured yet this error
1194 // constructor may not have been defined. Bail out.
1195 if (!fun_obj->IsJSFunction()) {
1196 return EmergencyNewError(message, args);
1198 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1199 Handle<Object> message_obj = InternalizeUtf8String(message);
1200 Handle<Object> argv[] = { message_obj, args };
1202 // Invoke the JavaScript factory method. If an exception is thrown while
1203 // running the factory method, use the exception as the result.
1204 Handle<Object> result;
1205 Handle<Object> exception;
1206 if (!Execution::TryCall(fun,
1207 isolate()->js_builtins_object(),
1210 &exception).ToHandle(&result)) {
1217 Handle<Object> Factory::NewError(Handle<String> message) {
1218 return NewError("$Error", message);
1222 Handle<Object> Factory::NewError(const char* constructor,
1223 Handle<String> message) {
1224 Handle<String> constr = InternalizeUtf8String(constructor);
1225 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1226 isolate()->js_builtins_object(), constr).ToHandleChecked());
1227 Handle<Object> argv[] = { message };
1229 // Invoke the JavaScript factory method. If an exception is thrown while
1230 // running the factory method, use the exception as the result.
1231 Handle<Object> result;
1232 Handle<Object> exception;
1233 if (!Execution::TryCall(fun,
1234 isolate()->js_builtins_object(),
1237 &exception).ToHandle(&result)) {
1244 void Factory::InitializeFunction(Handle<JSFunction> function,
1245 Handle<SharedFunctionInfo> info,
1246 Handle<Context> context) {
1247 function->initialize_properties();
1248 function->initialize_elements();
1249 function->set_shared(*info);
1250 function->set_code(info->code());
1251 function->set_context(*context);
1252 function->set_prototype_or_initial_map(*the_hole_value());
1253 function->set_literals_or_bindings(*empty_fixed_array());
1254 function->set_next_function_link(*undefined_value());
1258 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1259 Handle<SharedFunctionInfo> info,
1260 Handle<Context> context,
1261 PretenureFlag pretenure) {
1262 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1263 Handle<JSFunction> result = New<JSFunction>(map, space);
1264 InitializeFunction(result, info, context);
1269 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1270 Handle<String> name,
1271 MaybeHandle<Code> code) {
1272 Handle<Context> context(isolate()->context()->native_context());
1273 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1274 ASSERT((info->strict_mode() == SLOPPY) &&
1275 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1276 map.is_identical_to(
1277 isolate()->sloppy_function_without_prototype_map()) ||
1278 map.is_identical_to(
1279 isolate()->sloppy_function_with_readonly_prototype_map())));
1280 return NewFunction(map, info, context);
1284 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1286 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1290 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1291 Handle<Code> code) {
1293 isolate()->sloppy_function_without_prototype_map(), name, code);
1297 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1299 Handle<Object> prototype,
1300 bool read_only_prototype) {
1301 Handle<Map> map = read_only_prototype
1302 ? isolate()->sloppy_function_with_readonly_prototype_map()
1303 : isolate()->sloppy_function_map();
1304 Handle<JSFunction> result = NewFunction(map, name, code);
1305 result->set_prototype_or_initial_map(*prototype);
1310 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1312 Handle<Object> prototype,
1315 bool read_only_prototype) {
1316 // Allocate the function
1317 Handle<JSFunction> function = NewFunction(
1318 name, code, prototype, read_only_prototype);
1320 Handle<Map> initial_map = NewMap(
1321 type, instance_size, GetInitialFastElementsKind());
1322 if (prototype->IsTheHole() && !function->shared()->is_generator()) {
1323 prototype = NewFunctionPrototype(function);
1325 initial_map->set_prototype(*prototype);
1326 function->set_initial_map(*initial_map);
1327 initial_map->set_constructor(*function);
1333 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1336 int instance_size) {
1337 return NewFunction(name, code, the_hole_value(), type, instance_size);
1341 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1342 // Make sure to use globals from the function's context, since the function
1343 // can be from a different context.
1344 Handle<Context> native_context(function->context()->native_context());
1345 Handle<Map> new_map;
1346 if (function->shared()->is_generator()) {
1347 // Generator prototypes can share maps since they don't have "constructor"
1349 new_map = handle(native_context->generator_object_prototype_map());
1351 // Each function prototype gets a fresh map to avoid unwanted sharing of
1352 // maps between prototypes of different constructors.
1353 Handle<JSFunction> object_function(native_context->object_function());
1354 ASSERT(object_function->has_initial_map());
1355 new_map = Map::Copy(handle(object_function->initial_map()));
1358 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1360 if (!function->shared()->is_generator()) {
1361 JSObject::SetOwnPropertyIgnoreAttributes(prototype,
1362 constructor_string(),
1364 DONT_ENUM).Assert();
1371 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1372 Handle<SharedFunctionInfo> info,
1373 Handle<Context> context,
1374 PretenureFlag pretenure) {
1375 int map_index = Context::FunctionMapIndex(info->strict_mode(),
1376 info->is_generator());
1377 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1378 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1380 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1381 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1384 int index = info->SearchOptimizedCodeMap(context->native_context(),
1386 if (!info->bound() && index < 0) {
1387 int number_of_literals = info->num_literals();
1388 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1389 if (number_of_literals > 0) {
1390 // Store the native context in the literals array prefix. This
1391 // context will be used when creating object, regexp and array
1392 // literals in this function.
1393 literals->set(JSFunction::kLiteralNativeContextIndex,
1394 context->native_context());
1396 result->set_literals(*literals);
1400 // Caching of optimized code enabled and optimized code found.
1401 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1402 if (literals != NULL) result->set_literals(literals);
1403 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1404 ASSERT(!code->marked_for_deoptimization());
1405 result->ReplaceCode(code);
1409 if (isolate()->use_crankshaft() &&
1411 result->is_compiled() &&
1412 !info->is_toplevel() &&
1413 info->allows_lazy_compilation() &&
1414 !info->optimization_disabled() &&
1415 !isolate()->DebuggerHasBreakPoints()) {
1416 result->MarkForOptimization();
1422 Handle<JSObject> Factory::NewIteratorResultObject(Handle<Object> value,
1424 Handle<Map> map(isolate()->native_context()->iterator_result_map());
1425 Handle<JSObject> result = NewJSObjectFromMap(map, NOT_TENURED, false);
1426 result->InObjectPropertyAtPut(
1427 JSGeneratorObject::kResultValuePropertyIndex, *value);
1428 result->InObjectPropertyAtPut(
1429 JSGeneratorObject::kResultDonePropertyIndex, *ToBoolean(done));
1434 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1435 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1436 array->set_map_no_write_barrier(*scope_info_map());
1437 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1442 Handle<JSObject> Factory::NewExternal(void* value) {
1443 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1444 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1445 external->SetInternalField(0, *foreign);
1450 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1451 CALL_HEAP_FUNCTION(isolate(),
1452 isolate()->heap()->AllocateCode(object_size, immovable),
1457 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1459 Handle<Object> self_ref,
1462 int prologue_offset,
1464 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1465 Handle<ConstantPoolArray> constant_pool =
1466 desc.origin->NewConstantPool(isolate());
1469 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1470 int obj_size = Code::SizeFor(body_size);
1472 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1473 ASSERT(isolate()->code_range() == NULL ||
1474 !isolate()->code_range()->valid() ||
1475 isolate()->code_range()->contains(code->address()));
1477 // The code object has not been fully initialized yet. We rely on the
1478 // fact that no allocation will happen from this point on.
1479 DisallowHeapAllocation no_gc;
1480 code->set_gc_metadata(Smi::FromInt(0));
1481 code->set_ic_age(isolate()->heap()->global_ic_age());
1482 code->set_instruction_size(desc.instr_size);
1483 code->set_relocation_info(*reloc_info);
1484 code->set_flags(flags);
1485 code->set_raw_kind_specific_flags1(0);
1486 code->set_raw_kind_specific_flags2(0);
1487 code->set_is_crankshafted(crankshafted);
1488 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1489 code->set_raw_type_feedback_info(*undefined_value());
1490 code->set_next_code_link(*undefined_value());
1491 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1492 code->set_prologue_offset(prologue_offset);
1493 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1494 code->set_marked_for_deoptimization(false);
1498 ASSERT(code->kind() == Code::FUNCTION);
1499 code->set_has_debug_break_slots(true);
1502 desc.origin->PopulateConstantPool(*constant_pool);
1503 code->set_constant_pool(*constant_pool);
1505 // Allow self references to created code object by patching the handle to
1506 // point to the newly allocated Code object.
1507 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1509 // Migrate generated code.
1510 // The generated code can contain Object** values (typically from handles)
1511 // that are dereferenced during the copy to point directly to the actual heap
1512 // objects. These pointers can include references to the code object itself,
1513 // through the self_reference parameter.
1514 code->CopyFrom(desc);
1517 if (FLAG_verify_heap) code->ObjectVerify();
1523 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1524 CALL_HEAP_FUNCTION(isolate(),
1525 isolate()->heap()->CopyCode(*code),
1530 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1531 CALL_HEAP_FUNCTION(isolate(),
1532 isolate()->heap()->CopyCode(*code, reloc_info),
1537 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1538 PretenureFlag pretenure) {
1539 JSFunction::EnsureHasInitialMap(constructor);
1542 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1546 Handle<JSObject> Factory::NewJSObjectWithMemento(
1547 Handle<JSFunction> constructor,
1548 Handle<AllocationSite> site) {
1549 JSFunction::EnsureHasInitialMap(constructor);
1552 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1557 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1558 Handle<ScopeInfo> scope_info) {
1559 // Allocate a fresh map. Modules do not have a prototype.
1560 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1561 // Allocate the object based on the map.
1562 Handle<JSModule> module =
1563 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1564 module->set_context(*context);
1565 module->set_scope_info(*scope_info);
1570 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1571 ASSERT(constructor->has_initial_map());
1572 Handle<Map> map(constructor->initial_map());
1573 ASSERT(map->is_dictionary_map());
1575 // Make sure no field properties are described in the initial map.
1576 // This guarantees us that normalizing the properties does not
1577 // require us to change property values to PropertyCells.
1578 ASSERT(map->NextFreePropertyIndex() == 0);
1580 // Make sure we don't have a ton of pre-allocated slots in the
1581 // global objects. They will be unused once we normalize the object.
1582 ASSERT(map->unused_property_fields() == 0);
1583 ASSERT(map->inobject_properties() == 0);
1585 // Initial size of the backing store to avoid resize of the storage during
1586 // bootstrapping. The size differs between the JS global object ad the
1588 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1590 // Allocate a dictionary object for backing storage.
1591 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1592 Handle<NameDictionary> dictionary =
1593 NameDictionary::New(isolate(), at_least_space_for);
1595 // The global object might be created from an object template with accessors.
1596 // Fill these accessors into the dictionary.
1597 Handle<DescriptorArray> descs(map->instance_descriptors());
1598 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1599 PropertyDetails details = descs->GetDetails(i);
1600 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
1601 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1602 Handle<Name> name(descs->GetKey(i));
1603 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1604 Handle<PropertyCell> cell = NewPropertyCell(value);
1605 // |dictionary| already contains enough space for all properties.
1606 USE(NameDictionary::Add(dictionary, name, cell, d));
1609 // Allocate the global object and initialize it with the backing store.
1610 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1611 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1613 // Create a new map for the global object.
1614 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1615 new_map->set_dictionary_map(true);
1617 // Set up the global object as a normalized object.
1618 global->set_map(*new_map);
1619 global->set_properties(*dictionary);
1621 // Make sure result is a global object with properties in dictionary.
1622 ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1627 Handle<JSObject> Factory::NewJSObjectFromMap(
1629 PretenureFlag pretenure,
1631 Handle<AllocationSite> allocation_site) {
1634 isolate()->heap()->AllocateJSObjectFromMap(
1638 allocation_site.is_null() ? NULL : *allocation_site),
1643 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1644 PretenureFlag pretenure) {
1645 Context* native_context = isolate()->context()->native_context();
1646 JSFunction* array_function = native_context->array_function();
1647 Map* map = array_function->initial_map();
1648 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1649 if (transition_map != NULL) map = transition_map;
1650 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1654 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1657 ArrayStorageAllocationMode mode,
1658 PretenureFlag pretenure) {
1659 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1660 NewJSArrayStorage(array, length, capacity, mode);
1665 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1666 ElementsKind elements_kind,
1668 PretenureFlag pretenure) {
1669 ASSERT(length <= elements->length());
1670 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1672 array->set_elements(*elements);
1673 array->set_length(Smi::FromInt(length));
1674 JSObject::ValidateElements(array);
1679 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1682 ArrayStorageAllocationMode mode) {
1683 ASSERT(capacity >= length);
1685 if (capacity == 0) {
1686 array->set_length(Smi::FromInt(0));
1687 array->set_elements(*empty_fixed_array());
1691 Handle<FixedArrayBase> elms;
1692 ElementsKind elements_kind = array->GetElementsKind();
1693 if (IsFastDoubleElementsKind(elements_kind)) {
1694 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1695 elms = NewFixedDoubleArray(capacity);
1697 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1698 elms = NewFixedDoubleArrayWithHoles(capacity);
1701 ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
1702 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1703 elms = NewUninitializedFixedArray(capacity);
1705 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1706 elms = NewFixedArrayWithHoles(capacity);
1710 array->set_elements(*elms);
1711 array->set_length(Smi::FromInt(length));
1715 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1716 Handle<JSFunction> function) {
1717 ASSERT(function->shared()->is_generator());
1718 JSFunction::EnsureHasInitialMap(function);
1719 Handle<Map> map(function->initial_map());
1720 ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1723 isolate()->heap()->AllocateJSObjectFromMap(*map),
1728 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1729 Handle<JSFunction> array_buffer_fun(
1730 isolate()->context()->native_context()->array_buffer_fun());
1733 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1738 Handle<JSDataView> Factory::NewJSDataView() {
1739 Handle<JSFunction> data_view_fun(
1740 isolate()->context()->native_context()->data_view_fun());
1743 isolate()->heap()->AllocateJSObject(*data_view_fun),
1748 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1750 Context* native_context = isolate->context()->native_context();
1752 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1753 case kExternal##Type##Array: \
1754 return native_context->type##_array_fun();
1756 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1757 #undef TYPED_ARRAY_FUN
1766 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1767 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1771 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1776 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1777 Handle<Object> prototype) {
1779 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1780 // maps. Will probably depend on the identity of the handler object, too.
1781 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1782 map->set_prototype(*prototype);
1784 // Allocate the proxy object.
1785 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1786 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1787 result->set_handler(*handler);
1788 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1793 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1794 Handle<Object> call_trap,
1795 Handle<Object> construct_trap,
1796 Handle<Object> prototype) {
1798 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1799 // maps. Will probably depend on the identity of the handler object, too.
1800 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1801 map->set_prototype(*prototype);
1803 // Allocate the proxy object.
1804 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1805 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1806 result->set_handler(*handler);
1807 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1808 result->set_call_trap(*call_trap);
1809 result->set_construct_trap(*construct_trap);
1814 void Factory::ReinitializeJSReceiver(Handle<JSReceiver> object,
1817 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
1819 // Allocate fresh map.
1820 // TODO(rossberg): Once we optimize proxies, cache these maps.
1821 Handle<Map> map = NewMap(type, size);
1823 // Check that the receiver has at least the size of the fresh object.
1824 int size_difference = object->map()->instance_size() - map->instance_size();
1825 ASSERT(size_difference >= 0);
1827 map->set_prototype(object->map()->prototype());
1829 // Allocate the backing storage for the properties.
1830 int prop_size = map->InitialPropertiesLength();
1831 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1833 Heap* heap = isolate()->heap();
1834 MaybeHandle<SharedFunctionInfo> shared;
1835 if (type == JS_FUNCTION_TYPE) {
1836 OneByteStringKey key(STATIC_ASCII_VECTOR("<freezing call trap>"),
1838 Handle<String> name = InternalizeStringWithKey(&key);
1839 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1842 // In order to keep heap in consistent state there must be no allocations
1843 // before object re-initialization is finished and filler object is installed.
1844 DisallowHeapAllocation no_allocation;
1846 // Reset the map for the object.
1847 object->set_map(*map);
1848 Handle<JSObject> jsobj = Handle<JSObject>::cast(object);
1850 // Reinitialize the object from the constructor map.
1851 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1853 // Functions require some minimal initialization.
1854 if (type == JS_FUNCTION_TYPE) {
1855 map->set_function_with_prototype(true);
1856 Handle<JSFunction> js_function = Handle<JSFunction>::cast(object);
1857 Handle<Context> context(isolate()->context()->native_context());
1858 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1861 // Put in filler if the new object is smaller than the old.
1862 if (size_difference > 0) {
1863 heap->CreateFillerObjectAt(
1864 object->address() + map->instance_size(), size_difference);
1869 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1870 Handle<JSFunction> constructor) {
1871 ASSERT(constructor->has_initial_map());
1872 Handle<Map> map(constructor->initial_map(), isolate());
1874 // The proxy's hash should be retained across reinitialization.
1875 Handle<Object> hash(object->hash(), isolate());
1877 // Check that the already allocated object has the same size and type as
1878 // objects allocated using the constructor.
1879 ASSERT(map->instance_size() == object->map()->instance_size());
1880 ASSERT(map->instance_type() == object->map()->instance_type());
1882 // Allocate the backing storage for the properties.
1883 int prop_size = map->InitialPropertiesLength();
1884 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1886 // In order to keep heap in consistent state there must be no allocations
1887 // before object re-initialization is finished.
1888 DisallowHeapAllocation no_allocation;
1890 // Reset the map for the object.
1891 object->set_map(constructor->initial_map());
1893 Heap* heap = isolate()->heap();
1894 // Reinitialize the object from the constructor map.
1895 heap->InitializeJSObjectFromMap(*object, *properties, *map);
1897 // Restore the saved hash.
1898 object->set_hash(*hash);
1902 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1903 ReinitializeJSReceiver(object, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1907 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1908 ReinitializeJSReceiver(object, JS_FUNCTION_TYPE, JSFunction::kSize);
1912 Handle<FixedArray> Factory::NewTypeFeedbackVector(int slot_count) {
1913 // Ensure we can skip the write barrier
1914 ASSERT_EQ(isolate()->heap()->uninitialized_symbol(),
1915 *TypeFeedbackInfo::UninitializedSentinel(isolate()));
1919 isolate()->heap()->AllocateFixedArrayWithFiller(
1922 *TypeFeedbackInfo::UninitializedSentinel(isolate())),
1927 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1928 Handle<String> name,
1929 int number_of_literals,
1932 Handle<ScopeInfo> scope_info,
1933 Handle<FixedArray> feedback_vector) {
1934 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
1935 shared->set_scope_info(*scope_info);
1936 shared->set_feedback_vector(*feedback_vector);
1937 int literals_array_size = number_of_literals;
1938 // If the function contains object, regexp or array literals,
1939 // allocate extra space for a literals array prefix containing the
1941 if (number_of_literals > 0) {
1942 literals_array_size += JSFunction::kLiteralsPrefixSize;
1944 shared->set_num_literals(literals_array_size);
1946 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1947 shared->DisableOptimization(kGenerator);
1953 Handle<JSMessageObject> Factory::NewJSMessageObject(
1954 Handle<String> type,
1955 Handle<JSArray> arguments,
1958 Handle<Object> script,
1959 Handle<Object> stack_frames) {
1960 Handle<Map> map = message_object_map();
1961 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
1962 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1963 message->initialize_elements();
1964 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1965 message->set_type(*type);
1966 message->set_arguments(*arguments);
1967 message->set_start_position(start_position);
1968 message->set_end_position(end_position);
1969 message->set_script(*script);
1970 message->set_stack_frames(*stack_frames);
1975 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1976 Handle<String> name,
1977 MaybeHandle<Code> maybe_code) {
1978 Handle<Map> map = shared_function_info_map();
1979 Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
1982 // Set pointer fields.
1983 share->set_name(*name);
1985 if (!maybe_code.ToHandle(&code)) {
1986 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
1988 share->set_code(*code);
1989 share->set_optimized_code_map(Smi::FromInt(0));
1990 share->set_scope_info(ScopeInfo::Empty(isolate()));
1991 Code* construct_stub =
1992 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
1993 share->set_construct_stub(construct_stub);
1994 share->set_instance_class_name(*Object_string());
1995 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
1996 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
1997 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
1998 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
1999 share->set_feedback_vector(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2000 share->set_profiler_ticks(0);
2001 share->set_ast_node_count(0);
2002 share->set_counters(0);
2004 // Set integer fields (smi or int, depending on the architecture).
2005 share->set_length(0);
2006 share->set_formal_parameter_count(0);
2007 share->set_expected_nof_properties(0);
2008 share->set_num_literals(0);
2009 share->set_start_position_and_type(0);
2010 share->set_end_position(0);
2011 share->set_function_token_position(0);
2012 // All compiler hints default to false or 0.
2013 share->set_compiler_hints(0);
2014 share->set_opt_count_and_bailout_reason(0);
2020 static inline int NumberCacheHash(Handle<FixedArray> cache,
2021 Handle<Object> number) {
2022 int mask = (cache->length() >> 1) - 1;
2023 if (number->IsSmi()) {
2024 return Handle<Smi>::cast(number)->value() & mask;
2026 DoubleRepresentation rep(number->Number());
2028 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2033 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2034 DisallowHeapAllocation no_gc;
2035 int hash = NumberCacheHash(number_string_cache(), number);
2036 Object* key = number_string_cache()->get(hash * 2);
2037 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2038 key->Number() == number->Number())) {
2039 return Handle<String>(
2040 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2042 return undefined_value();
2046 void Factory::SetNumberStringCache(Handle<Object> number,
2047 Handle<String> string) {
2048 int hash = NumberCacheHash(number_string_cache(), number);
2049 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2050 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2051 if (number_string_cache()->length() != full_size) {
2052 // The first time we have a hash collision, we move to the full sized
2053 // number string cache. The idea is to have a small number string
2054 // cache in the snapshot to keep boot-time memory usage down.
2055 // If we expand the number string cache already while creating
2056 // the snapshot then that didn't work out.
2057 ASSERT(!isolate()->serializer_enabled() || FLAG_extra_code != NULL);
2058 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2059 isolate()->heap()->set_number_string_cache(*new_cache);
2063 number_string_cache()->set(hash * 2, *number);
2064 number_string_cache()->set(hash * 2 + 1, *string);
2068 Handle<String> Factory::NumberToString(Handle<Object> number,
2069 bool check_number_string_cache) {
2070 isolate()->counters()->number_to_string_runtime()->Increment();
2071 if (check_number_string_cache) {
2072 Handle<Object> cached = GetNumberStringCache(number);
2073 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2077 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2079 if (number->IsSmi()) {
2080 int num = Handle<Smi>::cast(number)->value();
2081 str = IntToCString(num, buffer);
2083 double num = Handle<HeapNumber>::cast(number)->value();
2084 str = DoubleToCString(num, buffer);
2087 // We tenure the allocated string since it is referenced from the
2088 // number-string cache which lives in the old space.
2089 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2090 SetNumberStringCache(number, js_string);
2095 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2096 // Get the original code of the function.
2097 Handle<Code> code(shared->code());
2099 // Create a copy of the code before allocating the debug info object to avoid
2100 // allocation while setting up the debug info object.
2101 Handle<Code> original_code(*Factory::CopyCode(code));
2103 // Allocate initial fixed array for active break points before allocating the
2104 // debug info object to avoid allocation while setting up the debug info
2106 Handle<FixedArray> break_points(
2107 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2109 // Create and set up the debug info object. Debug info contains function, a
2110 // copy of the original code, the executing code and initial fixed array for
2111 // active break points.
2112 Handle<DebugInfo> debug_info =
2113 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2114 debug_info->set_shared(*shared);
2115 debug_info->set_original_code(*original_code);
2116 debug_info->set_code(*code);
2117 debug_info->set_break_points(*break_points);
2119 // Link debug info to function.
2120 shared->set_debug_info(*debug_info);
2126 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
2130 isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
2134 Handle<JSFunction> Factory::CreateApiFunction(
2135 Handle<FunctionTemplateInfo> obj,
2136 Handle<Object> prototype,
2137 ApiInstanceType instance_type) {
2138 Handle<Code> code = isolate()->builtins()->HandleApiCall();
2139 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
2141 Handle<JSFunction> result;
2142 if (obj->remove_prototype()) {
2143 result = NewFunctionWithoutPrototype(empty_string(), code);
2145 int internal_field_count = 0;
2146 if (!obj->instance_template()->IsUndefined()) {
2147 Handle<ObjectTemplateInfo> instance_template =
2148 Handle<ObjectTemplateInfo>(
2149 ObjectTemplateInfo::cast(obj->instance_template()));
2150 internal_field_count =
2151 Smi::cast(instance_template->internal_field_count())->value();
2154 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
2155 // JSObject::GetHeaderSize.
2156 int instance_size = kPointerSize * internal_field_count;
2158 switch (instance_type) {
2159 case JavaScriptObject:
2160 type = JS_OBJECT_TYPE;
2161 instance_size += JSObject::kHeaderSize;
2163 case InnerGlobalObject:
2164 type = JS_GLOBAL_OBJECT_TYPE;
2165 instance_size += JSGlobalObject::kSize;
2167 case OuterGlobalObject:
2168 type = JS_GLOBAL_PROXY_TYPE;
2169 instance_size += JSGlobalProxy::kSize;
2173 type = JS_OBJECT_TYPE; // Keep the compiler happy.
2177 result = NewFunction(empty_string(), code, prototype, type,
2178 instance_size, obj->read_only_prototype());
2181 result->shared()->set_length(obj->length());
2182 Handle<Object> class_name(obj->class_name(), isolate());
2183 if (class_name->IsString()) {
2184 result->shared()->set_instance_class_name(*class_name);
2185 result->shared()->set_name(*class_name);
2187 result->shared()->set_function_data(*obj);
2188 result->shared()->set_construct_stub(*construct_stub);
2189 result->shared()->DontAdaptArguments();
2191 if (obj->remove_prototype()) {
2192 ASSERT(result->shared()->IsApiFunction());
2193 ASSERT(!result->has_initial_map());
2194 ASSERT(!result->has_prototype());
2198 JSObject::SetOwnPropertyIgnoreAttributes(
2199 handle(JSObject::cast(result->prototype())),
2200 constructor_string(),
2202 DONT_ENUM).Assert();
2204 // Down from here is only valid for API functions that can be used as a
2205 // constructor (don't set the "remove prototype" flag).
2207 Handle<Map> map(result->initial_map());
2209 // Mark as undetectable if needed.
2210 if (obj->undetectable()) {
2211 map->set_is_undetectable();
2214 // Mark as hidden for the __proto__ accessor if needed.
2215 if (obj->hidden_prototype()) {
2216 map->set_is_hidden_prototype();
2219 // Mark as needs_access_check if needed.
2220 if (obj->needs_access_check()) {
2221 map->set_is_access_check_needed(true);
2224 // Set interceptor information in the map.
2225 if (!obj->named_property_handler()->IsUndefined()) {
2226 map->set_has_named_interceptor();
2228 if (!obj->indexed_property_handler()->IsUndefined()) {
2229 map->set_has_indexed_interceptor();
2232 // Set instance call-as-function information in the map.
2233 if (!obj->instance_call_handler()->IsUndefined()) {
2234 map->set_has_instance_call_handler();
2237 // Recursively copy parent instance templates' accessors,
2238 // 'data' may be modified.
2239 int max_number_of_additional_properties = 0;
2240 int max_number_of_static_properties = 0;
2241 FunctionTemplateInfo* info = *obj;
2243 if (!info->instance_template()->IsUndefined()) {
2245 ObjectTemplateInfo::cast(
2246 info->instance_template())->property_accessors();
2247 if (!props->IsUndefined()) {
2248 Handle<Object> props_handle(props, isolate());
2249 NeanderArray props_array(props_handle);
2250 max_number_of_additional_properties += props_array.length();
2253 if (!info->property_accessors()->IsUndefined()) {
2254 Object* props = info->property_accessors();
2255 if (!props->IsUndefined()) {
2256 Handle<Object> props_handle(props, isolate());
2257 NeanderArray props_array(props_handle);
2258 max_number_of_static_properties += props_array.length();
2261 Object* parent = info->parent_template();
2262 if (parent->IsUndefined()) break;
2263 info = FunctionTemplateInfo::cast(parent);
2266 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
2268 // Use a temporary FixedArray to acculumate static accessors
2269 int valid_descriptors = 0;
2270 Handle<FixedArray> array;
2271 if (max_number_of_static_properties > 0) {
2272 array = NewFixedArray(max_number_of_static_properties);
2276 // Install instance descriptors
2277 if (!obj->instance_template()->IsUndefined()) {
2278 Handle<ObjectTemplateInfo> instance =
2279 Handle<ObjectTemplateInfo>(
2280 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
2281 Handle<Object> props = Handle<Object>(instance->property_accessors(),
2283 if (!props->IsUndefined()) {
2284 Map::AppendCallbackDescriptors(map, props);
2287 // Accumulate static accessors
2288 if (!obj->property_accessors()->IsUndefined()) {
2289 Handle<Object> props = Handle<Object>(obj->property_accessors(),
2292 AccessorInfo::AppendUnique(props, array, valid_descriptors);
2294 // Climb parent chain
2295 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
2296 if (parent->IsUndefined()) break;
2297 obj = Handle<FunctionTemplateInfo>::cast(parent);
2300 // Install accumulated static accessors
2301 for (int i = 0; i < valid_descriptors; i++) {
2302 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
2303 JSObject::SetAccessor(result, accessor).Assert();
2306 ASSERT(result->shared()->IsApiFunction());
2311 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
2312 Handle<FixedArray> keys,
2314 Handle<MapCache> map_cache = handle(MapCache::cast(context->map_cache()));
2315 Handle<MapCache> result = MapCache::Put(map_cache, keys, map);
2316 context->set_map_cache(*result);
2321 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2322 Handle<FixedArray> keys) {
2323 if (context->map_cache()->IsUndefined()) {
2324 // Allocate the new map cache for the native context.
2325 Handle<MapCache> new_cache = MapCache::New(isolate(), 24);
2326 context->set_map_cache(*new_cache);
2328 // Check to see whether there is a matching element in the cache.
2329 Handle<MapCache> cache =
2330 Handle<MapCache>(MapCache::cast(context->map_cache()));
2331 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
2332 if (result->IsMap()) return Handle<Map>::cast(result);
2333 // Create a new map and add it to the cache.
2334 Handle<Map> map = Map::Create(
2335 handle(context->object_function()), keys->length());
2336 AddToMapCache(context, keys, map);
2341 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2342 JSRegExp::Type type,
2343 Handle<String> source,
2344 JSRegExp::Flags flags,
2345 Handle<Object> data) {
2346 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2348 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2349 store->set(JSRegExp::kSourceIndex, *source);
2350 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2351 store->set(JSRegExp::kAtomPatternIndex, *data);
2352 regexp->set_data(*store);
2355 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2356 JSRegExp::Type type,
2357 Handle<String> source,
2358 JSRegExp::Flags flags,
2359 int capture_count) {
2360 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2361 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2362 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2363 store->set(JSRegExp::kSourceIndex, *source);
2364 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2365 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
2366 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2367 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
2368 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2369 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2370 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2371 Smi::FromInt(capture_count));
2372 regexp->set_data(*store);
2377 MaybeHandle<FunctionTemplateInfo> Factory::ConfigureInstance(
2378 Handle<FunctionTemplateInfo> desc, Handle<JSObject> instance) {
2379 // Configure the instance by adding the properties specified by the
2380 // instance template.
2381 Handle<Object> instance_template(desc->instance_template(), isolate());
2382 if (!instance_template->IsUndefined()) {
2383 RETURN_ON_EXCEPTION(
2385 Execution::ConfigureInstance(isolate(), instance, instance_template),
2386 FunctionTemplateInfo);
2392 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2393 if (String::Equals(name, undefined_string())) return undefined_value();
2394 if (String::Equals(name, nan_string())) return nan_value();
2395 if (String::Equals(name, infinity_string())) return infinity_value();
2396 return Handle<Object>::null();
2400 Handle<Object> Factory::ToBoolean(bool value) {
2401 return value ? true_value() : false_value();
2405 } } // namespace v8::internal