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