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