1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "execution.h"
34 #include "isolate-inl.h"
35 #include "macro-assembler.h"
37 #include "objects-visiting.h"
39 #include "scopeinfo.h"
45 Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
48 isolate()->heap()->AllocateBox(*value, pretenure),
53 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
57 isolate()->heap()->AllocateFixedArray(size, pretenure),
62 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
63 PretenureFlag pretenure) {
67 isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
72 Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
73 PretenureFlag pretenure) {
77 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
82 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
83 int number_of_int64_entries,
84 int number_of_ptr_entries,
85 int number_of_int32_entries) {
86 ASSERT(number_of_int64_entries > 0 || number_of_ptr_entries > 0 ||
87 number_of_int32_entries > 0);
90 isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
91 number_of_ptr_entries,
92 number_of_int32_entries),
97 Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
98 ASSERT(0 <= at_least_space_for);
99 CALL_HEAP_FUNCTION(isolate(),
100 NameDictionary::Allocate(isolate()->heap(),
106 Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
107 int at_least_space_for) {
108 ASSERT(0 <= at_least_space_for);
109 CALL_HEAP_FUNCTION(isolate(),
110 SeededNumberDictionary::Allocate(isolate()->heap(),
112 SeededNumberDictionary);
116 Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
117 int at_least_space_for) {
118 ASSERT(0 <= at_least_space_for);
119 CALL_HEAP_FUNCTION(isolate(),
120 UnseededNumberDictionary::Allocate(isolate()->heap(),
122 UnseededNumberDictionary);
126 Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
127 ASSERT(0 <= at_least_space_for);
128 CALL_HEAP_FUNCTION(isolate(),
129 ObjectHashSet::Allocate(isolate()->heap(),
135 Handle<ObjectHashTable> Factory::NewObjectHashTable(
136 int at_least_space_for,
137 MinimumCapacity capacity_option) {
138 ASSERT(0 <= at_least_space_for);
139 CALL_HEAP_FUNCTION(isolate(),
140 ObjectHashTable::Allocate(isolate()->heap(),
147 Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
148 ASSERT(0 <= at_least_space_for);
151 WeakHashTable::Allocate(isolate()->heap(),
153 USE_DEFAULT_MINIMUM_CAPACITY,
159 Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
161 ASSERT(0 <= number_of_descriptors);
162 CALL_HEAP_FUNCTION(isolate(),
163 DescriptorArray::Allocate(
164 isolate(), number_of_descriptors, slack),
169 Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
170 int deopt_entry_count,
171 PretenureFlag pretenure) {
172 ASSERT(deopt_entry_count > 0);
173 CALL_HEAP_FUNCTION(isolate(),
174 DeoptimizationInputData::Allocate(isolate(),
177 DeoptimizationInputData);
181 Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
182 int deopt_entry_count,
183 PretenureFlag pretenure) {
184 ASSERT(deopt_entry_count > 0);
185 CALL_HEAP_FUNCTION(isolate(),
186 DeoptimizationOutputData::Allocate(isolate(),
189 DeoptimizationOutputData);
193 Handle<AccessorPair> Factory::NewAccessorPair() {
194 CALL_HEAP_FUNCTION(isolate(),
195 isolate()->heap()->AllocateAccessorPair(),
200 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
201 CALL_HEAP_FUNCTION(isolate(),
202 isolate()->heap()->AllocateTypeFeedbackInfo(),
207 // Internalized strings are created in the old generation (data space).
208 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
209 Utf8StringKey key(string, isolate()->heap()->HashSeed());
210 return InternalizeStringWithKey(&key);
214 // Internalized strings are created in the old generation (data space).
215 Handle<String> Factory::InternalizeString(Handle<String> string) {
216 CALL_HEAP_FUNCTION(isolate(),
217 isolate()->heap()->InternalizeString(*string),
222 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
223 OneByteStringKey key(string, isolate()->heap()->HashSeed());
224 return InternalizeStringWithKey(&key);
228 Handle<String> Factory::InternalizeOneByteString(
229 Handle<SeqOneByteString> string, int from, int length) {
230 SubStringKey<uint8_t> key(string, from, length);
231 return InternalizeStringWithKey(&key);
235 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
236 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
237 return InternalizeStringWithKey(&key);
241 template<class StringTableKey>
242 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
243 CALL_HEAP_FUNCTION(isolate(),
244 isolate()->heap()->InternalizeStringWithKey(key),
249 template Handle<String> Factory::InternalizeStringWithKey<
250 SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
251 template Handle<String> Factory::InternalizeStringWithKey<
252 SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
255 Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
256 PretenureFlag pretenure) {
259 isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
263 Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
264 PretenureFlag pretenure) {
267 isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
272 Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
273 PretenureFlag pretenure) {
276 isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
281 Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
282 PretenureFlag pretenure) {
285 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
290 Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
291 PretenureFlag pretenure) {
294 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
299 // Returns true for a character in a range. Both limits are inclusive.
300 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
301 // This makes uses of the the unsigned wraparound.
302 return character - from <= to - from;
306 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
309 // Numeric strings have a different hash algorithm not known by
310 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
311 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
313 StringTable* table = isolate->heap()->string_table();
314 if (table->LookupTwoCharsStringIfExists(c1, c2, &result)) {
315 return handle(result);
319 // Now we know the length is 2, we might as well make use of that fact
320 // when building the new string.
321 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
323 ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
324 Handle<SeqOneByteString> str = isolate->factory()->NewRawOneByteString(2);
325 uint8_t* dest = str->GetChars();
326 dest[0] = static_cast<uint8_t>(c1);
327 dest[1] = static_cast<uint8_t>(c2);
330 Handle<SeqTwoByteString> str = isolate->factory()->NewRawTwoByteString(2);
331 uc16* dest = str->GetChars();
339 template<typename SinkChar, typename StringType>
340 Handle<String> ConcatStringContent(Handle<StringType> result,
341 Handle<String> first,
342 Handle<String> second) {
343 DisallowHeapAllocation pointer_stays_valid;
344 SinkChar* sink = result->GetChars();
345 String::WriteToFlat(*first, sink, 0, first->length());
346 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
351 Handle<ConsString> Factory::NewRawConsString(String::Encoding encoding) {
352 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
353 ? cons_ascii_string_map() : cons_string_map();
354 CALL_HEAP_FUNCTION(isolate(),
355 isolate()->heap()->Allocate(*map, NEW_SPACE),
360 Handle<String> Factory::NewConsString(Handle<String> left,
361 Handle<String> right) {
362 int left_length = left->length();
363 if (left_length == 0) return right;
364 int right_length = right->length();
365 if (right_length == 0) return left;
367 int length = left_length + right_length;
370 uint16_t c1 = left->Get(0);
371 uint16_t c2 = right->Get(0);
372 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
375 // Make sure that an out of memory exception is thrown if the length
376 // of the new cons string is too large.
377 if (length > String::kMaxLength || length < 0) {
378 isolate()->context()->mark_out_of_memory();
379 V8::FatalProcessOutOfMemory("String concatenation result too large.");
381 return Handle<String>::null();
384 bool left_is_one_byte = left->IsOneByteRepresentation();
385 bool right_is_one_byte = right->IsOneByteRepresentation();
386 bool is_one_byte = left_is_one_byte && right_is_one_byte;
387 bool is_one_byte_data_in_two_byte_string = false;
389 // At least one of the strings uses two-byte representation so we
390 // can't use the fast case code for short ASCII strings below, but
391 // we can try to save memory if all chars actually fit in ASCII.
392 is_one_byte_data_in_two_byte_string =
393 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
394 if (is_one_byte_data_in_two_byte_string) {
395 isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
399 // If the resulting string is small make a flat string.
400 if (length < ConsString::kMinLength) {
401 // Note that neither of the two inputs can be a slice because:
402 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
403 ASSERT(left->IsFlat());
404 ASSERT(right->IsFlat());
407 Handle<SeqOneByteString> result = NewRawOneByteString(length);
408 DisallowHeapAllocation no_gc;
409 uint8_t* dest = result->GetChars();
411 const uint8_t* src = left->IsExternalString()
412 ? Handle<ExternalAsciiString>::cast(left)->GetChars()
413 : Handle<SeqOneByteString>::cast(left)->GetChars();
414 for (int i = 0; i < left_length; i++) *dest++ = src[i];
416 src = right->IsExternalString()
417 ? Handle<ExternalAsciiString>::cast(right)->GetChars()
418 : Handle<SeqOneByteString>::cast(right)->GetChars();
419 for (int i = 0; i < right_length; i++) *dest++ = src[i];
423 return (is_one_byte_data_in_two_byte_string)
424 ? ConcatStringContent<uint8_t>(NewRawOneByteString(length), left, right)
425 : ConcatStringContent<uc16>(NewRawTwoByteString(length), left, right);
428 Handle<ConsString> result = NewRawConsString(
429 (is_one_byte || is_one_byte_data_in_two_byte_string)
430 ? String::ONE_BYTE_ENCODING
431 : String::TWO_BYTE_ENCODING);
433 DisallowHeapAllocation no_gc;
434 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
436 result->set_hash_field(String::kEmptyHashField);
437 result->set_length(length);
438 result->set_first(*left, mode);
439 result->set_second(*right, mode);
444 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
445 Handle<String> second) {
446 int total_length = first->length() + second->length();
447 if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
448 return ConcatStringContent<uint8_t>(
449 NewRawOneByteString(total_length), first, second);
451 return ConcatStringContent<uc16>(
452 NewRawTwoByteString(total_length), first, second);
457 Handle<SlicedString> Factory::NewRawSlicedString(String::Encoding encoding) {
458 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
459 ? sliced_ascii_string_map() : sliced_string_map();
460 CALL_HEAP_FUNCTION(isolate(),
461 isolate()->heap()->Allocate(*map, NEW_SPACE),
466 Handle<String> Factory::NewProperSubString(Handle<String> str,
470 if (FLAG_verify_heap) str->StringVerify();
472 ASSERT(begin > 0 || end < str->length());
474 int length = end - begin;
475 if (length <= 0) return empty_string();
477 return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
480 // Optimization for 2-byte strings often used as keys in a decompression
481 // dictionary. Check whether we already have the string in the string
482 // table to prevent creation of many unnecessary strings.
483 uint16_t c1 = str->Get(begin);
484 uint16_t c2 = str->Get(begin + 1);
485 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
488 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
489 if (str->IsOneByteRepresentation()) {
490 Handle<SeqOneByteString> result = NewRawOneByteString(length);
491 uint8_t* dest = result->GetChars();
492 DisallowHeapAllocation no_gc;
493 String::WriteToFlat(*str, dest, begin, end);
496 Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
497 uc16* dest = result->GetChars();
498 DisallowHeapAllocation no_gc;
499 String::WriteToFlat(*str, dest, begin, end);
506 while (str->IsConsString()) {
507 Handle<ConsString> cons = Handle<ConsString>::cast(str);
508 int split = cons->first()->length();
509 if (split <= offset) {
510 // Slice is fully contained in the second part.
511 str = Handle<String>(cons->second(), isolate());
512 offset -= split; // Adjust for offset.
514 } else if (offset + length <= split) {
515 // Slice is fully contained in the first part.
516 str = Handle<String>(cons->first(), isolate());
522 if (str->IsSlicedString()) {
523 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
524 str = Handle<String>(slice->parent(), isolate());
525 offset += slice->offset();
527 str = FlattenGetString(str);
530 ASSERT(str->IsSeqString() || str->IsExternalString());
531 Handle<SlicedString> slice = NewRawSlicedString(
532 str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
533 : String::TWO_BYTE_ENCODING);
535 slice->set_hash_field(String::kEmptyHashField);
536 slice->set_length(length);
537 slice->set_parent(*str);
538 slice->set_offset(offset);
543 Handle<String> Factory::NewExternalStringFromAscii(
544 const ExternalAsciiString::Resource* resource) {
547 isolate()->heap()->AllocateExternalStringFromAscii(resource),
552 Handle<String> Factory::NewExternalStringFromTwoByte(
553 const ExternalTwoByteString::Resource* resource) {
556 isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
561 Handle<Symbol> Factory::NewSymbol() {
564 isolate()->heap()->AllocateSymbol(),
569 Handle<Symbol> Factory::NewPrivateSymbol() {
572 isolate()->heap()->AllocatePrivateSymbol(),
577 Handle<Context> Factory::NewNativeContext() {
580 isolate()->heap()->AllocateNativeContext(),
585 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
586 Handle<ScopeInfo> scope_info) {
589 isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
594 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
597 isolate()->heap()->AllocateModuleContext(*scope_info),
602 Handle<Context> Factory::NewFunctionContext(int length,
603 Handle<JSFunction> function) {
606 isolate()->heap()->AllocateFunctionContext(length, *function),
611 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
612 Handle<Context> previous,
614 Handle<Object> thrown_object) {
617 isolate()->heap()->AllocateCatchContext(*function,
625 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
626 Handle<Context> previous,
627 Handle<JSObject> extension) {
630 isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
635 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
636 Handle<Context> previous,
637 Handle<ScopeInfo> scope_info) {
640 isolate()->heap()->AllocateBlockContext(*function,
647 Handle<Struct> Factory::NewStruct(InstanceType type) {
650 isolate()->heap()->AllocateStruct(type),
655 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
656 int aliased_context_slot) {
657 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
658 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
659 entry->set_aliased_context_slot(aliased_context_slot);
664 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
665 return Handle<DeclaredAccessorDescriptor>::cast(
666 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
670 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
671 Handle<DeclaredAccessorInfo> info =
672 Handle<DeclaredAccessorInfo>::cast(
673 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
674 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
679 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
680 Handle<ExecutableAccessorInfo> info =
681 Handle<ExecutableAccessorInfo>::cast(
682 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
683 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
688 Handle<Script> Factory::NewScript(Handle<String> source) {
689 // Generate id for this script.
690 Heap* heap = isolate()->heap();
691 int id = heap->last_script_id()->value() + 1;
692 if (!Smi::IsValid(id) || id < 0) id = 1;
693 heap->set_last_script_id(Smi::FromInt(id));
695 // Create and initialize script object.
696 Handle<Foreign> wrapper = NewForeign(0, TENURED);
697 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
698 script->set_source(*source);
699 script->set_name(heap->undefined_value());
700 script->set_id(Smi::FromInt(id));
701 script->set_line_offset(Smi::FromInt(0));
702 script->set_column_offset(Smi::FromInt(0));
703 script->set_data(heap->undefined_value());
704 script->set_context_data(heap->undefined_value());
705 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
706 script->set_wrapper(*wrapper);
707 script->set_line_ends(heap->undefined_value());
708 script->set_eval_from_shared(heap->undefined_value());
709 script->set_eval_from_instructions_offset(Smi::FromInt(0));
710 script->set_flags(Smi::FromInt(0));
716 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
717 CALL_HEAP_FUNCTION(isolate(),
718 isolate()->heap()->AllocateForeign(addr, pretenure),
723 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
724 return NewForeign((Address) desc, TENURED);
728 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
732 isolate()->heap()->AllocateByteArray(length, pretenure),
737 Handle<ExternalArray> Factory::NewExternalArray(int length,
738 ExternalArrayType array_type,
739 void* external_pointer,
740 PretenureFlag pretenure) {
741 ASSERT(0 <= length && length <= Smi::kMaxValue);
744 isolate()->heap()->AllocateExternalArray(length,
752 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
754 ExternalArrayType array_type,
755 PretenureFlag pretenure) {
756 ASSERT(0 <= length && length <= Smi::kMaxValue);
759 isolate()->heap()->AllocateFixedTypedArray(length,
762 FixedTypedArrayBase);
766 Handle<Cell> Factory::NewCell(Handle<Object> value) {
767 AllowDeferredHandleDereference convert_to_cell;
770 isolate()->heap()->AllocateCell(*value),
775 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
778 isolate()->heap()->AllocatePropertyCell(),
783 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
784 AllowDeferredHandleDereference convert_to_cell;
785 Handle<PropertyCell> cell = NewPropertyCellWithHole();
786 PropertyCell::SetValueInferType(cell, value);
791 Handle<AllocationSite> Factory::NewAllocationSite() {
794 isolate()->heap()->AllocateAllocationSite(),
799 Handle<Map> Factory::NewMap(InstanceType type,
801 ElementsKind elements_kind) {
804 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
809 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
810 // Make sure to use globals from the function's context, since the function
811 // can be from a different context.
812 Handle<Context> native_context(function->context()->native_context());
814 if (function->shared()->is_generator()) {
815 // Generator prototypes can share maps since they don't have "constructor"
817 new_map = handle(native_context->generator_object_prototype_map());
819 // Each function prototype gets a fresh map to avoid unwanted sharing of
820 // maps between prototypes of different constructors.
821 Handle<JSFunction> object_function(native_context->object_function());
822 ASSERT(object_function->has_initial_map());
823 new_map = Map::Copy(handle(object_function->initial_map()));
826 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
828 if (!function->shared()->is_generator()) {
829 JSObject::SetLocalPropertyIgnoreAttributes(prototype,
830 constructor_string(),
839 Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
841 isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
845 Handle<Map> Factory::CopyMap(Handle<Map> src,
846 int extra_inobject_properties) {
847 Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
848 // Check that we do not overflow the instance size when adding the
849 // extra inobject properties.
850 int instance_size_delta = extra_inobject_properties * kPointerSize;
851 int max_instance_size_delta =
852 JSObject::kMaxInstanceSize - copy->instance_size();
853 int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
854 if (extra_inobject_properties > max_extra_properties) {
855 // If the instance size overflows, we allocate as many properties
856 // as we can as inobject properties.
857 instance_size_delta = max_instance_size_delta;
858 extra_inobject_properties = max_extra_properties;
860 // Adjust the map with the extra inobject properties.
861 int inobject_properties =
862 copy->inobject_properties() + extra_inobject_properties;
863 copy->set_inobject_properties(inobject_properties);
864 copy->set_unused_property_fields(inobject_properties);
865 copy->set_instance_size(copy->instance_size() + instance_size_delta);
866 copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
871 Handle<Map> Factory::CopyMap(Handle<Map> src) {
872 CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
876 Handle<Map> Factory::GetElementsTransitionMap(
877 Handle<JSObject> src,
878 ElementsKind elements_kind) {
879 Isolate* i = isolate();
880 CALL_HEAP_FUNCTION(i,
881 src->GetElementsTransitionMap(i, elements_kind),
886 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
887 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
891 Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
893 PretenureFlag pretenure) {
894 CALL_HEAP_FUNCTION(isolate(),
895 array->CopySize(new_length, pretenure),
900 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
901 Handle<FixedDoubleArray> array) {
902 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
906 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
907 Handle<ConstantPoolArray> array) {
908 CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
912 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
913 Handle<SharedFunctionInfo> function_info,
914 Handle<Map> function_map,
915 PretenureFlag pretenure) {
918 isolate()->heap()->AllocateFunction(*function_map,
920 isolate()->heap()->the_hole_value(),
926 static Handle<Map> MapForNewFunction(Isolate *isolate,
927 Handle<SharedFunctionInfo> function_info) {
928 Context *context = isolate->context()->native_context();
929 int map_index = Context::FunctionMapIndex(function_info->language_mode(),
930 function_info->is_generator());
931 return Handle<Map>(Map::cast(context->get(map_index)));
935 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
936 Handle<SharedFunctionInfo> function_info,
937 Handle<Context> context,
938 PretenureFlag pretenure) {
939 Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
941 MapForNewFunction(isolate(), function_info),
944 if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
945 function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
948 result->set_context(*context);
950 int index = function_info->SearchOptimizedCodeMap(context->native_context(),
952 if (!function_info->bound() && index < 0) {
953 int number_of_literals = function_info->num_literals();
954 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
955 if (number_of_literals > 0) {
956 // Store the native context in the literals array prefix. This
957 // context will be used when creating object, regexp and array
958 // literals in this function.
959 literals->set(JSFunction::kLiteralNativeContextIndex,
960 context->native_context());
962 result->set_literals(*literals);
966 // Caching of optimized code enabled and optimized code found.
967 FixedArray* literals =
968 function_info->GetLiteralsFromOptimizedCodeMap(index);
969 if (literals != NULL) result->set_literals(literals);
970 result->ReplaceCode(function_info->GetCodeFromOptimizedCodeMap(index));
974 if (isolate()->use_crankshaft() &&
976 result->is_compiled() &&
977 !function_info->is_toplevel() &&
978 function_info->allows_lazy_compilation() &&
979 !function_info->optimization_disabled() &&
980 !isolate()->DebuggerHasBreakPoints()) {
981 result->MarkForOptimization();
987 Handle<Object> Factory::NewNumber(double value,
988 PretenureFlag pretenure) {
991 isolate()->heap()->NumberFromDouble(value, pretenure), Object);
995 Handle<Object> Factory::NewNumberFromInt(int32_t value,
996 PretenureFlag pretenure) {
999 isolate()->heap()->NumberFromInt32(value, pretenure), Object);
1003 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1004 PretenureFlag pretenure) {
1007 isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1011 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1012 PretenureFlag pretenure) {
1015 isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1019 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1020 PretenureFlag pretenure) {
1023 isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1027 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1028 PretenureFlag pretenure) {
1031 isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1035 Handle<JSObject> Factory::NewNeanderObject() {
1038 isolate()->heap()->AllocateJSObjectFromMap(
1039 isolate()->heap()->neander_map()),
1044 Handle<Object> Factory::NewTypeError(const char* message,
1045 Vector< Handle<Object> > args) {
1046 return NewError("MakeTypeError", message, args);
1050 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1051 return NewError("$TypeError", message);
1055 Handle<Object> Factory::NewRangeError(const char* message,
1056 Vector< Handle<Object> > args) {
1057 return NewError("MakeRangeError", message, args);
1061 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1062 return NewError("$RangeError", message);
1066 Handle<Object> Factory::NewSyntaxError(const char* message,
1067 Handle<JSArray> args) {
1068 return NewError("MakeSyntaxError", message, args);
1072 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1073 return NewError("$SyntaxError", message);
1077 Handle<Object> Factory::NewReferenceError(const char* message,
1078 Vector< Handle<Object> > args) {
1079 return NewError("MakeReferenceError", message, args);
1083 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1084 return NewError("$ReferenceError", message);
1088 Handle<Object> Factory::NewError(const char* maker,
1089 const char* message,
1090 Vector< Handle<Object> > args) {
1091 // Instantiate a closeable HandleScope for EscapeFrom.
1092 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1093 Handle<FixedArray> array = NewFixedArray(args.length());
1094 for (int i = 0; i < args.length(); i++) {
1095 array->set(i, *args[i]);
1097 Handle<JSArray> object = NewJSArrayWithElements(array);
1098 Handle<Object> result = NewError(maker, message, object);
1099 return result.EscapeFrom(&scope);
1103 Handle<Object> Factory::NewEvalError(const char* message,
1104 Vector< Handle<Object> > args) {
1105 return NewError("MakeEvalError", message, args);
1109 Handle<Object> Factory::NewError(const char* message,
1110 Vector< Handle<Object> > args) {
1111 return NewError("MakeError", message, args);
1115 Handle<String> Factory::EmergencyNewError(const char* message,
1116 Handle<JSArray> args) {
1117 const int kBufferSize = 1000;
1118 char buffer[kBufferSize];
1119 size_t space = kBufferSize;
1120 char* p = &buffer[0];
1122 Vector<char> v(buffer, kBufferSize);
1123 OS::StrNCpy(v, message, space);
1124 space -= Min(space, strlen(message));
1125 p = &buffer[kBufferSize] - space;
1127 for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1132 MaybeObject* maybe_arg = args->GetElement(isolate(), i);
1133 Handle<String> arg_str(reinterpret_cast<String*>(maybe_arg));
1134 SmartArrayPointer<char> arg = arg_str->ToCString();
1135 Vector<char> v2(p, static_cast<int>(space));
1136 OS::StrNCpy(v2, arg.get(), space);
1137 space -= Min(space, strlen(arg.get()));
1138 p = &buffer[kBufferSize] - space;
1145 buffer[kBufferSize - 1] = '\0';
1147 Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
1148 return error_string;
1152 Handle<Object> Factory::NewError(const char* maker,
1153 const char* message,
1154 Handle<JSArray> args) {
1155 Handle<String> make_str = InternalizeUtf8String(maker);
1156 Handle<Object> fun_obj(
1157 isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
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 bool caught_exception;
1171 Handle<Object> result = Execution::TryCall(fun,
1172 isolate()->js_builtins_object(),
1180 Handle<Object> Factory::NewError(Handle<String> message) {
1181 return NewError("$Error", message);
1185 Handle<Object> Factory::NewError(const char* constructor,
1186 Handle<String> message) {
1187 Handle<String> constr = InternalizeUtf8String(constructor);
1188 Handle<JSFunction> fun = Handle<JSFunction>(
1189 JSFunction::cast(isolate()->js_builtins_object()->
1190 GetPropertyNoExceptionThrown(*constr)));
1191 Handle<Object> argv[] = { message };
1193 // Invoke the JavaScript factory method. If an exception is thrown while
1194 // running the factory method, use the exception as the result.
1195 bool caught_exception;
1196 Handle<Object> result = Execution::TryCall(fun,
1197 isolate()->js_builtins_object(),
1205 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1209 bool force_initial_map) {
1210 // Allocate the function
1211 Handle<JSFunction> function = NewFunction(name, the_hole_value());
1213 // Set up the code pointer in both the shared function info and in
1214 // the function itself.
1215 function->shared()->set_code(*code);
1216 function->set_code(*code);
1218 if (force_initial_map ||
1219 type != JS_OBJECT_TYPE ||
1220 instance_size != JSObject::kHeaderSize) {
1221 Handle<Map> initial_map = NewMap(type, instance_size);
1222 Handle<JSObject> prototype = NewFunctionPrototype(function);
1223 initial_map->set_prototype(*prototype);
1224 function->set_initial_map(*initial_map);
1225 initial_map->set_constructor(*function);
1227 ASSERT(!function->has_initial_map());
1228 ASSERT(!function->has_prototype());
1235 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
1238 Handle<JSObject> prototype,
1240 bool force_initial_map) {
1241 // Allocate the function.
1242 Handle<JSFunction> function = NewFunction(name, prototype);
1244 // Set up the code pointer in both the shared function info and in
1245 // the function itself.
1246 function->shared()->set_code(*code);
1247 function->set_code(*code);
1249 if (force_initial_map ||
1250 type != JS_OBJECT_TYPE ||
1251 instance_size != JSObject::kHeaderSize) {
1252 Handle<Map> initial_map = NewMap(type,
1254 GetInitialFastElementsKind());
1255 function->set_initial_map(*initial_map);
1256 initial_map->set_constructor(*function);
1259 JSFunction::SetPrototype(function, prototype);
1264 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1265 Handle<Code> code) {
1266 Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
1268 function->shared()->set_code(*code);
1269 function->set_code(*code);
1270 ASSERT(!function->has_initial_map());
1271 ASSERT(!function->has_prototype());
1276 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1279 isolate()->heap()->AllocateScopeInfo(length),
1284 Handle<JSObject> Factory::NewExternal(void* value) {
1285 CALL_HEAP_FUNCTION(isolate(),
1286 isolate()->heap()->AllocateExternal(value),
1291 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1293 Handle<Object> self_ref,
1296 int prologue_offset) {
1297 CALL_HEAP_FUNCTION(isolate(),
1298 isolate()->heap()->CreateCode(
1299 desc, flags, self_ref, immovable, crankshafted,
1305 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1306 CALL_HEAP_FUNCTION(isolate(),
1307 isolate()->heap()->CopyCode(*code),
1312 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1313 CALL_HEAP_FUNCTION(isolate(),
1314 isolate()->heap()->CopyCode(*code, reloc_info),
1319 Handle<String> Factory::InternalizedStringFromString(Handle<String> value) {
1320 CALL_HEAP_FUNCTION(isolate(),
1321 isolate()->heap()->InternalizeString(*value), String);
1325 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1326 PretenureFlag pretenure) {
1327 JSFunction::EnsureHasInitialMap(constructor);
1330 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1334 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1335 Handle<ScopeInfo> scope_info) {
1338 isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1342 // TODO(mstarzinger): Temporary wrapper until handlified.
1343 static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1345 Handle<Object> value,
1346 PropertyDetails details) {
1347 CALL_HEAP_FUNCTION(dict->GetIsolate(),
1348 dict->Add(*name, *value, details),
1353 static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1355 CALL_HEAP_FUNCTION(isolate,
1356 isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1361 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1362 ASSERT(constructor->has_initial_map());
1363 Handle<Map> map(constructor->initial_map());
1364 ASSERT(map->is_dictionary_map());
1366 // Make sure no field properties are described in the initial map.
1367 // This guarantees us that normalizing the properties does not
1368 // require us to change property values to PropertyCells.
1369 ASSERT(map->NextFreePropertyIndex() == 0);
1371 // Make sure we don't have a ton of pre-allocated slots in the
1372 // global objects. They will be unused once we normalize the object.
1373 ASSERT(map->unused_property_fields() == 0);
1374 ASSERT(map->inobject_properties() == 0);
1376 // Initial size of the backing store to avoid resize of the storage during
1377 // bootstrapping. The size differs between the JS global object ad the
1379 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1381 // Allocate a dictionary object for backing storage.
1382 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1383 Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1385 // The global object might be created from an object template with accessors.
1386 // Fill these accessors into the dictionary.
1387 Handle<DescriptorArray> descs(map->instance_descriptors());
1388 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1389 PropertyDetails details = descs->GetDetails(i);
1390 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
1391 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1392 Handle<Name> name(descs->GetKey(i));
1393 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1394 Handle<PropertyCell> cell = NewPropertyCell(value);
1395 NameDictionaryAdd(dictionary, name, cell, d);
1398 // Allocate the global object and initialize it with the backing store.
1399 Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1400 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1402 // Create a new map for the global object.
1403 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1404 new_map->set_dictionary_map(true);
1406 // Set up the global object as a normalized object.
1407 global->set_map(*new_map);
1408 global->set_properties(*dictionary);
1410 // Make sure result is a global object with properties in dictionary.
1411 ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1416 Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map,
1417 PretenureFlag pretenure,
1421 isolate()->heap()->AllocateJSObjectFromMap(*map, pretenure, alloc_props),
1426 Handle<JSArray> Factory::NewJSArray(int capacity,
1427 ElementsKind elements_kind,
1428 PretenureFlag pretenure) {
1429 if (capacity != 0) {
1430 elements_kind = GetHoleyElementsKind(elements_kind);
1432 CALL_HEAP_FUNCTION(isolate(),
1433 isolate()->heap()->AllocateJSArrayAndStorage(
1437 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1443 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1444 ElementsKind elements_kind,
1445 PretenureFlag pretenure) {
1448 isolate()->heap()->AllocateJSArrayWithElements(*elements,
1456 void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
1459 ElementsAccessor* accessor = array->GetElementsAccessor();
1460 CALL_HEAP_FUNCTION_VOID(
1462 accessor->SetCapacityAndLength(*array, capacity, length));
1466 void Factory::SetContent(Handle<JSArray> array,
1467 Handle<FixedArrayBase> elements) {
1468 CALL_HEAP_FUNCTION_VOID(
1470 array->SetContent(*elements));
1474 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1475 Handle<JSFunction> function) {
1476 ASSERT(function->shared()->is_generator());
1477 JSFunction::EnsureHasInitialMap(function);
1478 Handle<Map> map(function->initial_map());
1479 ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1482 isolate()->heap()->AllocateJSObjectFromMap(*map),
1487 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1488 Handle<JSFunction> array_buffer_fun(
1489 isolate()->context()->native_context()->array_buffer_fun());
1492 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1497 Handle<JSDataView> Factory::NewJSDataView() {
1498 Handle<JSFunction> data_view_fun(
1499 isolate()->context()->native_context()->data_view_fun());
1502 isolate()->heap()->AllocateJSObject(*data_view_fun),
1507 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1509 Context* native_context = isolate->context()->native_context();
1511 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1512 case kExternal##Type##Array: \
1513 return native_context->type##_array_fun();
1515 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1516 #undef TYPED_ARRAY_FUN
1525 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1526 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1530 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1535 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1536 Handle<Object> prototype) {
1539 isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1544 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1545 CALL_HEAP_FUNCTION_VOID(
1547 isolate()->heap()->ReinitializeJSReceiver(
1548 *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1552 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1553 CALL_HEAP_FUNCTION_VOID(
1555 isolate()->heap()->ReinitializeJSReceiver(
1556 *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1560 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1561 Handle<String> name,
1562 int number_of_literals,
1565 Handle<ScopeInfo> scope_info) {
1566 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1567 shared->set_code(*code);
1568 shared->set_scope_info(*scope_info);
1569 int literals_array_size = number_of_literals;
1570 // If the function contains object, regexp or array literals,
1571 // allocate extra space for a literals array prefix containing the
1573 if (number_of_literals > 0) {
1574 literals_array_size += JSFunction::kLiteralsPrefixSize;
1576 shared->set_num_literals(literals_array_size);
1578 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1579 shared->DisableOptimization(kGenerator);
1585 Handle<JSMessageObject> Factory::NewJSMessageObject(
1586 Handle<String> type,
1587 Handle<JSArray> arguments,
1590 Handle<Object> script,
1591 Handle<Object> stack_trace,
1592 Handle<Object> stack_frames) {
1593 CALL_HEAP_FUNCTION(isolate(),
1594 isolate()->heap()->AllocateJSMessageObject(*type,
1605 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1606 CALL_HEAP_FUNCTION(isolate(),
1607 isolate()->heap()->AllocateSharedFunctionInfo(*name),
1608 SharedFunctionInfo);
1612 Handle<String> Factory::NumberToString(Handle<Object> number) {
1613 CALL_HEAP_FUNCTION(isolate(),
1614 isolate()->heap()->NumberToString(*number), String);
1618 Handle<String> Factory::Uint32ToString(uint32_t value) {
1619 CALL_HEAP_FUNCTION(isolate(),
1620 isolate()->heap()->Uint32ToString(value), String);
1624 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1625 Handle<SeededNumberDictionary> dictionary,
1627 Handle<Object> value) {
1628 CALL_HEAP_FUNCTION(isolate(),
1629 dictionary->AtNumberPut(key, *value),
1630 SeededNumberDictionary);
1634 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1635 Handle<UnseededNumberDictionary> dictionary,
1637 Handle<Object> value) {
1638 CALL_HEAP_FUNCTION(isolate(),
1639 dictionary->AtNumberPut(key, *value),
1640 UnseededNumberDictionary);
1644 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1645 Handle<Object> prototype) {
1646 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1649 isolate()->heap()->AllocateFunction(*isolate()->function_map(),
1656 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1657 Handle<Object> prototype) {
1658 Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1659 fun->set_context(isolate()->context()->native_context());
1664 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1665 Handle<String> name,
1666 LanguageMode language_mode) {
1667 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1668 Handle<Map> map = (language_mode == CLASSIC_MODE)
1669 ? isolate()->function_without_prototype_map()
1670 : isolate()->strict_mode_function_without_prototype_map();
1671 CALL_HEAP_FUNCTION(isolate(),
1672 isolate()->heap()->AllocateFunction(
1680 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1681 Handle<String> name,
1682 LanguageMode language_mode) {
1683 Handle<JSFunction> fun =
1684 NewFunctionWithoutPrototypeHelper(name, language_mode);
1685 fun->set_context(isolate()->context()->native_context());
1690 Handle<Object> Factory::ToObject(Handle<Object> object) {
1691 CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1695 Handle<Object> Factory::ToObject(Handle<Object> object,
1696 Handle<Context> native_context) {
1697 CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1701 #ifdef ENABLE_DEBUGGER_SUPPORT
1702 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1703 // Get the original code of the function.
1704 Handle<Code> code(shared->code());
1706 // Create a copy of the code before allocating the debug info object to avoid
1707 // allocation while setting up the debug info object.
1708 Handle<Code> original_code(*Factory::CopyCode(code));
1710 // Allocate initial fixed array for active break points before allocating the
1711 // debug info object to avoid allocation while setting up the debug info
1713 Handle<FixedArray> break_points(
1714 NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1716 // Create and set up the debug info object. Debug info contains function, a
1717 // copy of the original code, the executing code and initial fixed array for
1718 // active break points.
1719 Handle<DebugInfo> debug_info =
1720 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1721 debug_info->set_shared(*shared);
1722 debug_info->set_original_code(*original_code);
1723 debug_info->set_code(*code);
1724 debug_info->set_break_points(*break_points);
1726 // Link debug info to function.
1727 shared->set_debug_info(*debug_info);
1734 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1738 isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1742 Handle<JSFunction> Factory::CreateApiFunction(
1743 Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1744 Handle<Code> code = isolate()->builtins()->HandleApiCall();
1745 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1747 int internal_field_count = 0;
1748 if (!obj->instance_template()->IsUndefined()) {
1749 Handle<ObjectTemplateInfo> instance_template =
1750 Handle<ObjectTemplateInfo>(
1751 ObjectTemplateInfo::cast(obj->instance_template()));
1752 internal_field_count =
1753 Smi::cast(instance_template->internal_field_count())->value();
1756 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1757 // JSObject::GetHeaderSize.
1758 int instance_size = kPointerSize * internal_field_count;
1760 switch (instance_type) {
1761 case JavaScriptObject:
1762 type = JS_OBJECT_TYPE;
1763 instance_size += JSObject::kHeaderSize;
1765 case InnerGlobalObject:
1766 type = JS_GLOBAL_OBJECT_TYPE;
1767 instance_size += JSGlobalObject::kSize;
1769 case OuterGlobalObject:
1770 type = JS_GLOBAL_PROXY_TYPE;
1771 instance_size += JSGlobalProxy::kSize;
1775 type = JS_OBJECT_TYPE; // Keep the compiler happy.
1779 Handle<JSFunction> result =
1780 NewFunction(Factory::empty_string(),
1787 result->shared()->set_length(obj->length());
1790 Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1791 if (class_name->IsString()) {
1792 result->shared()->set_instance_class_name(*class_name);
1793 result->shared()->set_name(*class_name);
1796 Handle<Map> map = Handle<Map>(result->initial_map());
1798 // Mark as undetectable if needed.
1799 if (obj->undetectable()) {
1800 map->set_is_undetectable();
1803 // Mark as hidden for the __proto__ accessor if needed.
1804 if (obj->hidden_prototype()) {
1805 map->set_is_hidden_prototype();
1808 // Mark as needs_access_check if needed.
1809 if (obj->needs_access_check()) {
1810 map->set_is_access_check_needed(true);
1813 // Set interceptor information in the map.
1814 if (!obj->named_property_handler()->IsUndefined()) {
1815 map->set_has_named_interceptor();
1817 if (!obj->indexed_property_handler()->IsUndefined()) {
1818 map->set_has_indexed_interceptor();
1821 // Set instance call-as-function information in the map.
1822 if (!obj->instance_call_handler()->IsUndefined()) {
1823 map->set_has_instance_call_handler();
1826 result->shared()->set_function_data(*obj);
1827 result->shared()->set_construct_stub(*construct_stub);
1828 result->shared()->DontAdaptArguments();
1830 // Recursively copy parent instance templates' accessors,
1831 // 'data' may be modified.
1832 int max_number_of_additional_properties = 0;
1833 int max_number_of_static_properties = 0;
1834 FunctionTemplateInfo* info = *obj;
1836 if (!info->instance_template()->IsUndefined()) {
1838 ObjectTemplateInfo::cast(
1839 info->instance_template())->property_accessors();
1840 if (!props->IsUndefined()) {
1841 Handle<Object> props_handle(props, isolate());
1842 NeanderArray props_array(props_handle);
1843 max_number_of_additional_properties += props_array.length();
1846 if (!info->property_accessors()->IsUndefined()) {
1847 Object* props = info->property_accessors();
1848 if (!props->IsUndefined()) {
1849 Handle<Object> props_handle(props, isolate());
1850 NeanderArray props_array(props_handle);
1851 max_number_of_static_properties += props_array.length();
1854 Object* parent = info->parent_template();
1855 if (parent->IsUndefined()) break;
1856 info = FunctionTemplateInfo::cast(parent);
1859 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1861 // Use a temporary FixedArray to acculumate static accessors
1862 int valid_descriptors = 0;
1863 Handle<FixedArray> array;
1864 if (max_number_of_static_properties > 0) {
1865 array = NewFixedArray(max_number_of_static_properties);
1869 // Install instance descriptors
1870 if (!obj->instance_template()->IsUndefined()) {
1871 Handle<ObjectTemplateInfo> instance =
1872 Handle<ObjectTemplateInfo>(
1873 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1874 Handle<Object> props = Handle<Object>(instance->property_accessors(),
1876 if (!props->IsUndefined()) {
1877 Map::AppendCallbackDescriptors(map, props);
1880 // Accumulate static accessors
1881 if (!obj->property_accessors()->IsUndefined()) {
1882 Handle<Object> props = Handle<Object>(obj->property_accessors(),
1885 AccessorInfo::AppendUnique(props, array, valid_descriptors);
1887 // Climb parent chain
1888 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1889 if (parent->IsUndefined()) break;
1890 obj = Handle<FunctionTemplateInfo>::cast(parent);
1893 // Install accumulated static accessors
1894 for (int i = 0; i < valid_descriptors; i++) {
1895 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1896 JSObject::SetAccessor(result, accessor);
1899 ASSERT(result->shared()->IsApiFunction());
1904 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1905 CALL_HEAP_FUNCTION(isolate(),
1906 MapCache::Allocate(isolate()->heap(),
1907 at_least_space_for),
1912 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1916 { MaybeObject* maybe_result =
1917 MapCache::cast(context->map_cache())->Put(keys, map);
1918 if (!maybe_result->ToObject(&result)) return maybe_result;
1920 context->set_map_cache(MapCache::cast(result));
1925 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1926 Handle<FixedArray> keys,
1928 CALL_HEAP_FUNCTION(isolate(),
1929 UpdateMapCacheWith(*context, *keys, *map), MapCache);
1933 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1934 Handle<FixedArray> keys) {
1935 if (context->map_cache()->IsUndefined()) {
1936 // Allocate the new map cache for the native context.
1937 Handle<MapCache> new_cache = NewMapCache(24);
1938 context->set_map_cache(*new_cache);
1940 // Check to see whether there is a matching element in the cache.
1941 Handle<MapCache> cache =
1942 Handle<MapCache>(MapCache::cast(context->map_cache()));
1943 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1944 if (result->IsMap()) return Handle<Map>::cast(result);
1945 // Create a new map and add it to the cache.
1947 CopyMap(Handle<Map>(context->object_function()->initial_map()),
1949 AddToMapCache(context, keys, map);
1950 return Handle<Map>(map);
1954 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1955 JSRegExp::Type type,
1956 Handle<String> source,
1957 JSRegExp::Flags flags,
1958 Handle<Object> data) {
1959 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1961 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1962 store->set(JSRegExp::kSourceIndex, *source);
1963 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1964 store->set(JSRegExp::kAtomPatternIndex, *data);
1965 regexp->set_data(*store);
1968 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1969 JSRegExp::Type type,
1970 Handle<String> source,
1971 JSRegExp::Flags flags,
1972 int capture_count) {
1973 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1974 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1975 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1976 store->set(JSRegExp::kSourceIndex, *source);
1977 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1978 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1979 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1980 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1981 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1982 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1983 store->set(JSRegExp::kIrregexpCaptureCountIndex,
1984 Smi::FromInt(capture_count));
1985 regexp->set_data(*store);
1990 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1991 Handle<JSObject> instance,
1992 bool* pending_exception) {
1993 // Configure the instance by adding the properties specified by the
1994 // instance template.
1995 Handle<Object> instance_template(desc->instance_template(), isolate());
1996 if (!instance_template->IsUndefined()) {
1997 Execution::ConfigureInstance(isolate(),
2002 *pending_exception = false;
2007 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2008 Heap* h = isolate()->heap();
2009 if (name->Equals(h->undefined_string())) return undefined_value();
2010 if (name->Equals(h->nan_string())) return nan_value();
2011 if (name->Equals(h->infinity_string())) return infinity_value();
2012 return Handle<Object>::null();
2016 Handle<Object> Factory::ToBoolean(bool value) {
2017 return value ? true_value() : false_value();
2021 } } // namespace v8::internal