deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / factory.cc
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.
4
5 #include "src/factory.h"
6
7 #include "src/allocation-site-scopes.h"
8 #include "src/base/bits.h"
9 #include "src/conversions.h"
10 #include "src/isolate-inl.h"
11 #include "src/macro-assembler.h"
12
13 namespace v8 {
14 namespace internal {
15
16
17 template<typename T>
18 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
19   CALL_HEAP_FUNCTION(
20       isolate(),
21       isolate()->heap()->Allocate(*map, space),
22       T);
23 }
24
25
26 template<typename T>
27 Handle<T> Factory::New(Handle<Map> map,
28                        AllocationSpace space,
29                        Handle<AllocationSite> allocation_site) {
30   CALL_HEAP_FUNCTION(
31       isolate(),
32       isolate()->heap()->Allocate(*map, space, *allocation_site),
33       T);
34 }
35
36
37 Handle<HeapObject> Factory::NewFillerObject(int size,
38                                             bool double_align,
39                                             AllocationSpace space) {
40   CALL_HEAP_FUNCTION(
41       isolate(),
42       isolate()->heap()->AllocateFillerObject(size, double_align, space),
43       HeapObject);
44 }
45
46
47 Handle<Box> Factory::NewBox(Handle<Object> value) {
48   Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
49   result->set_value(*value);
50   return result;
51 }
52
53
54 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
55                                     const char* to_string,
56                                     Handle<Object> to_number,
57                                     byte kind) {
58   Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
59   Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
60   return oddball;
61 }
62
63
64 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
65   DCHECK(0 <= size);
66   CALL_HEAP_FUNCTION(
67       isolate(),
68       isolate()->heap()->AllocateFixedArray(size, pretenure),
69       FixedArray);
70 }
71
72
73 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
74                                                    PretenureFlag pretenure) {
75   DCHECK(0 <= size);
76   CALL_HEAP_FUNCTION(
77       isolate(),
78       isolate()->heap()->AllocateFixedArrayWithFiller(size,
79                                                       pretenure,
80                                                       *the_hole_value()),
81       FixedArray);
82 }
83
84
85 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
86   CALL_HEAP_FUNCTION(
87       isolate(),
88       isolate()->heap()->AllocateUninitializedFixedArray(size),
89       FixedArray);
90 }
91
92
93 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
94                                                     PretenureFlag pretenure) {
95   DCHECK(0 <= size);
96   CALL_HEAP_FUNCTION(
97       isolate(),
98       isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
99       FixedArrayBase);
100 }
101
102
103 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
104     int size,
105     PretenureFlag pretenure) {
106   DCHECK(0 <= size);
107   Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
108   if (size > 0) {
109     Handle<FixedDoubleArray> double_array =
110         Handle<FixedDoubleArray>::cast(array);
111     for (int i = 0; i < size; ++i) {
112       double_array->set_the_hole(i);
113     }
114   }
115   return array;
116 }
117
118
119 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
120     const ConstantPoolArray::NumberOfEntries& small) {
121   DCHECK(small.total_count() > 0);
122   CALL_HEAP_FUNCTION(
123       isolate(),
124       isolate()->heap()->AllocateConstantPoolArray(small),
125       ConstantPoolArray);
126 }
127
128
129 Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
130     const ConstantPoolArray::NumberOfEntries& small,
131     const ConstantPoolArray::NumberOfEntries& extended) {
132   DCHECK(small.total_count() > 0);
133   DCHECK(extended.total_count() > 0);
134   CALL_HEAP_FUNCTION(
135       isolate(),
136       isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
137       ConstantPoolArray);
138 }
139
140
141 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
142   return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kMinCapacity);
143 }
144
145
146 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
147   return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
148 }
149
150
151 Handle<AccessorPair> Factory::NewAccessorPair() {
152   Handle<AccessorPair> accessors =
153       Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
154   accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
155   accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
156   return accessors;
157 }
158
159
160 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
161   Handle<TypeFeedbackInfo> info =
162       Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
163   info->initialize_storage();
164   return info;
165 }
166
167
168 // Internalized strings are created in the old generation (data space).
169 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
170   Utf8StringKey key(string, isolate()->heap()->HashSeed());
171   return InternalizeStringWithKey(&key);
172 }
173
174
175 // Internalized strings are created in the old generation (data space).
176 Handle<String> Factory::InternalizeString(Handle<String> string) {
177   if (string->IsInternalizedString()) return string;
178   return StringTable::LookupString(isolate(), string);
179 }
180
181
182 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
183   OneByteStringKey key(string, isolate()->heap()->HashSeed());
184   return InternalizeStringWithKey(&key);
185 }
186
187
188 Handle<String> Factory::InternalizeOneByteString(
189     Handle<SeqOneByteString> string, int from, int length) {
190   SeqOneByteSubStringKey key(string, from, length);
191   return InternalizeStringWithKey(&key);
192 }
193
194
195 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
196   TwoByteStringKey key(string, isolate()->heap()->HashSeed());
197   return InternalizeStringWithKey(&key);
198 }
199
200
201 template<class StringTableKey>
202 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
203   return StringTable::LookupKey(isolate(), key);
204 }
205
206
207 MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
208                                                   PretenureFlag pretenure) {
209   int length = string.length();
210   if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
211   Handle<SeqOneByteString> result;
212   ASSIGN_RETURN_ON_EXCEPTION(
213       isolate(),
214       result,
215       NewRawOneByteString(string.length(), pretenure),
216       String);
217
218   DisallowHeapAllocation no_gc;
219   // Copy the characters into the new object.
220   CopyChars(SeqOneByteString::cast(*result)->GetChars(),
221             string.start(),
222             length);
223   return result;
224 }
225
226 MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
227                                                PretenureFlag pretenure) {
228   // Check for ASCII first since this is the common case.
229   const char* start = string.start();
230   int length = string.length();
231   int non_ascii_start = String::NonAsciiStart(start, length);
232   if (non_ascii_start >= length) {
233     // If the string is ASCII, we do not need to convert the characters
234     // since UTF8 is backwards compatible with ASCII.
235     return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
236   }
237
238   // Non-ASCII and we need to decode.
239   Access<UnicodeCache::Utf8Decoder>
240       decoder(isolate()->unicode_cache()->utf8_decoder());
241   decoder->Reset(string.start() + non_ascii_start,
242                  length - non_ascii_start);
243   int utf16_length = static_cast<int>(decoder->Utf16Length());
244   DCHECK(utf16_length > 0);
245   // Allocate string.
246   Handle<SeqTwoByteString> result;
247   ASSIGN_RETURN_ON_EXCEPTION(
248       isolate(), result,
249       NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
250       String);
251   // Copy ASCII portion.
252   uint16_t* data = result->GetChars();
253   const char* ascii_data = string.start();
254   for (int i = 0; i < non_ascii_start; i++) {
255     *data++ = *ascii_data++;
256   }
257   // Now write the remainder.
258   decoder->WriteUtf16(data, utf16_length);
259   return result;
260 }
261
262
263 MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
264                                                   PretenureFlag pretenure) {
265   int length = string.length();
266   const uc16* start = string.start();
267   if (String::IsOneByte(start, length)) {
268     if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
269     Handle<SeqOneByteString> result;
270     ASSIGN_RETURN_ON_EXCEPTION(
271         isolate(),
272         result,
273         NewRawOneByteString(length, pretenure),
274         String);
275     CopyChars(result->GetChars(), start, length);
276     return result;
277   } else {
278     Handle<SeqTwoByteString> result;
279     ASSIGN_RETURN_ON_EXCEPTION(
280         isolate(),
281         result,
282         NewRawTwoByteString(length, pretenure),
283         String);
284     CopyChars(result->GetChars(), start, length);
285     return result;
286   }
287 }
288
289
290 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
291                                                       int chars,
292                                                       uint32_t hash_field) {
293   CALL_HEAP_FUNCTION(
294       isolate(),
295       isolate()->heap()->AllocateInternalizedStringFromUtf8(
296           str, chars, hash_field),
297       String);
298 }
299
300
301 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
302       Vector<const uint8_t> str,
303       uint32_t hash_field) {
304   CALL_HEAP_FUNCTION(
305       isolate(),
306       isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
307       String);
308 }
309
310
311 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
312     Handle<SeqOneByteString> string, int offset, int length,
313     uint32_t hash_field) {
314   CALL_HEAP_FUNCTION(
315       isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
316                      Vector<const uint8_t>(string->GetChars() + offset, length),
317                      hash_field),
318       String);
319 }
320
321
322 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
323       Vector<const uc16> str,
324       uint32_t hash_field) {
325   CALL_HEAP_FUNCTION(
326       isolate(),
327       isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
328       String);
329 }
330
331
332 Handle<String> Factory::NewInternalizedStringImpl(
333     Handle<String> string, int chars, uint32_t hash_field) {
334   CALL_HEAP_FUNCTION(
335       isolate(),
336       isolate()->heap()->AllocateInternalizedStringImpl(
337           *string, chars, hash_field),
338       String);
339 }
340
341
342 MaybeHandle<Map> Factory::InternalizedStringMapForString(
343     Handle<String> string) {
344   // If the string is in new space it cannot be used as internalized.
345   if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
346
347   // Find the corresponding internalized string map for strings.
348   switch (string->map()->instance_type()) {
349     case STRING_TYPE: return internalized_string_map();
350     case ONE_BYTE_STRING_TYPE:
351       return one_byte_internalized_string_map();
352     case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
353     case EXTERNAL_ONE_BYTE_STRING_TYPE:
354       return external_one_byte_internalized_string_map();
355     case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
356       return external_internalized_string_with_one_byte_data_map();
357     case SHORT_EXTERNAL_STRING_TYPE:
358       return short_external_internalized_string_map();
359     case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
360       return short_external_one_byte_internalized_string_map();
361     case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
362       return short_external_internalized_string_with_one_byte_data_map();
363     default: return MaybeHandle<Map>();  // No match found.
364   }
365 }
366
367
368 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
369     int length, PretenureFlag pretenure) {
370   if (length > String::kMaxLength || length < 0) {
371     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
372   }
373   CALL_HEAP_FUNCTION(
374       isolate(),
375       isolate()->heap()->AllocateRawOneByteString(length, pretenure),
376       SeqOneByteString);
377 }
378
379
380 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
381     int length, PretenureFlag pretenure) {
382   if (length > String::kMaxLength || length < 0) {
383     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
384   }
385   CALL_HEAP_FUNCTION(
386       isolate(),
387       isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
388       SeqTwoByteString);
389 }
390
391
392 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
393   if (code <= String::kMaxOneByteCharCodeU) {
394     {
395       DisallowHeapAllocation no_allocation;
396       Object* value = single_character_string_cache()->get(code);
397       if (value != *undefined_value()) {
398         return handle(String::cast(value), isolate());
399       }
400     }
401     uint8_t buffer[1];
402     buffer[0] = static_cast<uint8_t>(code);
403     Handle<String> result =
404         InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
405     single_character_string_cache()->set(code, *result);
406     return result;
407   }
408   DCHECK(code <= String::kMaxUtf16CodeUnitU);
409
410   Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
411   result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
412   return result;
413 }
414
415
416 // Returns true for a character in a range.  Both limits are inclusive.
417 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
418   // This makes uses of the the unsigned wraparound.
419   return character - from <= to - from;
420 }
421
422
423 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
424                                                           uint16_t c1,
425                                                           uint16_t c2) {
426   // Numeric strings have a different hash algorithm not known by
427   // LookupTwoCharsStringIfExists, so we skip this step for such strings.
428   if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
429     Handle<String> result;
430     if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
431         ToHandle(&result)) {
432       return result;
433     }
434   }
435
436   // Now we know the length is 2, we might as well make use of that fact
437   // when building the new string.
438   if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
439     // We can do this.
440     DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
441                                       1));  // because of this.
442     Handle<SeqOneByteString> str =
443         isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
444     uint8_t* dest = str->GetChars();
445     dest[0] = static_cast<uint8_t>(c1);
446     dest[1] = static_cast<uint8_t>(c2);
447     return str;
448   } else {
449     Handle<SeqTwoByteString> str =
450         isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
451     uc16* dest = str->GetChars();
452     dest[0] = c1;
453     dest[1] = c2;
454     return str;
455   }
456 }
457
458
459 template<typename SinkChar, typename StringType>
460 Handle<String> ConcatStringContent(Handle<StringType> result,
461                                    Handle<String> first,
462                                    Handle<String> second) {
463   DisallowHeapAllocation pointer_stays_valid;
464   SinkChar* sink = result->GetChars();
465   String::WriteToFlat(*first, sink, 0, first->length());
466   String::WriteToFlat(*second, sink + first->length(), 0, second->length());
467   return result;
468 }
469
470
471 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
472                                            Handle<String> right) {
473   int left_length = left->length();
474   if (left_length == 0) return right;
475   int right_length = right->length();
476   if (right_length == 0) return left;
477
478   int length = left_length + right_length;
479
480   if (length == 2) {
481     uint16_t c1 = left->Get(0);
482     uint16_t c2 = right->Get(0);
483     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
484   }
485
486   // Make sure that an out of memory exception is thrown if the length
487   // of the new cons string is too large.
488   if (length > String::kMaxLength || length < 0) {
489     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
490   }
491
492   bool left_is_one_byte = left->IsOneByteRepresentation();
493   bool right_is_one_byte = right->IsOneByteRepresentation();
494   bool is_one_byte = left_is_one_byte && right_is_one_byte;
495   bool is_one_byte_data_in_two_byte_string = false;
496   if (!is_one_byte) {
497     // At least one of the strings uses two-byte representation so we
498     // can't use the fast case code for short one-byte strings below, but
499     // we can try to save memory if all chars actually fit in one-byte.
500     is_one_byte_data_in_two_byte_string =
501         left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
502     if (is_one_byte_data_in_two_byte_string) {
503       isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
504     }
505   }
506
507   // If the resulting string is small make a flat string.
508   if (length < ConsString::kMinLength) {
509     // Note that neither of the two inputs can be a slice because:
510     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
511     DCHECK(left->IsFlat());
512     DCHECK(right->IsFlat());
513
514     STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
515     if (is_one_byte) {
516       Handle<SeqOneByteString> result =
517           NewRawOneByteString(length).ToHandleChecked();
518       DisallowHeapAllocation no_gc;
519       uint8_t* dest = result->GetChars();
520       // Copy left part.
521       const uint8_t* src =
522           left->IsExternalString()
523               ? Handle<ExternalOneByteString>::cast(left)->GetChars()
524               : Handle<SeqOneByteString>::cast(left)->GetChars();
525       for (int i = 0; i < left_length; i++) *dest++ = src[i];
526       // Copy right part.
527       src = right->IsExternalString()
528                 ? Handle<ExternalOneByteString>::cast(right)->GetChars()
529                 : Handle<SeqOneByteString>::cast(right)->GetChars();
530       for (int i = 0; i < right_length; i++) *dest++ = src[i];
531       return result;
532     }
533
534     return (is_one_byte_data_in_two_byte_string)
535         ? ConcatStringContent<uint8_t>(
536             NewRawOneByteString(length).ToHandleChecked(), left, right)
537         : ConcatStringContent<uc16>(
538             NewRawTwoByteString(length).ToHandleChecked(), left, right);
539   }
540
541   return (is_one_byte || is_one_byte_data_in_two_byte_string)
542              ? NewOneByteConsString(length, left, right)
543              : NewTwoByteConsString(length, left, right);
544 }
545
546
547 MaybeHandle<String> Factory::NewOneByteConsString(int length,
548                                                   Handle<String> left,
549                                                   Handle<String> right) {
550   return NewRawConsString(cons_one_byte_string_map(), length, left, right);
551 }
552
553
554 MaybeHandle<String> Factory::NewTwoByteConsString(int length,
555                                                   Handle<String> left,
556                                                   Handle<String> right) {
557   return NewRawConsString(cons_string_map(), length, left, right);
558 }
559
560
561 MaybeHandle<String> Factory::NewRawConsString(Handle<Map> map, int length,
562                                               Handle<String> left,
563                                               Handle<String> right) {
564   Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
565
566   DisallowHeapAllocation no_gc;
567   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
568
569   result->set_hash_field(String::kEmptyHashField);
570   result->set_length(length);
571   result->set_first(*left, mode);
572   result->set_second(*right, mode);
573   return result;
574 }
575
576
577 Handle<String> Factory::NewProperSubString(Handle<String> str,
578                                            int begin,
579                                            int end) {
580 #if VERIFY_HEAP
581   if (FLAG_verify_heap) str->StringVerify();
582 #endif
583   DCHECK(begin > 0 || end < str->length());
584
585   str = String::Flatten(str);
586
587   int length = end - begin;
588   if (length <= 0) return empty_string();
589   if (length == 1) {
590     return LookupSingleCharacterStringFromCode(str->Get(begin));
591   }
592   if (length == 2) {
593     // Optimization for 2-byte strings often used as keys in a decompression
594     // dictionary.  Check whether we already have the string in the string
595     // table to prevent creation of many unnecessary strings.
596     uint16_t c1 = str->Get(begin);
597     uint16_t c2 = str->Get(begin + 1);
598     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
599   }
600
601   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
602     if (str->IsOneByteRepresentation()) {
603       Handle<SeqOneByteString> result =
604           NewRawOneByteString(length).ToHandleChecked();
605       uint8_t* dest = result->GetChars();
606       DisallowHeapAllocation no_gc;
607       String::WriteToFlat(*str, dest, begin, end);
608       return result;
609     } else {
610       Handle<SeqTwoByteString> result =
611           NewRawTwoByteString(length).ToHandleChecked();
612       uc16* dest = result->GetChars();
613       DisallowHeapAllocation no_gc;
614       String::WriteToFlat(*str, dest, begin, end);
615       return result;
616     }
617   }
618
619   int offset = begin;
620
621   if (str->IsSlicedString()) {
622     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
623     str = Handle<String>(slice->parent(), isolate());
624     offset += slice->offset();
625   }
626
627   DCHECK(str->IsSeqString() || str->IsExternalString());
628   Handle<Map> map = str->IsOneByteRepresentation()
629                         ? sliced_one_byte_string_map()
630                         : sliced_string_map();
631   Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
632
633   slice->set_hash_field(String::kEmptyHashField);
634   slice->set_length(length);
635   slice->set_parent(*str);
636   slice->set_offset(offset);
637   return slice;
638 }
639
640
641 MaybeHandle<String> Factory::NewExternalStringFromOneByte(
642     const ExternalOneByteString::Resource* resource) {
643   size_t length = resource->length();
644   if (length > static_cast<size_t>(String::kMaxLength)) {
645     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
646   }
647
648   Handle<Map> map = external_one_byte_string_map();
649   Handle<ExternalOneByteString> external_string =
650       New<ExternalOneByteString>(map, NEW_SPACE);
651   external_string->set_length(static_cast<int>(length));
652   external_string->set_hash_field(String::kEmptyHashField);
653   external_string->set_resource(resource);
654
655   return external_string;
656 }
657
658
659 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
660     const ExternalTwoByteString::Resource* resource) {
661   size_t length = resource->length();
662   if (length > static_cast<size_t>(String::kMaxLength)) {
663     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
664   }
665
666   // For small strings we check whether the resource contains only
667   // one byte characters.  If yes, we use a different string map.
668   static const size_t kOneByteCheckLengthLimit = 32;
669   bool is_one_byte = length <= kOneByteCheckLengthLimit &&
670       String::IsOneByte(resource->data(), static_cast<int>(length));
671   Handle<Map> map = is_one_byte ?
672       external_string_with_one_byte_data_map() : external_string_map();
673   Handle<ExternalTwoByteString> external_string =
674       New<ExternalTwoByteString>(map, NEW_SPACE);
675   external_string->set_length(static_cast<int>(length));
676   external_string->set_hash_field(String::kEmptyHashField);
677   external_string->set_resource(resource);
678
679   return external_string;
680 }
681
682
683 Handle<Symbol> Factory::NewSymbol() {
684   CALL_HEAP_FUNCTION(
685       isolate(),
686       isolate()->heap()->AllocateSymbol(),
687       Symbol);
688 }
689
690
691 Handle<Symbol> Factory::NewPrivateSymbol() {
692   Handle<Symbol> symbol = NewSymbol();
693   symbol->set_is_private(true);
694   return symbol;
695 }
696
697
698 Handle<Symbol> Factory::NewPrivateOwnSymbol() {
699   Handle<Symbol> symbol = NewSymbol();
700   symbol->set_is_private(true);
701   symbol->set_is_own(true);
702   return symbol;
703 }
704
705
706 Handle<Context> Factory::NewNativeContext() {
707   Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
708   array->set_map_no_write_barrier(*native_context_map());
709   Handle<Context> context = Handle<Context>::cast(array);
710   context->set_js_array_maps(*undefined_value());
711   DCHECK(context->IsNativeContext());
712   return context;
713 }
714
715
716 Handle<Context> Factory::NewScriptContext(Handle<JSFunction> function,
717                                           Handle<ScopeInfo> scope_info) {
718   Handle<FixedArray> array =
719       NewFixedArray(scope_info->ContextLength(), TENURED);
720   array->set_map_no_write_barrier(*script_context_map());
721   Handle<Context> context = Handle<Context>::cast(array);
722   context->set_closure(*function);
723   context->set_previous(function->context());
724   context->set_extension(*scope_info);
725   context->set_global_object(function->context()->global_object());
726   DCHECK(context->IsScriptContext());
727   return context;
728 }
729
730
731 Handle<ScriptContextTable> Factory::NewScriptContextTable() {
732   Handle<FixedArray> array = NewFixedArray(1);
733   array->set_map_no_write_barrier(*script_context_table_map());
734   Handle<ScriptContextTable> context_table =
735       Handle<ScriptContextTable>::cast(array);
736   context_table->set_used(0);
737   return context_table;
738 }
739
740
741 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
742   Handle<FixedArray> array =
743       NewFixedArray(scope_info->ContextLength(), TENURED);
744   array->set_map_no_write_barrier(*module_context_map());
745   // Instance link will be set later.
746   Handle<Context> context = Handle<Context>::cast(array);
747   context->set_extension(Smi::FromInt(0));
748   return context;
749 }
750
751
752 Handle<Context> Factory::NewFunctionContext(int length,
753                                             Handle<JSFunction> function) {
754   DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
755   Handle<FixedArray> array = NewFixedArray(length);
756   array->set_map_no_write_barrier(*function_context_map());
757   Handle<Context> context = Handle<Context>::cast(array);
758   context->set_closure(*function);
759   context->set_previous(function->context());
760   context->set_extension(Smi::FromInt(0));
761   context->set_global_object(function->context()->global_object());
762   return context;
763 }
764
765
766 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
767                                          Handle<Context> previous,
768                                          Handle<String> name,
769                                          Handle<Object> thrown_object) {
770   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
771   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
772   array->set_map_no_write_barrier(*catch_context_map());
773   Handle<Context> context = Handle<Context>::cast(array);
774   context->set_closure(*function);
775   context->set_previous(*previous);
776   context->set_extension(*name);
777   context->set_global_object(previous->global_object());
778   context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
779   return context;
780 }
781
782
783 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
784                                         Handle<Context> previous,
785                                         Handle<JSReceiver> extension) {
786   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
787   array->set_map_no_write_barrier(*with_context_map());
788   Handle<Context> context = Handle<Context>::cast(array);
789   context->set_closure(*function);
790   context->set_previous(*previous);
791   context->set_extension(*extension);
792   context->set_global_object(previous->global_object());
793   return context;
794 }
795
796
797 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
798                                          Handle<Context> previous,
799                                          Handle<ScopeInfo> scope_info) {
800   Handle<FixedArray> array =
801       NewFixedArrayWithHoles(scope_info->ContextLength());
802   array->set_map_no_write_barrier(*block_context_map());
803   Handle<Context> context = Handle<Context>::cast(array);
804   context->set_closure(*function);
805   context->set_previous(*previous);
806   context->set_extension(*scope_info);
807   context->set_global_object(previous->global_object());
808   return context;
809 }
810
811
812 Handle<Struct> Factory::NewStruct(InstanceType type) {
813   CALL_HEAP_FUNCTION(
814       isolate(),
815       isolate()->heap()->AllocateStruct(type),
816       Struct);
817 }
818
819
820 Handle<CodeCache> Factory::NewCodeCache() {
821   Handle<CodeCache> code_cache =
822       Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
823   code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
824   code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
825   return code_cache;
826 }
827
828
829 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
830     int aliased_context_slot) {
831   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
832       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
833   entry->set_aliased_context_slot(aliased_context_slot);
834   return entry;
835 }
836
837
838 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
839   Handle<ExecutableAccessorInfo> info =
840       Handle<ExecutableAccessorInfo>::cast(
841           NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
842   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
843   return info;
844 }
845
846
847 Handle<Script> Factory::NewScript(Handle<String> source) {
848   // Create and initialize script object.
849   Heap* heap = isolate()->heap();
850   Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
851   script->set_source(*source);
852   script->set_name(heap->undefined_value());
853   script->set_id(isolate()->heap()->NextScriptId());
854   script->set_line_offset(Smi::FromInt(0));
855   script->set_column_offset(Smi::FromInt(0));
856   script->set_context_data(heap->undefined_value());
857   script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
858   script->set_wrapper(heap->undefined_value());
859   script->set_line_ends(heap->undefined_value());
860   script->set_eval_from_shared(heap->undefined_value());
861   script->set_eval_from_instructions_offset(Smi::FromInt(0));
862   script->set_flags(Smi::FromInt(0));
863
864   return script;
865 }
866
867
868 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
869   CALL_HEAP_FUNCTION(isolate(),
870                      isolate()->heap()->AllocateForeign(addr, pretenure),
871                      Foreign);
872 }
873
874
875 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
876   return NewForeign((Address) desc, TENURED);
877 }
878
879
880 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
881   DCHECK(0 <= length);
882   CALL_HEAP_FUNCTION(
883       isolate(),
884       isolate()->heap()->AllocateByteArray(length, pretenure),
885       ByteArray);
886 }
887
888
889 Handle<ExternalArray> Factory::NewExternalArray(int length,
890                                                 ExternalArrayType array_type,
891                                                 void* external_pointer,
892                                                 PretenureFlag pretenure) {
893   DCHECK(0 <= length && length <= Smi::kMaxValue);
894   CALL_HEAP_FUNCTION(
895       isolate(),
896       isolate()->heap()->AllocateExternalArray(length,
897                                                array_type,
898                                                external_pointer,
899                                                pretenure),
900       ExternalArray);
901 }
902
903
904 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
905     int length,
906     ExternalArrayType array_type,
907     PretenureFlag pretenure) {
908   DCHECK(0 <= length && length <= Smi::kMaxValue);
909   CALL_HEAP_FUNCTION(
910       isolate(),
911       isolate()->heap()->AllocateFixedTypedArray(length,
912                                                  array_type,
913                                                  pretenure),
914       FixedTypedArrayBase);
915 }
916
917
918 Handle<Cell> Factory::NewCell(Handle<Object> value) {
919   AllowDeferredHandleDereference convert_to_cell;
920   CALL_HEAP_FUNCTION(
921       isolate(),
922       isolate()->heap()->AllocateCell(*value),
923       Cell);
924 }
925
926
927 Handle<PropertyCell> Factory::NewPropertyCell() {
928   CALL_HEAP_FUNCTION(
929       isolate(),
930       isolate()->heap()->AllocatePropertyCell(),
931       PropertyCell);
932 }
933
934
935 Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
936   AllowDeferredHandleDereference convert_to_cell;
937   CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
938                      WeakCell);
939 }
940
941
942 Handle<AllocationSite> Factory::NewAllocationSite() {
943   Handle<Map> map = allocation_site_map();
944   Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
945   site->Initialize();
946
947   // Link the site
948   site->set_weak_next(isolate()->heap()->allocation_sites_list());
949   isolate()->heap()->set_allocation_sites_list(*site);
950   return site;
951 }
952
953
954 Handle<Map> Factory::NewMap(InstanceType type,
955                             int instance_size,
956                             ElementsKind elements_kind) {
957   CALL_HEAP_FUNCTION(
958       isolate(),
959       isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
960       Map);
961 }
962
963
964 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
965   CALL_HEAP_FUNCTION(isolate(),
966                      isolate()->heap()->CopyJSObject(*object, NULL),
967                      JSObject);
968 }
969
970
971 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
972     Handle<JSObject> object,
973     Handle<AllocationSite> site) {
974   CALL_HEAP_FUNCTION(isolate(),
975                      isolate()->heap()->CopyJSObject(
976                          *object,
977                          site.is_null() ? NULL : *site),
978                      JSObject);
979 }
980
981
982 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
983                                                   Handle<Map> map) {
984   CALL_HEAP_FUNCTION(isolate(),
985                      isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
986                      FixedArray);
987 }
988
989
990 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
991   CALL_HEAP_FUNCTION(isolate(),
992                      isolate()->heap()->CopyFixedArray(*array),
993                      FixedArray);
994 }
995
996
997 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
998     Handle<FixedArray> array) {
999   DCHECK(isolate()->heap()->InNewSpace(*array));
1000   CALL_HEAP_FUNCTION(isolate(),
1001                      isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
1002                      FixedArray);
1003 }
1004
1005
1006 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1007     Handle<FixedDoubleArray> array) {
1008   CALL_HEAP_FUNCTION(isolate(),
1009                      isolate()->heap()->CopyFixedDoubleArray(*array),
1010                      FixedDoubleArray);
1011 }
1012
1013
1014 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1015     Handle<ConstantPoolArray> array) {
1016   CALL_HEAP_FUNCTION(isolate(),
1017                      isolate()->heap()->CopyConstantPoolArray(*array),
1018                      ConstantPoolArray);
1019 }
1020
1021
1022 Handle<Object> Factory::NewNumber(double value,
1023                                   PretenureFlag pretenure) {
1024   // We need to distinguish the minus zero value and this cannot be
1025   // done after conversion to int. Doing this by comparing bit
1026   // patterns is faster than using fpclassify() et al.
1027   if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1028
1029   int int_value = FastD2IChecked(value);
1030   if (value == int_value && Smi::IsValid(int_value)) {
1031     return handle(Smi::FromInt(int_value), isolate());
1032   }
1033
1034   // Materialize the value in the heap.
1035   return NewHeapNumber(value, IMMUTABLE, pretenure);
1036 }
1037
1038
1039 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1040                                          PretenureFlag pretenure) {
1041   if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1042   // Bypass NewNumber to avoid various redundant checks.
1043   return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1044 }
1045
1046
1047 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1048                                           PretenureFlag pretenure) {
1049   int32_t int32v = static_cast<int32_t>(value);
1050   if (int32v >= 0 && Smi::IsValid(int32v)) {
1051     return handle(Smi::FromInt(int32v), isolate());
1052   }
1053   return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1054 }
1055
1056
1057 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1058                                           MutableMode mode,
1059                                           PretenureFlag pretenure) {
1060   CALL_HEAP_FUNCTION(
1061       isolate(),
1062       isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1063       HeapNumber);
1064 }
1065
1066
1067 Handle<Object> Factory::NewTypeError(const char* message,
1068                                      Vector<Handle<Object> > args) {
1069   return NewError("MakeTypeError", message, args);
1070 }
1071
1072
1073 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1074   return NewError("$TypeError", message);
1075 }
1076
1077
1078 Handle<Object> Factory::NewRangeError(const char* message,
1079                                       Vector<Handle<Object> > args) {
1080   return NewError("MakeRangeError", message, args);
1081 }
1082
1083
1084 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1085   return NewError("$RangeError", message);
1086 }
1087
1088
1089 Handle<Object> Factory::NewSyntaxError(const char* message,
1090                                        Handle<JSArray> args) {
1091   return NewError("MakeSyntaxError", message, args);
1092 }
1093
1094
1095 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1096   return NewError("$SyntaxError", message);
1097 }
1098
1099
1100 Handle<Object> Factory::NewReferenceError(const char* message,
1101                                           Vector<Handle<Object> > args) {
1102   return NewError("MakeReferenceError", message, args);
1103 }
1104
1105
1106 Handle<Object> Factory::NewReferenceError(const char* message,
1107                                           Handle<JSArray> args) {
1108   return NewError("MakeReferenceError", message, args);
1109 }
1110
1111
1112 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1113   return NewError("$ReferenceError", message);
1114 }
1115
1116
1117 Handle<Object> Factory::NewError(const char* maker, const char* message,
1118                                  Vector<Handle<Object> > args) {
1119   // Instantiate a closeable HandleScope for EscapeFrom.
1120   v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1121   Handle<FixedArray> array = NewFixedArray(args.length());
1122   for (int i = 0; i < args.length(); i++) {
1123     array->set(i, *args[i]);
1124   }
1125   Handle<JSArray> object = NewJSArrayWithElements(array);
1126   Handle<Object> result = NewError(maker, message, object);
1127   return result.EscapeFrom(&scope);
1128 }
1129
1130
1131 Handle<Object> Factory::NewEvalError(const char* message,
1132                                      Vector<Handle<Object> > args) {
1133   return NewError("MakeEvalError", message, args);
1134 }
1135
1136
1137 Handle<Object> Factory::NewError(const char* message,
1138                                  Vector<Handle<Object> > args) {
1139   return NewError("MakeError", message, args);
1140 }
1141
1142
1143 Handle<String> Factory::EmergencyNewError(const char* message,
1144                                           Handle<JSArray> args) {
1145   const int kBufferSize = 1000;
1146   char buffer[kBufferSize];
1147   size_t space = kBufferSize;
1148   char* p = &buffer[0];
1149
1150   Vector<char> v(buffer, kBufferSize);
1151   StrNCpy(v, message, space);
1152   space -= Min(space, strlen(message));
1153   p = &buffer[kBufferSize] - space;
1154
1155   for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1156     if (space > 0) {
1157       *p++ = ' ';
1158       space--;
1159       if (space > 0) {
1160         Handle<String> arg_str = Handle<String>::cast(
1161             Object::GetElement(isolate(), args, i).ToHandleChecked());
1162         SmartArrayPointer<char> arg = arg_str->ToCString();
1163         Vector<char> v2(p, static_cast<int>(space));
1164         StrNCpy(v2, arg.get(), space);
1165         space -= Min(space, strlen(arg.get()));
1166         p = &buffer[kBufferSize] - space;
1167       }
1168     }
1169   }
1170   if (space > 0) {
1171     *p = '\0';
1172   } else {
1173     buffer[kBufferSize - 1] = '\0';
1174   }
1175   return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1176 }
1177
1178
1179 Handle<Object> Factory::NewError(const char* maker, const char* message,
1180                                  Handle<JSArray> args) {
1181   Handle<String> make_str = InternalizeUtf8String(maker);
1182   Handle<Object> fun_obj = Object::GetProperty(
1183       isolate()->js_builtins_object(), make_str).ToHandleChecked();
1184   // If the builtins haven't been properly configured yet this error
1185   // constructor may not have been defined.  Bail out.
1186   if (!fun_obj->IsJSFunction()) {
1187     return EmergencyNewError(message, args);
1188   }
1189   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1190   Handle<Object> message_obj = InternalizeUtf8String(message);
1191   Handle<Object> argv[] = { message_obj, args };
1192
1193   // Invoke the JavaScript factory method. If an exception is thrown while
1194   // running the factory method, use the exception as the result.
1195   Handle<Object> result;
1196   MaybeHandle<Object> exception;
1197   if (!Execution::TryCall(fun,
1198                           isolate()->js_builtins_object(),
1199                           arraysize(argv),
1200                           argv,
1201                           &exception).ToHandle(&result)) {
1202     Handle<Object> exception_obj;
1203     if (exception.ToHandle(&exception_obj)) return exception_obj;
1204     return undefined_value();
1205   }
1206   return result;
1207 }
1208
1209
1210 Handle<Object> Factory::NewError(Handle<String> message) {
1211   return NewError("$Error", message);
1212 }
1213
1214
1215 Handle<Object> Factory::NewError(const char* constructor,
1216                                  Handle<String> message) {
1217   Handle<String> constr = InternalizeUtf8String(constructor);
1218   Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1219       isolate()->js_builtins_object(), constr).ToHandleChecked());
1220   Handle<Object> argv[] = { message };
1221
1222   // Invoke the JavaScript factory method. If an exception is thrown while
1223   // running the factory method, use the exception as the result.
1224   Handle<Object> result;
1225   MaybeHandle<Object> exception;
1226   if (!Execution::TryCall(fun,
1227                           isolate()->js_builtins_object(),
1228                           arraysize(argv),
1229                           argv,
1230                           &exception).ToHandle(&result)) {
1231     Handle<Object> exception_obj;
1232     if (exception.ToHandle(&exception_obj)) return exception_obj;
1233     return undefined_value();
1234   }
1235   return result;
1236 }
1237
1238
1239 void Factory::InitializeFunction(Handle<JSFunction> function,
1240                                  Handle<SharedFunctionInfo> info,
1241                                  Handle<Context> context) {
1242   function->initialize_properties();
1243   function->initialize_elements();
1244   function->set_shared(*info);
1245   function->set_code(info->code());
1246   function->set_context(*context);
1247   function->set_prototype_or_initial_map(*the_hole_value());
1248   function->set_literals_or_bindings(*empty_fixed_array());
1249   function->set_next_function_link(*undefined_value());
1250 }
1251
1252
1253 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1254                                         Handle<SharedFunctionInfo> info,
1255                                         Handle<Context> context,
1256                                         PretenureFlag pretenure) {
1257   AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1258   Handle<JSFunction> result = New<JSFunction>(map, space);
1259   InitializeFunction(result, info, context);
1260   return result;
1261 }
1262
1263
1264 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1265                                         Handle<String> name,
1266                                         MaybeHandle<Code> code) {
1267   Handle<Context> context(isolate()->native_context());
1268   Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1269   DCHECK(is_sloppy(info->language_mode()) &&
1270          (map.is_identical_to(isolate()->sloppy_function_map()) ||
1271           map.is_identical_to(
1272               isolate()->sloppy_function_without_prototype_map()) ||
1273           map.is_identical_to(
1274               isolate()->sloppy_function_with_readonly_prototype_map())));
1275   return NewFunction(map, info, context);
1276 }
1277
1278
1279 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1280   return NewFunction(
1281       isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1282 }
1283
1284
1285 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1286                                                         Handle<Code> code) {
1287   return NewFunction(
1288       isolate()->sloppy_function_without_prototype_map(), name, code);
1289 }
1290
1291
1292 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1293                                         Handle<Code> code,
1294                                         Handle<Object> prototype,
1295                                         bool read_only_prototype) {
1296   Handle<Map> map = read_only_prototype
1297       ? isolate()->sloppy_function_with_readonly_prototype_map()
1298       : isolate()->sloppy_function_map();
1299   Handle<JSFunction> result = NewFunction(map, name, code);
1300   result->set_prototype_or_initial_map(*prototype);
1301   return result;
1302 }
1303
1304
1305 Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1306                                         Handle<Object> prototype,
1307                                         InstanceType type, int instance_size,
1308                                         bool read_only_prototype,
1309                                         bool install_constructor) {
1310   // Allocate the function
1311   Handle<JSFunction> function = NewFunction(
1312       name, code, prototype, read_only_prototype);
1313
1314   ElementsKind elements_kind =
1315       type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1316   Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1317   if (!function->shared()->is_generator()) {
1318     if (prototype->IsTheHole()) {
1319       prototype = NewFunctionPrototype(function);
1320     } else if (install_constructor) {
1321       JSObject::AddProperty(Handle<JSObject>::cast(prototype),
1322                             constructor_string(), function, DONT_ENUM);
1323     }
1324   }
1325
1326   JSFunction::SetInitialMap(function, initial_map,
1327                             Handle<JSReceiver>::cast(prototype));
1328
1329   return function;
1330 }
1331
1332
1333 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1334                                         Handle<Code> code,
1335                                         InstanceType type,
1336                                         int instance_size) {
1337   return NewFunction(name, code, the_hole_value(), type, instance_size);
1338 }
1339
1340
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"
1348     // properties.
1349     new_map = handle(native_context->generator_object_prototype_map());
1350   } else {
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     DCHECK(object_function->has_initial_map());
1355     new_map = handle(object_function->initial_map());
1356   }
1357
1358   DCHECK(!new_map->is_prototype_map());
1359   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1360
1361   if (!function->shared()->is_generator()) {
1362     JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1363   }
1364
1365   return prototype;
1366 }
1367
1368
1369 static bool ShouldOptimizeNewClosure(Handle<SharedFunctionInfo> info) {
1370   return !info->is_toplevel() && info->allows_lazy_compilation();
1371 }
1372
1373
1374 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1375     Handle<SharedFunctionInfo> info,
1376     Handle<Context> context,
1377     PretenureFlag pretenure) {
1378   int map_index =
1379       Context::FunctionMapIndex(info->language_mode(), info->kind());
1380   Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1381   Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1382
1383   if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1384     info->ResetForNewContext(isolate()->heap()->global_ic_age());
1385   }
1386
1387   int index = info->SearchOptimizedCodeMap(context->native_context(),
1388                                            BailoutId::None());
1389   if (!info->bound() && index < 0) {
1390     int number_of_literals = info->num_literals();
1391     Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1392     result->set_literals(*literals);
1393   }
1394
1395   if (index > 0) {
1396     // Caching of optimized code enabled and optimized code found.
1397     FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1398     if (literals != NULL) result->set_literals(literals);
1399     Code* code = info->GetCodeFromOptimizedCodeMap(index);
1400     DCHECK(!code->marked_for_deoptimization());
1401     result->ReplaceCode(code);
1402     return result;
1403   }
1404
1405   if (FLAG_always_opt && ShouldOptimizeNewClosure(info)) {
1406     result->MarkForOptimization();
1407   }
1408   return result;
1409 }
1410
1411
1412 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1413   Handle<FixedArray> array = NewFixedArray(length, TENURED);
1414   array->set_map_no_write_barrier(*scope_info_map());
1415   Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1416   return scope_info;
1417 }
1418
1419
1420 Handle<JSObject> Factory::NewExternal(void* value) {
1421   Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1422   Handle<JSObject> external = NewJSObjectFromMap(external_map());
1423   external->SetInternalField(0, *foreign);
1424   return external;
1425 }
1426
1427
1428 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1429   CALL_HEAP_FUNCTION(isolate(),
1430                      isolate()->heap()->AllocateCode(object_size, immovable),
1431                      Code);
1432 }
1433
1434
1435 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1436                               Code::Flags flags,
1437                               Handle<Object> self_ref,
1438                               bool immovable,
1439                               bool crankshafted,
1440                               int prologue_offset,
1441                               bool is_debug) {
1442   Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1443   Handle<ConstantPoolArray> constant_pool =
1444       desc.origin->NewConstantPool(isolate());
1445
1446   // Compute size.
1447   int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1448   int obj_size = Code::SizeFor(body_size);
1449
1450   Handle<Code> code = NewCodeRaw(obj_size, immovable);
1451   DCHECK(isolate()->code_range() == NULL ||
1452          !isolate()->code_range()->valid() ||
1453          isolate()->code_range()->contains(code->address()));
1454
1455   // The code object has not been fully initialized yet.  We rely on the
1456   // fact that no allocation will happen from this point on.
1457   DisallowHeapAllocation no_gc;
1458   code->set_gc_metadata(Smi::FromInt(0));
1459   code->set_ic_age(isolate()->heap()->global_ic_age());
1460   code->set_instruction_size(desc.instr_size);
1461   code->set_relocation_info(*reloc_info);
1462   code->set_flags(flags);
1463   code->set_raw_kind_specific_flags1(0);
1464   code->set_raw_kind_specific_flags2(0);
1465   code->set_is_crankshafted(crankshafted);
1466   code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1467   code->set_raw_type_feedback_info(Smi::FromInt(0));
1468   code->set_next_code_link(*undefined_value());
1469   code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1470   code->set_prologue_offset(prologue_offset);
1471   if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1472     code->set_marked_for_deoptimization(false);
1473   }
1474
1475   if (is_debug) {
1476     DCHECK(code->kind() == Code::FUNCTION);
1477     code->set_has_debug_break_slots(true);
1478   }
1479
1480   desc.origin->PopulateConstantPool(*constant_pool);
1481   code->set_constant_pool(*constant_pool);
1482
1483   // Allow self references to created code object by patching the handle to
1484   // point to the newly allocated Code object.
1485   if (!self_ref.is_null()) *(self_ref.location()) = *code;
1486
1487   // Migrate generated code.
1488   // The generated code can contain Object** values (typically from handles)
1489   // that are dereferenced during the copy to point directly to the actual heap
1490   // objects. These pointers can include references to the code object itself,
1491   // through the self_reference parameter.
1492   code->CopyFrom(desc);
1493
1494 #ifdef VERIFY_HEAP
1495   if (FLAG_verify_heap) code->ObjectVerify();
1496 #endif
1497   return code;
1498 }
1499
1500
1501 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1502   CALL_HEAP_FUNCTION(isolate(),
1503                      isolate()->heap()->CopyCode(*code),
1504                      Code);
1505 }
1506
1507
1508 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1509   CALL_HEAP_FUNCTION(isolate(),
1510                      isolate()->heap()->CopyCode(*code, reloc_info),
1511                      Code);
1512 }
1513
1514
1515 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1516                                       PretenureFlag pretenure) {
1517   JSFunction::EnsureHasInitialMap(constructor);
1518   CALL_HEAP_FUNCTION(
1519       isolate(),
1520       isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1521 }
1522
1523
1524 Handle<JSObject> Factory::NewJSObjectWithMemento(
1525     Handle<JSFunction> constructor,
1526     Handle<AllocationSite> site) {
1527   JSFunction::EnsureHasInitialMap(constructor);
1528   CALL_HEAP_FUNCTION(
1529       isolate(),
1530       isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1531       JSObject);
1532 }
1533
1534
1535 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1536                                       Handle<ScopeInfo> scope_info) {
1537   // Allocate a fresh map. Modules do not have a prototype.
1538   Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1539   // Allocate the object based on the map.
1540   Handle<JSModule> module =
1541       Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1542   module->set_context(*context);
1543   module->set_scope_info(*scope_info);
1544   return module;
1545 }
1546
1547
1548 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1549   DCHECK(constructor->has_initial_map());
1550   Handle<Map> map(constructor->initial_map());
1551   DCHECK(map->is_dictionary_map());
1552
1553   // Make sure no field properties are described in the initial map.
1554   // This guarantees us that normalizing the properties does not
1555   // require us to change property values to PropertyCells.
1556   DCHECK(map->NextFreePropertyIndex() == 0);
1557
1558   // Make sure we don't have a ton of pre-allocated slots in the
1559   // global objects. They will be unused once we normalize the object.
1560   DCHECK(map->unused_property_fields() == 0);
1561   DCHECK(map->inobject_properties() == 0);
1562
1563   // Initial size of the backing store to avoid resize of the storage during
1564   // bootstrapping. The size differs between the JS global object ad the
1565   // builtins object.
1566   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1567
1568   // Allocate a dictionary object for backing storage.
1569   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1570   Handle<NameDictionary> dictionary =
1571       NameDictionary::New(isolate(), at_least_space_for);
1572
1573   // The global object might be created from an object template with accessors.
1574   // Fill these accessors into the dictionary.
1575   Handle<DescriptorArray> descs(map->instance_descriptors());
1576   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1577     PropertyDetails details = descs->GetDetails(i);
1578     // Only accessors are expected.
1579     DCHECK_EQ(ACCESSOR_CONSTANT, details.type());
1580     PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
1581                       PropertyCellType::kMutable);
1582     Handle<Name> name(descs->GetKey(i));
1583     Handle<PropertyCell> cell = NewPropertyCell();
1584     cell->set_value(descs->GetCallbacksObject(i));
1585     // |dictionary| already contains enough space for all properties.
1586     USE(NameDictionary::Add(dictionary, name, cell, d));
1587   }
1588
1589   // Allocate the global object and initialize it with the backing store.
1590   Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1591   isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1592
1593   // Create a new map for the global object.
1594   Handle<Map> new_map = Map::CopyDropDescriptors(map);
1595   new_map->set_dictionary_map(true);
1596
1597   // Set up the global object as a normalized object.
1598   global->set_map(*new_map);
1599   global->set_properties(*dictionary);
1600
1601   // Make sure result is a global object with properties in dictionary.
1602   DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1603   return global;
1604 }
1605
1606
1607 Handle<JSObject> Factory::NewJSObjectFromMap(
1608     Handle<Map> map,
1609     PretenureFlag pretenure,
1610     bool alloc_props,
1611     Handle<AllocationSite> allocation_site) {
1612   CALL_HEAP_FUNCTION(
1613       isolate(),
1614       isolate()->heap()->AllocateJSObjectFromMap(
1615           *map,
1616           pretenure,
1617           alloc_props,
1618           allocation_site.is_null() ? NULL : *allocation_site),
1619       JSObject);
1620 }
1621
1622
1623 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1624                                     PretenureFlag pretenure) {
1625   Context* native_context = isolate()->context()->native_context();
1626   JSFunction* array_function = native_context->array_function();
1627   Map* map = array_function->initial_map();
1628   Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1629   if (transition_map != NULL) map = transition_map;
1630   return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1631 }
1632
1633
1634 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1635                                     int length,
1636                                     int capacity,
1637                                     ArrayStorageAllocationMode mode,
1638                                     PretenureFlag pretenure) {
1639   Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1640   NewJSArrayStorage(array, length, capacity, mode);
1641   return array;
1642 }
1643
1644
1645 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1646                                                 ElementsKind elements_kind,
1647                                                 int length,
1648                                                 PretenureFlag pretenure) {
1649   DCHECK(length <= elements->length());
1650   Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1651
1652   array->set_elements(*elements);
1653   array->set_length(Smi::FromInt(length));
1654   JSObject::ValidateElements(array);
1655   return array;
1656 }
1657
1658
1659 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1660                                 int length,
1661                                 int capacity,
1662                                 ArrayStorageAllocationMode mode) {
1663   DCHECK(capacity >= length);
1664
1665   if (capacity == 0) {
1666     array->set_length(Smi::FromInt(0));
1667     array->set_elements(*empty_fixed_array());
1668     return;
1669   }
1670
1671   HandleScope inner_scope(isolate());
1672   Handle<FixedArrayBase> elms;
1673   ElementsKind elements_kind = array->GetElementsKind();
1674   if (IsFastDoubleElementsKind(elements_kind)) {
1675     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1676       elms = NewFixedDoubleArray(capacity);
1677     } else {
1678       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1679       elms = NewFixedDoubleArrayWithHoles(capacity);
1680     }
1681   } else {
1682     DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1683     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1684       elms = NewUninitializedFixedArray(capacity);
1685     } else {
1686       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1687       elms = NewFixedArrayWithHoles(capacity);
1688     }
1689   }
1690
1691   array->set_elements(*elms);
1692   array->set_length(Smi::FromInt(length));
1693 }
1694
1695
1696 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1697     Handle<JSFunction> function) {
1698   DCHECK(function->shared()->is_generator());
1699   JSFunction::EnsureHasInitialMap(function);
1700   Handle<Map> map(function->initial_map());
1701   DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1702   CALL_HEAP_FUNCTION(
1703       isolate(),
1704       isolate()->heap()->AllocateJSObjectFromMap(*map),
1705       JSGeneratorObject);
1706 }
1707
1708
1709 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1710   Handle<JSFunction> array_buffer_fun(
1711       isolate()->native_context()->array_buffer_fun());
1712   CALL_HEAP_FUNCTION(
1713       isolate(),
1714       isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1715       JSArrayBuffer);
1716 }
1717
1718
1719 Handle<JSDataView> Factory::NewJSDataView() {
1720   Handle<JSFunction> data_view_fun(
1721       isolate()->native_context()->data_view_fun());
1722   CALL_HEAP_FUNCTION(
1723       isolate(),
1724       isolate()->heap()->AllocateJSObject(*data_view_fun),
1725       JSDataView);
1726 }
1727
1728
1729 Handle<JSMapIterator> Factory::NewJSMapIterator() {
1730   Handle<Map> map(isolate()->native_context()->map_iterator_map());
1731   CALL_HEAP_FUNCTION(isolate(),
1732                      isolate()->heap()->AllocateJSObjectFromMap(*map),
1733                      JSMapIterator);
1734 }
1735
1736
1737 Handle<JSSetIterator> Factory::NewJSSetIterator() {
1738   Handle<Map> map(isolate()->native_context()->set_iterator_map());
1739   CALL_HEAP_FUNCTION(isolate(),
1740                      isolate()->heap()->AllocateJSObjectFromMap(*map),
1741                      JSSetIterator);
1742 }
1743
1744
1745 namespace {
1746
1747 ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
1748   switch (type) {
1749 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1750   case kExternal##Type##Array:                          \
1751     return EXTERNAL_##TYPE##_ELEMENTS;
1752     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1753   }
1754   UNREACHABLE();
1755   return FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND;
1756 #undef TYPED_ARRAY_CASE
1757 }
1758
1759
1760 size_t GetExternalArrayElementSize(ExternalArrayType type) {
1761   switch (type) {
1762 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1763   case kExternal##Type##Array:                          \
1764     return size;
1765     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1766   }
1767   UNREACHABLE();
1768   return 0;
1769 #undef TYPED_ARRAY_CASE
1770 }
1771
1772
1773 JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1774   Context* native_context = isolate->context()->native_context();
1775   switch (type) {
1776 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
1777     case kExternal##Type##Array:                                              \
1778       return native_context->type##_array_fun();
1779
1780     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1781 #undef TYPED_ARRAY_FUN
1782
1783     default:
1784       UNREACHABLE();
1785       return NULL;
1786   }
1787 }
1788
1789
1790 void SetupArrayBufferView(i::Isolate* isolate,
1791                           i::Handle<i::JSArrayBufferView> obj,
1792                           i::Handle<i::JSArrayBuffer> buffer,
1793                           size_t byte_offset, size_t byte_length) {
1794   DCHECK(byte_offset + byte_length <=
1795          static_cast<size_t>(buffer->byte_length()->Number()));
1796
1797   obj->set_buffer(*buffer);
1798
1799   Heap* heap = isolate->heap();
1800   if (heap->InNewSpace(*obj)) {
1801     obj->set_weak_next(heap->new_array_buffer_views_list());
1802     heap->set_new_array_buffer_views_list(*obj);
1803   } else {
1804     obj->set_weak_next(buffer->weak_first_view());
1805     buffer->set_weak_first_view(*obj);
1806   }
1807
1808   i::Handle<i::Object> byte_offset_object =
1809       isolate->factory()->NewNumberFromSize(byte_offset);
1810   obj->set_byte_offset(*byte_offset_object);
1811
1812   i::Handle<i::Object> byte_length_object =
1813       isolate->factory()->NewNumberFromSize(byte_length);
1814   obj->set_byte_length(*byte_length_object);
1815 }
1816
1817
1818 }  // namespace
1819
1820
1821 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1822   Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1823
1824   CALL_HEAP_FUNCTION(
1825       isolate(),
1826       isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1827       JSTypedArray);
1828 }
1829
1830
1831 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
1832                                               Handle<JSArrayBuffer> buffer,
1833                                               size_t byte_offset,
1834                                               size_t length) {
1835   Handle<JSTypedArray> obj = NewJSTypedArray(type);
1836
1837   size_t element_size = GetExternalArrayElementSize(type);
1838   ElementsKind elements_kind = GetExternalArrayElementsKind(type);
1839
1840   CHECK(byte_offset % element_size == 0);
1841
1842   CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
1843   CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
1844   size_t byte_length = length * element_size;
1845   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1846
1847   Handle<Object> length_object = NewNumberFromSize(length);
1848   obj->set_length(*length_object);
1849
1850   Handle<ExternalArray> elements = NewExternalArray(
1851       static_cast<int>(length), type,
1852       static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1853   Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
1854   JSObject::SetMapAndElements(obj, map, elements);
1855   return obj;
1856 }
1857
1858
1859 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
1860                                           size_t byte_offset,
1861                                           size_t byte_length) {
1862   Handle<JSDataView> obj = NewJSDataView();
1863   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1864   return obj;
1865 }
1866
1867
1868 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1869                                     Handle<Object> prototype) {
1870   // Allocate map.
1871   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1872   // maps. Will probably depend on the identity of the handler object, too.
1873   Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1874   map->SetPrototype(prototype);
1875
1876   // Allocate the proxy object.
1877   Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1878   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1879   result->set_handler(*handler);
1880   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1881   return result;
1882 }
1883
1884
1885 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1886                                             Handle<Object> call_trap,
1887                                             Handle<Object> construct_trap,
1888                                             Handle<Object> prototype) {
1889   // Allocate map.
1890   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1891   // maps. Will probably depend on the identity of the handler object, too.
1892   Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1893   map->SetPrototype(prototype);
1894
1895   // Allocate the proxy object.
1896   Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1897   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1898   result->set_handler(*handler);
1899   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1900   result->set_call_trap(*call_trap);
1901   result->set_construct_trap(*construct_trap);
1902   return result;
1903 }
1904
1905
1906 void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
1907                                   int size) {
1908   DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
1909
1910   // Allocate fresh map.
1911   // TODO(rossberg): Once we optimize proxies, cache these maps.
1912   Handle<Map> map = NewMap(type, size);
1913
1914   // Check that the receiver has at least the size of the fresh object.
1915   int size_difference = proxy->map()->instance_size() - map->instance_size();
1916   DCHECK(size_difference >= 0);
1917
1918   map->SetPrototype(handle(proxy->map()->prototype(), proxy->GetIsolate()));
1919
1920   // Allocate the backing storage for the properties.
1921   int prop_size = map->InitialPropertiesLength();
1922   Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1923
1924   Heap* heap = isolate()->heap();
1925   MaybeHandle<SharedFunctionInfo> shared;
1926   if (type == JS_FUNCTION_TYPE) {
1927     OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
1928                          heap->HashSeed());
1929     Handle<String> name = InternalizeStringWithKey(&key);
1930     shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1931   }
1932
1933   // In order to keep heap in consistent state there must be no allocations
1934   // before object re-initialization is finished and filler object is installed.
1935   DisallowHeapAllocation no_allocation;
1936
1937   // Put in filler if the new object is smaller than the old.
1938   if (size_difference > 0) {
1939     Address address = proxy->address();
1940     heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1941     heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1942   }
1943
1944   // Reset the map for the object.
1945   proxy->synchronized_set_map(*map);
1946   Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
1947
1948   // Reinitialize the object from the constructor map.
1949   heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1950
1951   // The current native context is used to set up certain bits.
1952   // TODO(adamk): Using the current context seems wrong, it should be whatever
1953   // context the JSProxy originated in. But that context isn't stored anywhere.
1954   Handle<Context> context(isolate()->native_context());
1955
1956   // Functions require some minimal initialization.
1957   if (type == JS_FUNCTION_TYPE) {
1958     map->set_function_with_prototype(true);
1959     Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
1960     InitializeFunction(js_function, shared.ToHandleChecked(), context);
1961   } else {
1962     // Provide JSObjects with a constructor.
1963     map->SetConstructor(context->object_function());
1964   }
1965 }
1966
1967
1968 Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy() {
1969   // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
1970   // via ReinitializeJSGlobalProxy later.
1971   Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
1972   // Maintain invariant expected from any JSGlobalProxy.
1973   map->set_is_access_check_needed(true);
1974   CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObjectFromMap(
1975                                     *map, NOT_TENURED, false),
1976                      JSGlobalProxy);
1977 }
1978
1979
1980 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1981                                         Handle<JSFunction> constructor) {
1982   DCHECK(constructor->has_initial_map());
1983   Handle<Map> map(constructor->initial_map(), isolate());
1984
1985   // The proxy's hash should be retained across reinitialization.
1986   Handle<Object> hash(object->hash(), isolate());
1987
1988   // Check that the already allocated object has the same size and type as
1989   // objects allocated using the constructor.
1990   DCHECK(map->instance_size() == object->map()->instance_size());
1991   DCHECK(map->instance_type() == object->map()->instance_type());
1992
1993   // Allocate the backing storage for the properties.
1994   int prop_size = map->InitialPropertiesLength();
1995   Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1996
1997   // In order to keep heap in consistent state there must be no allocations
1998   // before object re-initialization is finished.
1999   DisallowHeapAllocation no_allocation;
2000
2001   // Reset the map for the object.
2002   object->synchronized_set_map(*map);
2003
2004   Heap* heap = isolate()->heap();
2005   // Reinitialize the object from the constructor map.
2006   heap->InitializeJSObjectFromMap(*object, *properties, *map);
2007
2008   // Restore the saved hash.
2009   object->set_hash(*hash);
2010 }
2011
2012
2013 void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
2014   ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2015 }
2016
2017
2018 void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
2019   ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
2020 }
2021
2022
2023 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2024     const ZoneFeedbackVectorSpec* spec);
2025 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2026     const FeedbackVectorSpec* spec);
2027
2028 template <typename Spec>
2029 Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(const Spec* spec) {
2030   return TypeFeedbackVector::Allocate<Spec>(isolate(), spec);
2031 }
2032
2033
2034 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2035     Handle<String> name, int number_of_literals, FunctionKind kind,
2036     Handle<Code> code, Handle<ScopeInfo> scope_info,
2037     Handle<TypeFeedbackVector> feedback_vector) {
2038   DCHECK(IsValidFunctionKind(kind));
2039   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
2040   shared->set_scope_info(*scope_info);
2041   shared->set_feedback_vector(*feedback_vector);
2042   shared->set_kind(kind);
2043   shared->set_num_literals(number_of_literals);
2044   if (IsGeneratorFunction(kind)) {
2045     shared->set_instance_class_name(isolate()->heap()->Generator_string());
2046     shared->DisableOptimization(kGenerator);
2047   }
2048   return shared;
2049 }
2050
2051
2052 Handle<JSMessageObject> Factory::NewJSMessageObject(
2053     Handle<String> type,
2054     Handle<JSArray> arguments,
2055     int start_position,
2056     int end_position,
2057     Handle<Object> script,
2058     Handle<Object> stack_frames) {
2059   Handle<Map> map = message_object_map();
2060   Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
2061   message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2062   message->initialize_elements();
2063   message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2064   message->set_type(*type);
2065   message->set_arguments(*arguments);
2066   message->set_start_position(start_position);
2067   message->set_end_position(end_position);
2068   message->set_script(*script);
2069   message->set_stack_frames(*stack_frames);
2070   return message;
2071 }
2072
2073
2074 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2075     Handle<String> name,
2076     MaybeHandle<Code> maybe_code) {
2077   Handle<Map> map = shared_function_info_map();
2078   Handle<SharedFunctionInfo> share =
2079       New<SharedFunctionInfo>(map, OLD_POINTER_SPACE);
2080
2081   // Set pointer fields.
2082   share->set_name(*name);
2083   Handle<Code> code;
2084   if (!maybe_code.ToHandle(&code)) {
2085     code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
2086   }
2087   share->set_code(*code);
2088   share->set_optimized_code_map(Smi::FromInt(0));
2089   share->set_scope_info(ScopeInfo::Empty(isolate()));
2090   Code* construct_stub =
2091       isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2092   share->set_construct_stub(construct_stub);
2093   share->set_instance_class_name(*Object_string());
2094   share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2095   share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2096   share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
2097   share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2098   FeedbackVectorSpec empty_spec(0);
2099   Handle<TypeFeedbackVector> feedback_vector =
2100       NewTypeFeedbackVector(&empty_spec);
2101   share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2102 #if TRACE_MAPS
2103   share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
2104 #endif
2105   share->set_profiler_ticks(0);
2106   share->set_ast_node_count(0);
2107   share->set_counters(0);
2108
2109   // Set integer fields (smi or int, depending on the architecture).
2110   share->set_length(0);
2111   share->set_internal_formal_parameter_count(0);
2112   share->set_expected_nof_properties(0);
2113   share->set_num_literals(0);
2114   share->set_start_position_and_type(0);
2115   share->set_end_position(0);
2116   share->set_function_token_position(0);
2117   // All compiler hints default to false or 0.
2118   share->set_compiler_hints(0);
2119   share->set_opt_count_and_bailout_reason(0);
2120
2121   return share;
2122 }
2123
2124
2125 static inline int NumberCacheHash(Handle<FixedArray> cache,
2126                                   Handle<Object> number) {
2127   int mask = (cache->length() >> 1) - 1;
2128   if (number->IsSmi()) {
2129     return Handle<Smi>::cast(number)->value() & mask;
2130   } else {
2131     DoubleRepresentation rep(number->Number());
2132     return
2133         (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2134   }
2135 }
2136
2137
2138 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2139   DisallowHeapAllocation no_gc;
2140   int hash = NumberCacheHash(number_string_cache(), number);
2141   Object* key = number_string_cache()->get(hash * 2);
2142   if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2143                          key->Number() == number->Number())) {
2144     return Handle<String>(
2145         String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2146   }
2147   return undefined_value();
2148 }
2149
2150
2151 void Factory::SetNumberStringCache(Handle<Object> number,
2152                                    Handle<String> string) {
2153   int hash = NumberCacheHash(number_string_cache(), number);
2154   if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2155     int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2156     if (number_string_cache()->length() != full_size) {
2157       Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2158       isolate()->heap()->set_number_string_cache(*new_cache);
2159       return;
2160     }
2161   }
2162   number_string_cache()->set(hash * 2, *number);
2163   number_string_cache()->set(hash * 2 + 1, *string);
2164 }
2165
2166
2167 Handle<String> Factory::NumberToString(Handle<Object> number,
2168                                        bool check_number_string_cache) {
2169   isolate()->counters()->number_to_string_runtime()->Increment();
2170   if (check_number_string_cache) {
2171     Handle<Object> cached = GetNumberStringCache(number);
2172     if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2173   }
2174
2175   char arr[100];
2176   Vector<char> buffer(arr, arraysize(arr));
2177   const char* str;
2178   if (number->IsSmi()) {
2179     int num = Handle<Smi>::cast(number)->value();
2180     str = IntToCString(num, buffer);
2181   } else {
2182     double num = Handle<HeapNumber>::cast(number)->value();
2183     str = DoubleToCString(num, buffer);
2184   }
2185
2186   // We tenure the allocated string since it is referenced from the
2187   // number-string cache which lives in the old space.
2188   Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2189   SetNumberStringCache(number, js_string);
2190   return js_string;
2191 }
2192
2193
2194 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2195   // Get the original code of the function.
2196   Handle<Code> code(shared->code());
2197
2198   // Create a copy of the code before allocating the debug info object to avoid
2199   // allocation while setting up the debug info object.
2200   Handle<Code> original_code(*Factory::CopyCode(code));
2201
2202   // Allocate initial fixed array for active break points before allocating the
2203   // debug info object to avoid allocation while setting up the debug info
2204   // object.
2205   Handle<FixedArray> break_points(
2206       NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2207
2208   // Create and set up the debug info object. Debug info contains function, a
2209   // copy of the original code, the executing code and initial fixed array for
2210   // active break points.
2211   Handle<DebugInfo> debug_info =
2212       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2213   debug_info->set_shared(*shared);
2214   debug_info->set_original_code(*original_code);
2215   debug_info->set_code(*code);
2216   debug_info->set_break_points(*break_points);
2217
2218   // Link debug info to function.
2219   shared->set_debug_info(*debug_info);
2220
2221   return debug_info;
2222 }
2223
2224
2225 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2226                                              int length) {
2227   bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2228                             !callee->is_simple_parameter_list();
2229   Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2230                                        : isolate()->sloppy_arguments_map();
2231
2232   AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2233                                      false);
2234   DCHECK(!isolate()->has_pending_exception());
2235   Handle<JSObject> result = NewJSObjectFromMap(map);
2236   Handle<Smi> value(Smi::FromInt(length), isolate());
2237   Object::SetProperty(result, length_string(), value, STRICT).Assert();
2238   if (!strict_mode_callee) {
2239     Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2240   }
2241   return result;
2242 }
2243
2244
2245 Handle<JSWeakMap> Factory::NewJSWeakMap() {
2246   // TODO(adamk): Currently the map is only created three times per
2247   // isolate. If it's created more often, the map should be moved into the
2248   // strong root list.
2249   Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
2250   return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
2251 }
2252
2253
2254 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2255                                                int number_of_properties,
2256                                                bool* is_result_from_cache) {
2257   const int kMapCacheSize = 128;
2258
2259   if (number_of_properties > kMapCacheSize) {
2260     *is_result_from_cache = false;
2261     return Map::Create(isolate(), number_of_properties);
2262   }
2263   *is_result_from_cache = true;
2264   if (number_of_properties == 0) {
2265     // Reuse the initial map of the Object function if the literal has no
2266     // predeclared properties.
2267     return handle(context->object_function()->initial_map(), isolate());
2268   }
2269   int cache_index = number_of_properties - 1;
2270   if (context->map_cache()->IsUndefined()) {
2271     // Allocate the new map cache for the native context.
2272     Handle<FixedArray> new_cache = NewFixedArray(kMapCacheSize, TENURED);
2273     context->set_map_cache(*new_cache);
2274   }
2275   // Check to see whether there is a matching element in the cache.
2276   Handle<FixedArray> cache(FixedArray::cast(context->map_cache()));
2277   {
2278     Object* result = cache->get(cache_index);
2279     if (result->IsWeakCell()) {
2280       WeakCell* cell = WeakCell::cast(result);
2281       if (!cell->cleared()) {
2282         return handle(Map::cast(cell->value()), isolate());
2283       }
2284     }
2285   }
2286   // Create a new map and add it to the cache.
2287   Handle<Map> map = Map::Create(isolate(), number_of_properties);
2288   Handle<WeakCell> cell = NewWeakCell(map);
2289   cache->set(cache_index, *cell);
2290   return map;
2291 }
2292
2293
2294 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2295                                 JSRegExp::Type type,
2296                                 Handle<String> source,
2297                                 JSRegExp::Flags flags,
2298                                 Handle<Object> data) {
2299   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2300
2301   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2302   store->set(JSRegExp::kSourceIndex, *source);
2303   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2304   store->set(JSRegExp::kAtomPatternIndex, *data);
2305   regexp->set_data(*store);
2306 }
2307
2308
2309 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2310                                     JSRegExp::Type type,
2311                                     Handle<String> source,
2312                                     JSRegExp::Flags flags,
2313                                     int capture_count) {
2314   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2315   Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2316   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2317   store->set(JSRegExp::kSourceIndex, *source);
2318   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2319   store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2320   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2321   store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2322   store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2323   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2324   store->set(JSRegExp::kIrregexpCaptureCountIndex,
2325              Smi::FromInt(capture_count));
2326   regexp->set_data(*store);
2327 }
2328
2329
2330 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2331   if (String::Equals(name, undefined_string())) return undefined_value();
2332   if (String::Equals(name, nan_string())) return nan_value();
2333   if (String::Equals(name, infinity_string())) return infinity_value();
2334   return Handle<Object>::null();
2335 }
2336
2337
2338 Handle<Object> Factory::ToBoolean(bool value) {
2339   return value ? true_value() : false_value();
2340 }
2341
2342
2343 } }  // namespace v8::internal