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