factory.cc 67.1 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "api.h"
31
#include "debug.h"
32 33
#include "execution.h"
#include "factory.h"
34
#include "isolate-inl.h"
35
#include "macro-assembler.h"
36
#include "objects.h"
37
#include "objects-visiting.h"
38
#include "platform.h"
39
#include "scopeinfo.h"
40

41 42
namespace v8 {
namespace internal {
43 44


45 46 47 48 49 50 51 52
Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateBox(*value, pretenure),
      Box);
}


53 54
Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
  ASSERT(0 <= size);
55 56 57 58
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedArray(size, pretenure),
      FixedArray);
59 60 61
}


62 63
Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
                                                   PretenureFlag pretenure) {
64
  ASSERT(0 <= size);
65 66 67 68
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
      FixedArray);
69 70 71
}


72 73
Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
                                                      PretenureFlag pretenure) {
74 75 76 77
  ASSERT(0 <= size);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
78
      FixedDoubleArray);
79 80 81
}


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
    int number_of_int64_entries,
    int number_of_ptr_entries,
    int number_of_int32_entries) {
  ASSERT(number_of_int64_entries > 0 || number_of_ptr_entries > 0 ||
         number_of_int32_entries > 0);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
                                                   number_of_ptr_entries,
                                                   number_of_int32_entries),
      ConstantPoolArray);
}


97
Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
98
  ASSERT(0 <= at_least_space_for);
99
  CALL_HEAP_FUNCTION(isolate(),
100 101
                     NameDictionary::Allocate(isolate()->heap(),
                                              at_least_space_for),
102
                     NameDictionary);
103 104 105
}


106 107
Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
    int at_least_space_for) {
108
  ASSERT(0 <= at_least_space_for);
109
  CALL_HEAP_FUNCTION(isolate(),
110 111
                     SeededNumberDictionary::Allocate(isolate()->heap(),
                                                      at_least_space_for),
112 113 114 115 116 117 118 119
                     SeededNumberDictionary);
}


Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
    int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
120 121
                     UnseededNumberDictionary::Allocate(isolate()->heap(),
                                                        at_least_space_for),
122
                     UnseededNumberDictionary);
123 124 125
}


126 127 128
Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
129 130
                     ObjectHashSet::Allocate(isolate()->heap(),
                                             at_least_space_for),
131 132 133 134
                     ObjectHashSet);
}


135 136 137
Handle<ObjectHashTable> Factory::NewObjectHashTable(
    int at_least_space_for,
    MinimumCapacity capacity_option) {
138 139
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
140
                     ObjectHashTable::Allocate(isolate()->heap(),
141 142
                                               at_least_space_for,
                                               capacity_option),
143 144 145 146
                     ObjectHashTable);
}


147 148 149 150 151 152
Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(
      isolate(),
      WeakHashTable::Allocate(isolate()->heap(),
                              at_least_space_for,
153
                              USE_DEFAULT_MINIMUM_CAPACITY,
154 155 156 157 158
                              TENURED),
      WeakHashTable);
}


159 160
Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
                                                    int slack) {
161
  ASSERT(0 <= number_of_descriptors);
162
  CALL_HEAP_FUNCTION(isolate(),
163 164
                     DescriptorArray::Allocate(
                         isolate(), number_of_descriptors, slack),
165 166 167 168
                     DescriptorArray);
}


169 170 171 172
Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
    int deopt_entry_count,
    PretenureFlag pretenure) {
  ASSERT(deopt_entry_count > 0);
173
  CALL_HEAP_FUNCTION(isolate(),
174 175
                     DeoptimizationInputData::Allocate(isolate(),
                                                       deopt_entry_count,
176 177 178 179 180 181 182 183 184
                                                       pretenure),
                     DeoptimizationInputData);
}


Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
    int deopt_entry_count,
    PretenureFlag pretenure) {
  ASSERT(deopt_entry_count > 0);
185
  CALL_HEAP_FUNCTION(isolate(),
186 187
                     DeoptimizationOutputData::Allocate(isolate(),
                                                        deopt_entry_count,
188 189 190 191 192
                                                        pretenure),
                     DeoptimizationOutputData);
}


193 194 195 196 197 198 199
Handle<AccessorPair> Factory::NewAccessorPair() {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateAccessorPair(),
                     AccessorPair);
}


200 201 202 203 204 205 206
Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateTypeFeedbackInfo(),
                     TypeFeedbackInfo);
}


207 208
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
209 210
  Utf8StringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
211 212
}

213

214 215
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeString(Handle<String> string) {
216
  CALL_HEAP_FUNCTION(isolate(),
217
                     isolate()->heap()->InternalizeString(*string),
218 219 220
                     String);
}

221

222
Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
223 224
  OneByteStringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
225 226
}

227

228 229
Handle<String> Factory::InternalizeOneByteString(
    Handle<SeqOneByteString> string, int from, int length) {
230
  SubStringKey<uint8_t> key(string, from, length);
231
  return InternalizeStringWithKey(&key);
232 233 234
}


235
Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
236 237 238 239 240 241 242
  TwoByteStringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
}


template<class StringTableKey>
Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
243
  CALL_HEAP_FUNCTION(isolate(),
244
                     isolate()->heap()->InternalizeStringWithKey(key),
245
                     String);
246 247
}

248

249 250 251 252 253 254
template Handle<String> Factory::InternalizeStringWithKey<
    SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
template Handle<String> Factory::InternalizeStringWithKey<
    SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);


255 256
Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
                                             PretenureFlag pretenure) {
257 258
  CALL_HEAP_FUNCTION(
      isolate(),
259
      isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
260
      String);
261 262 263
}

Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
264
                                          PretenureFlag pretenure) {
265 266
  CALL_HEAP_FUNCTION(
      isolate(),
267
      isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
268
      String);
269 270 271
}


272 273
Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
                                             PretenureFlag pretenure) {
274 275 276 277
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
      String);
278 279 280
}


281
Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
282
                                                  PretenureFlag pretenure) {
283 284
  CALL_HEAP_FUNCTION(
      isolate(),
285
      isolate()->heap()->AllocateRawOneByteString(length, pretenure),
286
      SeqOneByteString);
287 288 289
}


290 291
Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
                                                      PretenureFlag pretenure) {
292 293 294
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
295
      SeqTwoByteString);
296 297 298
}


299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
// Returns true for a character in a range.  Both limits are inclusive.
static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
  // This makes uses of the the unsigned wraparound.
  return character - from <= to - from;
}


static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
                                                          uint16_t c1,
                                                          uint16_t c2) {
  // Numeric strings have a different hash algorithm not known by
  // LookupTwoCharsStringIfExists, so we skip this step for such strings.
  if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
    String* result;
    StringTable* table = isolate->heap()->string_table();
    if (table->LookupTwoCharsStringIfExists(c1, c2, &result)) {
      return handle(result);
    }
  }

  // Now we know the length is 2, we might as well make use of that fact
  // when building the new string.
  if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
    // We can do this.
    ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1));  // because of this.
    Handle<SeqOneByteString> str = isolate->factory()->NewRawOneByteString(2);
    uint8_t* dest = str->GetChars();
    dest[0] = static_cast<uint8_t>(c1);
    dest[1] = static_cast<uint8_t>(c2);
    return str;
  } else {
    Handle<SeqTwoByteString> str = isolate->factory()->NewRawTwoByteString(2);
    uc16* dest = str->GetChars();
    dest[0] = c1;
    dest[1] = c2;
    return str;
  }
336 337 338
}


339 340 341 342 343 344 345 346 347 348 349 350
template<typename SinkChar, typename StringType>
Handle<String> ConcatStringContent(Handle<StringType> result,
                                   Handle<String> first,
                                   Handle<String> second) {
  DisallowHeapAllocation pointer_stays_valid;
  SinkChar* sink = result->GetChars();
  String::WriteToFlat(*first, sink, 0, first->length());
  String::WriteToFlat(*second, sink + first->length(), 0, second->length());
  return result;
}


351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
Handle<ConsString> Factory::NewRawConsString(String::Encoding encoding) {
  Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
      ? cons_ascii_string_map() : cons_string_map();
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->Allocate(*map, NEW_SPACE),
                     ConsString);
}


Handle<String> Factory::NewConsString(Handle<String> left,
                                      Handle<String> right) {
  int left_length = left->length();
  if (left_length == 0) return right;
  int right_length = right->length();
  if (right_length == 0) return left;

  int length = left_length + right_length;

  if (length == 2) {
    uint16_t c1 = left->Get(0);
    uint16_t c2 = right->Get(0);
    return MakeOrFindTwoCharacterString(isolate(), c1, c2);
  }

  // Make sure that an out of memory exception is thrown if the length
  // of the new cons string is too large.
  if (length > String::kMaxLength || length < 0) {
    isolate()->context()->mark_out_of_memory();
    V8::FatalProcessOutOfMemory("String concatenation result too large.");
    UNREACHABLE();
    return Handle<String>::null();
  }

  bool left_is_one_byte = left->IsOneByteRepresentation();
  bool right_is_one_byte = right->IsOneByteRepresentation();
  bool is_one_byte = left_is_one_byte && right_is_one_byte;
  bool is_one_byte_data_in_two_byte_string = false;
  if (!is_one_byte) {
    // At least one of the strings uses two-byte representation so we
    // can't use the fast case code for short ASCII strings below, but
    // we can try to save memory if all chars actually fit in ASCII.
    is_one_byte_data_in_two_byte_string =
        left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
    if (is_one_byte_data_in_two_byte_string) {
      isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
    }
  }

  // If the resulting string is small make a flat string.
  if (length < ConsString::kMinLength) {
    // Note that neither of the two inputs can be a slice because:
    STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
    ASSERT(left->IsFlat());
    ASSERT(right->IsFlat());

    if (is_one_byte) {
      Handle<SeqOneByteString> result = NewRawOneByteString(length);
      DisallowHeapAllocation no_gc;
      uint8_t* dest = result->GetChars();
      // Copy left part.
      const uint8_t* src = left->IsExternalString()
          ? Handle<ExternalAsciiString>::cast(left)->GetChars()
          : Handle<SeqOneByteString>::cast(left)->GetChars();
      for (int i = 0; i < left_length; i++) *dest++ = src[i];
      // Copy right part.
      src = right->IsExternalString()
          ? Handle<ExternalAsciiString>::cast(right)->GetChars()
          : Handle<SeqOneByteString>::cast(right)->GetChars();
      for (int i = 0; i < right_length; i++) *dest++ = src[i];
      return result;
    }

    return (is_one_byte_data_in_two_byte_string)
        ? ConcatStringContent<uint8_t>(NewRawOneByteString(length), left, right)
        : ConcatStringContent<uc16>(NewRawTwoByteString(length), left, right);
  }

  Handle<ConsString> result = NewRawConsString(
      (is_one_byte || is_one_byte_data_in_two_byte_string)
          ? String::ONE_BYTE_ENCODING
          : String::TWO_BYTE_ENCODING);

  DisallowHeapAllocation no_gc;
  WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);

  result->set_hash_field(String::kEmptyHashField);
  result->set_length(length);
  result->set_first(*left, mode);
  result->set_second(*right, mode);
  return result;
}


444 445 446
Handle<String> Factory::NewFlatConcatString(Handle<String> first,
                                            Handle<String> second) {
  int total_length = first->length() + second->length();
447
  if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
448 449 450 451 452 453 454 455 456
    return ConcatStringContent<uint8_t>(
        NewRawOneByteString(total_length), first, second);
  } else {
    return ConcatStringContent<uc16>(
        NewRawTwoByteString(total_length), first, second);
  }
}


457 458 459
Handle<SlicedString> Factory::NewRawSlicedString(String::Encoding encoding) {
  Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
      ? sliced_ascii_string_map() : sliced_string_map();
460
  CALL_HEAP_FUNCTION(isolate(),
461 462
                     isolate()->heap()->Allocate(*map, NEW_SPACE),
                     SlicedString);
463 464 465
}


466
Handle<String> Factory::NewProperSubString(Handle<String> str,
467 468
                                           int begin,
                                           int end) {
469 470 471
#if VERIFY_HEAP
  if (FLAG_verify_heap) str->StringVerify();
#endif
472
  ASSERT(begin > 0 || end < str->length());
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

  int length = end - begin;
  if (length <= 0) return empty_string();
  if (length == 1) {
    return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
  }
  if (length == 2) {
    // Optimization for 2-byte strings often used as keys in a decompression
    // dictionary.  Check whether we already have the string in the string
    // table to prevent creation of many unnecessary strings.
    uint16_t c1 = str->Get(begin);
    uint16_t c2 = str->Get(begin + 1);
    return MakeOrFindTwoCharacterString(isolate(), c1, c2);
  }

  if (!FLAG_string_slices || length < SlicedString::kMinLength) {
    if (str->IsOneByteRepresentation()) {
      Handle<SeqOneByteString> result = NewRawOneByteString(length);
      uint8_t* dest = result->GetChars();
      DisallowHeapAllocation no_gc;
      String::WriteToFlat(*str, dest, begin, end);
      return result;
    } else {
      Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
      uc16* dest = result->GetChars();
      DisallowHeapAllocation no_gc;
      String::WriteToFlat(*str, dest, begin, end);
      return result;
    }
  }

  int offset = begin;

  while (str->IsConsString()) {
    Handle<ConsString> cons = Handle<ConsString>::cast(str);
    int split = cons->first()->length();
    if (split <= offset) {
      // Slice is fully contained in the second part.
      str = Handle<String>(cons->second(), isolate());
      offset -= split;  // Adjust for offset.
      continue;
    } else if (offset + length <= split) {
      // Slice is fully contained in the first part.
      str = Handle<String>(cons->first(), isolate());
      continue;
    }
    break;
  }

  if (str->IsSlicedString()) {
    Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
    str = Handle<String>(slice->parent(), isolate());
    offset += slice->offset();
  } else {
    str = FlattenGetString(str);
  }

  ASSERT(str->IsSeqString() || str->IsExternalString());
  Handle<SlicedString> slice = NewRawSlicedString(
      str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
                                     : String::TWO_BYTE_ENCODING);

  slice->set_hash_field(String::kEmptyHashField);
  slice->set_length(length);
  slice->set_parent(*str);
  slice->set_offset(offset);
  return slice;
540 541 542
}


543
Handle<String> Factory::NewExternalStringFromAscii(
544
    const ExternalAsciiString::Resource* resource) {
545 546 547 548
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalStringFromAscii(resource),
      String);
549 550 551 552
}


Handle<String> Factory::NewExternalStringFromTwoByte(
553
    const ExternalTwoByteString::Resource* resource) {
554 555 556 557
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
      String);
558 559 560
}


561 562 563 564 565 566 567 568
Handle<Symbol> Factory::NewSymbol() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateSymbol(),
      Symbol);
}


569 570 571 572 573 574 575 576
Handle<Symbol> Factory::NewPrivateSymbol() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocatePrivateSymbol(),
      Symbol);
}


577
Handle<Context> Factory::NewNativeContext() {
578 579
  CALL_HEAP_FUNCTION(
      isolate(),
580
      isolate()->heap()->AllocateNativeContext(),
581
      Context);
582 583 584
}


585 586 587 588 589 590 591 592 593
Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
                                          Handle<ScopeInfo> scope_info) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
      Context);
}


594
Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
595 596
  CALL_HEAP_FUNCTION(
      isolate(),
597
      isolate()->heap()->AllocateModuleContext(*scope_info),
598 599 600 601
      Context);
}


602
Handle<Context> Factory::NewFunctionContext(int length,
603
                                            Handle<JSFunction> function) {
604 605
  CALL_HEAP_FUNCTION(
      isolate(),
606
      isolate()->heap()->AllocateFunctionContext(length, *function),
607
      Context);
608 609 610
}


611 612
Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
613 614
                                         Handle<String> name,
                                         Handle<Object> thrown_object) {
615 616
  CALL_HEAP_FUNCTION(
      isolate(),
617 618 619 620
      isolate()->heap()->AllocateCatchContext(*function,
                                              *previous,
                                              *name,
                                              *thrown_object),
621 622 623 624
      Context);
}


625 626
Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
                                        Handle<Context> previous,
627
                                        Handle<JSObject> extension) {
628 629
  CALL_HEAP_FUNCTION(
      isolate(),
630
      isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
631
      Context);
632 633 634
}


635 636 637
Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
                                         Handle<ScopeInfo> scope_info) {
638 639 640 641 642 643 644 645 646
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateBlockContext(*function,
                                              *previous,
                                              *scope_info),
      Context);
}


647
Handle<Struct> Factory::NewStruct(InstanceType type) {
648 649 650 651
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateStruct(type),
      Struct);
652 653 654
}


655 656 657 658 659 660 661 662 663
Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
    int aliased_context_slot) {
  Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
      NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
  entry->set_aliased_context_slot(aliased_context_slot);
  return entry;
}


664 665 666 667 668 669
Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
  return Handle<DeclaredAccessorDescriptor>::cast(
      NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
}


670 671 672 673 674 675 676 677 678 679 680 681 682
Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
  Handle<DeclaredAccessorInfo> info =
      Handle<DeclaredAccessorInfo>::cast(
          NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
  return info;
}


Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
  Handle<ExecutableAccessorInfo> info =
      Handle<ExecutableAccessorInfo>::cast(
          NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
683 684 685 686 687 688
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
  return info;
}


Handle<Script> Factory::NewScript(Handle<String> source) {
689
  // Generate id for this script.
690
  Heap* heap = isolate()->heap();
691 692 693
  int id = heap->last_script_id()->value() + 1;
  if (!Smi::IsValid(id) || id < 0) id = 1;
  heap->set_last_script_id(Smi::FromInt(id));
694

695
  // Create and initialize script object.
696
  Handle<Foreign> wrapper = NewForeign(0, TENURED);
697 698
  Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
  script->set_source(*source);
699
  script->set_name(heap->undefined_value());
700
  script->set_id(Smi::FromInt(id));
701 702
  script->set_line_offset(Smi::FromInt(0));
  script->set_column_offset(Smi::FromInt(0));
703 704
  script->set_data(heap->undefined_value());
  script->set_context_data(heap->undefined_value());
705
  script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
706
  script->set_wrapper(*wrapper);
707 708
  script->set_line_ends(heap->undefined_value());
  script->set_eval_from_shared(heap->undefined_value());
709
  script->set_eval_from_instructions_offset(Smi::FromInt(0));
710
  script->set_flags(Smi::FromInt(0));
711

712 713 714 715
  return script;
}


716
Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
717
  CALL_HEAP_FUNCTION(isolate(),
718 719
                     isolate()->heap()->AllocateForeign(addr, pretenure),
                     Foreign);
720 721 722
}


723 724
Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
  return NewForeign((Address) desc, TENURED);
725 726 727
}


728
Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
729
  ASSERT(0 <= length);
730 731 732 733
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateByteArray(length, pretenure),
      ByteArray);
734 735 736
}


737 738 739 740
Handle<ExternalArray> Factory::NewExternalArray(int length,
                                                ExternalArrayType array_type,
                                                void* external_pointer,
                                                PretenureFlag pretenure) {
741
  ASSERT(0 <= length && length <= Smi::kMaxValue);
742 743 744 745 746 747 748
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalArray(length,
                                               array_type,
                                               external_pointer,
                                               pretenure),
      ExternalArray);
749 750 751
}


752 753 754 755 756 757 758 759 760 761 762 763 764 765
Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
    int length,
    ExternalArrayType array_type,
    PretenureFlag pretenure) {
  ASSERT(0 <= length && length <= Smi::kMaxValue);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedTypedArray(length,
                                                 array_type,
                                                 pretenure),
      FixedTypedArrayBase);
}


766 767 768 769 770 771 772 773 774
Handle<Cell> Factory::NewCell(Handle<Object> value) {
  AllowDeferredHandleDereference convert_to_cell;
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateCell(*value),
      Cell);
}


775
Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
776 777
  CALL_HEAP_FUNCTION(
      isolate(),
778
      isolate()->heap()->AllocatePropertyCell(),
779
      PropertyCell);
780 781 782
}


783 784 785 786 787 788 789 790
Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
  AllowDeferredHandleDereference convert_to_cell;
  Handle<PropertyCell> cell = NewPropertyCellWithHole();
  PropertyCell::SetValueInferType(cell, value);
  return cell;
}


791 792 793 794 795 796 797 798
Handle<AllocationSite> Factory::NewAllocationSite() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateAllocationSite(),
      AllocationSite);
}


799 800 801
Handle<Map> Factory::NewMap(InstanceType type,
                            int instance_size,
                            ElementsKind elements_kind) {
802 803
  CALL_HEAP_FUNCTION(
      isolate(),
804
      isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
805
      Map);
806 807 808 809
}


Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  // Make sure to use globals from the function's context, since the function
  // can be from a different context.
  Handle<Context> native_context(function->context()->native_context());
  Handle<Map> new_map;
  if (function->shared()->is_generator()) {
    // Generator prototypes can share maps since they don't have "constructor"
    // properties.
    new_map = handle(native_context->generator_object_prototype_map());
  } else {
    // Each function prototype gets a fresh map to avoid unwanted sharing of
    // maps between prototypes of different constructors.
    Handle<JSFunction> object_function(native_context->object_function());
    ASSERT(object_function->has_initial_map());
    new_map = Map::Copy(handle(object_function->initial_map()));
  }

  Handle<JSObject> prototype = NewJSObjectFromMap(new_map);

  if (!function->shared()->is_generator()) {
    JSObject::SetLocalPropertyIgnoreAttributes(prototype,
                                               constructor_string(),
                                               function,
                                               DONT_ENUM);
  }

  return prototype;
836 837 838
}


839 840 841
Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
  CALL_HEAP_FUNCTION(
      isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
842 843 844
}


845 846
Handle<Map> Factory::CopyMap(Handle<Map> src,
                             int extra_inobject_properties) {
847
  Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
848 849 850 851 852
  // Check that we do not overflow the instance size when adding the
  // extra inobject properties.
  int instance_size_delta = extra_inobject_properties * kPointerSize;
  int max_instance_size_delta =
      JSObject::kMaxInstanceSize - copy->instance_size();
853 854
  int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
  if (extra_inobject_properties > max_extra_properties) {
855 856 857
    // If the instance size overflows, we allocate as many properties
    // as we can as inobject properties.
    instance_size_delta = max_instance_size_delta;
858
    extra_inobject_properties = max_extra_properties;
859 860 861 862 863 864 865
  }
  // Adjust the map with the extra inobject properties.
  int inobject_properties =
      copy->inobject_properties() + extra_inobject_properties;
  copy->set_inobject_properties(inobject_properties);
  copy->set_unused_property_fields(inobject_properties);
  copy->set_instance_size(copy->instance_size() + instance_size_delta);
866
  copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
867 868 869
  return copy;
}

870

871
Handle<Map> Factory::CopyMap(Handle<Map> src) {
872
  CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
873 874 875
}


876
Handle<Map> Factory::GetElementsTransitionMap(
877 878
    Handle<JSObject> src,
    ElementsKind elements_kind) {
879 880 881
  Isolate* i = isolate();
  CALL_HEAP_FUNCTION(i,
                     src->GetElementsTransitionMap(i, elements_kind),
882
                     Map);
883 884 885
}


886
Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
887
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
888 889 890
}


891
Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
892 893 894 895 896
                                               int new_length,
                                               PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(isolate(),
                     array->CopySize(new_length, pretenure),
                     FixedArray);
897 898 899
}


900 901 902 903 904 905
Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
    Handle<FixedDoubleArray> array) {
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
}


906 907 908 909 910 911
Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
    Handle<ConstantPoolArray> array) {
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
}


912 913
Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
    Handle<SharedFunctionInfo> function_info,
914 915
    Handle<Map> function_map,
    PretenureFlag pretenure) {
916 917 918 919 920 921
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFunction(*function_map,
                                          *function_info,
                                          isolate()->heap()->the_hole_value(),
                                          pretenure),
922 923 924 925
                     JSFunction);
}


926 927 928 929 930 931 932 933 934
static Handle<Map> MapForNewFunction(Isolate *isolate,
                                     Handle<SharedFunctionInfo> function_info) {
  Context *context = isolate->context()->native_context();
  int map_index = Context::FunctionMapIndex(function_info->language_mode(),
                                            function_info->is_generator());
  return Handle<Map>(Map::cast(context->get(map_index)));
}


935 936
Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    Handle<SharedFunctionInfo> function_info,
937 938
    Handle<Context> context,
    PretenureFlag pretenure) {
939
  Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
940
      function_info,
941
      MapForNewFunction(isolate(), function_info),
942 943
      pretenure);

944 945 946 947
  if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
    function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
  }

948
  result->set_context(*context);
949

950 951
  int index = function_info->SearchOptimizedCodeMap(context->native_context(),
                                                    BailoutId::None());
952 953 954 955
  if (!function_info->bound() && index < 0) {
    int number_of_literals = function_info->num_literals();
    Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
    if (number_of_literals > 0) {
956
      // Store the native context in the literals array prefix. This
957 958
      // context will be used when creating object, regexp and array
      // literals in this function.
959 960
      literals->set(JSFunction::kLiteralNativeContextIndex,
                    context->native_context());
961
    }
962
    result->set_literals(*literals);
963
  }
964 965 966

  if (index > 0) {
    // Caching of optimized code enabled and optimized code found.
967 968 969 970
    FixedArray* literals =
        function_info->GetLiteralsFromOptimizedCodeMap(index);
    if (literals != NULL) result->set_literals(literals);
    result->ReplaceCode(function_info->GetCodeFromOptimizedCodeMap(index));
971 972 973
    return result;
  }

974
  if (isolate()->use_crankshaft() &&
975 976 977
      FLAG_always_opt &&
      result->is_compiled() &&
      !function_info->is_toplevel() &&
978
      function_info->allows_lazy_compilation() &&
979 980
      !function_info->optimization_disabled() &&
      !isolate()->DebuggerHasBreakPoints()) {
981
    result->MarkForOptimization();
982
  }
983 984 985 986 987 988
  return result;
}


Handle<Object> Factory::NewNumber(double value,
                                  PretenureFlag pretenure) {
989 990 991
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->NumberFromDouble(value, pretenure), Object);
992 993 994
}


995 996
Handle<Object> Factory::NewNumberFromInt(int32_t value,
                                         PretenureFlag pretenure) {
997 998
  CALL_HEAP_FUNCTION(
      isolate(),
999
      isolate()->heap()->NumberFromInt32(value, pretenure), Object);
1000 1001 1002
}


1003 1004
Handle<Object> Factory::NewNumberFromUint(uint32_t value,
                                         PretenureFlag pretenure) {
1005 1006
  CALL_HEAP_FUNCTION(
      isolate(),
1007
      isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1008 1009 1010
}


1011 1012 1013 1014 1015 1016 1017 1018
Handle<HeapNumber> Factory::NewHeapNumber(double value,
                                          PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
}


1019
Handle<JSObject> Factory::NewNeanderObject() {
1020 1021 1022 1023 1024
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObjectFromMap(
          isolate()->heap()->neander_map()),
      JSObject);
1025 1026 1027
}


1028
Handle<Object> Factory::NewTypeError(const char* message,
1029
                                     Vector< Handle<Object> > args) {
1030
  return NewError("MakeTypeError", message, args);
1031 1032 1033 1034 1035 1036 1037 1038
}


Handle<Object> Factory::NewTypeError(Handle<String> message) {
  return NewError("$TypeError", message);
}


1039
Handle<Object> Factory::NewRangeError(const char* message,
1040
                                      Vector< Handle<Object> > args) {
1041
  return NewError("MakeRangeError", message, args);
1042 1043 1044 1045 1046 1047 1048 1049
}


Handle<Object> Factory::NewRangeError(Handle<String> message) {
  return NewError("$RangeError", message);
}


1050 1051 1052
Handle<Object> Factory::NewSyntaxError(const char* message,
                                       Handle<JSArray> args) {
  return NewError("MakeSyntaxError", message, args);
1053 1054 1055 1056 1057 1058 1059 1060
}


Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
  return NewError("$SyntaxError", message);
}


1061
Handle<Object> Factory::NewReferenceError(const char* message,
1062
                                          Vector< Handle<Object> > args) {
1063
  return NewError("MakeReferenceError", message, args);
1064 1065 1066 1067 1068 1069 1070 1071
}


Handle<Object> Factory::NewReferenceError(Handle<String> message) {
  return NewError("$ReferenceError", message);
}


1072
Handle<Object> Factory::NewError(const char* maker,
1073
                                 const char* message,
1074 1075
                                 Vector< Handle<Object> > args) {
  // Instantiate a closeable HandleScope for EscapeFrom.
1076
  v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1077
  Handle<FixedArray> array = NewFixedArray(args.length());
1078 1079 1080
  for (int i = 0; i < args.length(); i++) {
    array->set(i, *args[i]);
  }
1081
  Handle<JSArray> object = NewJSArrayWithElements(array);
1082
  Handle<Object> result = NewError(maker, message, object);
1083 1084 1085 1086
  return result.EscapeFrom(&scope);
}


1087
Handle<Object> Factory::NewEvalError(const char* message,
1088
                                     Vector< Handle<Object> > args) {
1089
  return NewError("MakeEvalError", message, args);
1090 1091 1092
}


1093
Handle<Object> Factory::NewError(const char* message,
1094
                                 Vector< Handle<Object> > args) {
1095
  return NewError("MakeError", message, args);
1096 1097 1098
}


1099
Handle<String> Factory::EmergencyNewError(const char* message,
1100 1101 1102 1103 1104 1105 1106
                                          Handle<JSArray> args) {
  const int kBufferSize = 1000;
  char buffer[kBufferSize];
  size_t space = kBufferSize;
  char* p = &buffer[0];

  Vector<char> v(buffer, kBufferSize);
1107 1108
  OS::StrNCpy(v, message, space);
  space -= Min(space, strlen(message));
1109 1110 1111 1112 1113 1114 1115
  p = &buffer[kBufferSize] - space;

  for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
    if (space > 0) {
      *p++ = ' ';
      space--;
      if (space > 0) {
1116
        MaybeObject* maybe_arg = args->GetElement(isolate(), i);
1117
        Handle<String> arg_str(reinterpret_cast<String*>(maybe_arg));
1118
        SmartArrayPointer<char> arg = arg_str->ToCString();
1119
        Vector<char> v2(p, static_cast<int>(space));
1120 1121
        OS::StrNCpy(v2, arg.get(), space);
        space -= Min(space, strlen(arg.get()));
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
        p = &buffer[kBufferSize] - space;
      }
    }
  }
  if (space > 0) {
    *p = '\0';
  } else {
    buffer[kBufferSize - 1] = '\0';
  }
  Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
  return error_string;
}


1136
Handle<Object> Factory::NewError(const char* maker,
1137
                                 const char* message,
1138
                                 Handle<JSArray> args) {
1139
  Handle<String> make_str = InternalizeUtf8String(maker);
1140
  Handle<Object> fun_obj(
1141 1142
      isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
      isolate());
1143 1144
  // If the builtins haven't been properly configured yet this error
  // constructor may not have been defined.  Bail out.
1145
  if (!fun_obj->IsJSFunction()) {
1146
    return EmergencyNewError(message, args);
1147
  }
1148
  Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1149 1150
  Handle<Object> message_obj = InternalizeUtf8String(message);
  Handle<Object> argv[] = { message_obj, args };
1151 1152 1153 1154 1155

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
  bool caught_exception;
  Handle<Object> result = Execution::TryCall(fun,
1156 1157 1158 1159
                                             isolate()->js_builtins_object(),
                                             ARRAY_SIZE(argv),
                                             argv,
                                             &caught_exception);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
  return result;
}


Handle<Object> Factory::NewError(Handle<String> message) {
  return NewError("$Error", message);
}


Handle<Object> Factory::NewError(const char* constructor,
                                 Handle<String> message) {
1171
  Handle<String> constr = InternalizeUtf8String(constructor);
1172 1173 1174
  Handle<JSFunction> fun = Handle<JSFunction>(
      JSFunction::cast(isolate()->js_builtins_object()->
                       GetPropertyNoExceptionThrown(*constr)));
1175
  Handle<Object> argv[] = { message };
1176 1177 1178 1179 1180

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
  bool caught_exception;
  Handle<Object> result = Execution::TryCall(fun,
1181 1182 1183 1184
                                             isolate()->js_builtins_object(),
                                             ARRAY_SIZE(argv),
                                             argv,
                                             &caught_exception);
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  return result;
}


Handle<JSFunction> Factory::NewFunction(Handle<String> name,
                                        InstanceType type,
                                        int instance_size,
                                        Handle<Code> code,
                                        bool force_initial_map) {
  // Allocate the function
  Handle<JSFunction> function = NewFunction(name, the_hole_value());
1196

1197
  // Set up the code pointer in both the shared function info and in
1198 1199
  // the function itself.
  function->shared()->set_code(*code);
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
  function->set_code(*code);

  if (force_initial_map ||
      type != JS_OBJECT_TYPE ||
      instance_size != JSObject::kHeaderSize) {
    Handle<Map> initial_map = NewMap(type, instance_size);
    Handle<JSObject> prototype = NewFunctionPrototype(function);
    initial_map->set_prototype(*prototype);
    function->set_initial_map(*initial_map);
    initial_map->set_constructor(*function);
  } else {
    ASSERT(!function->has_initial_map());
    ASSERT(!function->has_prototype());
  }

  return function;
}


Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
                                                     InstanceType type,
                                                     int instance_size,
                                                     Handle<JSObject> prototype,
                                                     Handle<Code> code,
                                                     bool force_initial_map) {
1225
  // Allocate the function.
1226 1227
  Handle<JSFunction> function = NewFunction(name, prototype);

1228
  // Set up the code pointer in both the shared function info and in
1229 1230
  // the function itself.
  function->shared()->set_code(*code);
1231 1232 1233 1234 1235
  function->set_code(*code);

  if (force_initial_map ||
      type != JS_OBJECT_TYPE ||
      instance_size != JSObject::kHeaderSize) {
1236 1237
    Handle<Map> initial_map = NewMap(type,
                                     instance_size,
1238
                                     GetInitialFastElementsKind());
1239 1240 1241 1242
    function->set_initial_map(*initial_map);
    initial_map->set_constructor(*function);
  }

1243
  JSFunction::SetPrototype(function, prototype);
1244 1245 1246
  return function;
}

1247

1248 1249
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
                                                        Handle<Code> code) {
1250
  Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
1251
                                                            CLASSIC_MODE);
1252
  function->shared()->set_code(*code);
1253 1254 1255 1256 1257 1258 1259
  function->set_code(*code);
  ASSERT(!function->has_initial_map());
  ASSERT(!function->has_prototype());
  return function;
}


1260
Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1261 1262
  CALL_HEAP_FUNCTION(
      isolate(),
1263 1264
      isolate()->heap()->AllocateScopeInfo(length),
      ScopeInfo);
1265 1266 1267
}


1268 1269 1270 1271 1272 1273 1274
Handle<JSObject> Factory::NewExternal(void* value) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateExternal(value),
                     JSObject);
}


1275 1276
Handle<Code> Factory::NewCode(const CodeDesc& desc,
                              Code::Flags flags,
1277
                              Handle<Object> self_ref,
1278
                              bool immovable,
1279 1280
                              bool crankshafted,
                              int prologue_offset) {
1281 1282
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CreateCode(
1283 1284
                         desc, flags, self_ref, immovable, crankshafted,
                         prologue_offset),
1285
                     Code);
1286 1287 1288 1289
}


Handle<Code> Factory::CopyCode(Handle<Code> code) {
1290 1291 1292
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code),
                     Code);
1293 1294 1295
}


1296
Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1297 1298 1299
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code, reloc_info),
                     Code);
1300 1301 1302
}


1303
Handle<String> Factory::InternalizedStringFromString(Handle<String> value) {
1304
  CALL_HEAP_FUNCTION(isolate(),
1305
                     isolate()->heap()->InternalizeString(*value), String);
1306 1307 1308 1309 1310
}


Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
                                      PretenureFlag pretenure) {
1311
  JSFunction::EnsureHasInitialMap(constructor);
1312 1313 1314
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1315 1316 1317
}


1318 1319
Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
                                      Handle<ScopeInfo> scope_info) {
1320 1321
  CALL_HEAP_FUNCTION(
      isolate(),
1322
      isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1323 1324 1325
}


1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
// TODO(mstarzinger): Temporary wrapper until handlified.
static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
                                                Handle<Name> name,
                                                Handle<Object> value,
                                                PropertyDetails details) {
  CALL_HEAP_FUNCTION(dict->GetIsolate(),
                     dict->Add(*name, *value, details),
                     NameDictionary);
}


static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
                                                   Handle<Map> map) {
  CALL_HEAP_FUNCTION(isolate,
                     isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1341
                     GlobalObject);
1342 1343 1344
}


1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
  ASSERT(constructor->has_initial_map());
  Handle<Map> map(constructor->initial_map());
  ASSERT(map->is_dictionary_map());

  // Make sure no field properties are described in the initial map.
  // This guarantees us that normalizing the properties does not
  // require us to change property values to PropertyCells.
  ASSERT(map->NextFreePropertyIndex() == 0);

  // Make sure we don't have a ton of pre-allocated slots in the
  // global objects. They will be unused once we normalize the object.
  ASSERT(map->unused_property_fields() == 0);
  ASSERT(map->inobject_properties() == 0);

  // Initial size of the backing store to avoid resize of the storage during
  // bootstrapping. The size differs between the JS global object ad the
  // builtins object.
  int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;

  // Allocate a dictionary object for backing storage.
  int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
  Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);

  // The global object might be created from an object template with accessors.
  // Fill these accessors into the dictionary.
  Handle<DescriptorArray> descs(map->instance_descriptors());
  for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
    PropertyDetails details = descs->GetDetails(i);
    ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
    PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
    Handle<Name> name(descs->GetKey(i));
    Handle<Object> value(descs->GetCallbacksObject(i), isolate());
    Handle<PropertyCell> cell = NewPropertyCell(value);
    NameDictionaryAdd(dictionary, name, cell, d);
  }

  // Allocate the global object and initialize it with the backing store.
  Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
  isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);

  // Create a new map for the global object.
  Handle<Map> new_map = Map::CopyDropDescriptors(map);
  new_map->set_dictionary_map(true);

  // Set up the global object as a normalized object.
  global->set_map(*new_map);
  global->set_properties(*dictionary);

  // Make sure result is a global object with properties in dictionary.
  ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
  return global;
}

1399

1400
Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map,
1401 1402
                                             PretenureFlag pretenure,
                                             bool alloc_props) {
1403 1404
  CALL_HEAP_FUNCTION(
      isolate(),
1405
      isolate()->heap()->AllocateJSObjectFromMap(*map, pretenure, alloc_props),
1406
      JSObject);
1407 1408 1409
}


1410
Handle<JSArray> Factory::NewJSArray(int capacity,
1411
                                    ElementsKind elements_kind,
1412
                                    PretenureFlag pretenure) {
1413 1414 1415
  if (capacity != 0) {
    elements_kind = GetHoleyElementsKind(elements_kind);
  }
1416
  CALL_HEAP_FUNCTION(isolate(),
1417 1418 1419 1420 1421 1422
                     isolate()->heap()->AllocateJSArrayAndStorage(
                         elements_kind,
                         0,
                         capacity,
                         INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
                         pretenure),
1423
                     JSArray);
1424 1425 1426
}


1427
Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1428
                                                ElementsKind elements_kind,
1429
                                                PretenureFlag pretenure) {
1430 1431 1432 1433
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSArrayWithElements(*elements,
                                                     elements_kind,
1434
                                                     elements->length(),
1435 1436
                                                     pretenure),
      JSArray);
1437 1438 1439
}


1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
                                           int capacity,
                                           int length) {
  ElementsAccessor* accessor = array->GetElementsAccessor();
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      accessor->SetCapacityAndLength(*array, capacity, length));
}


1450
void Factory::SetContent(Handle<JSArray> array,
1451
                         Handle<FixedArrayBase> elements) {
1452 1453 1454 1455 1456 1457
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      array->SetContent(*elements));
}


1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
    Handle<JSFunction> function) {
  ASSERT(function->shared()->is_generator());
  JSFunction::EnsureHasInitialMap(function);
  Handle<Map> map(function->initial_map());
  ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObjectFromMap(*map),
      JSGeneratorObject);
}


1471
Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1472 1473
  Handle<JSFunction> array_buffer_fun(
      isolate()->context()->native_context()->array_buffer_fun());
1474 1475
  CALL_HEAP_FUNCTION(
      isolate(),
1476
      isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1477 1478 1479 1480
      JSArrayBuffer);
}


1481
Handle<JSDataView> Factory::NewJSDataView() {
1482 1483
  Handle<JSFunction> data_view_fun(
      isolate()->context()->native_context()->data_view_fun());
1484 1485
  CALL_HEAP_FUNCTION(
      isolate(),
1486
      isolate()->heap()->AllocateJSObject(*data_view_fun),
1487 1488 1489 1490
      JSDataView);
}


1491 1492 1493
static JSFunction* GetTypedArrayFun(ExternalArrayType type,
                                    Isolate* isolate) {
  Context* native_context = isolate->context()->native_context();
1494
  switch (type) {
1495 1496 1497
#define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
    case kExternal##Type##Array:                                              \
      return native_context->type##_array_fun();
1498

1499 1500
    TYPED_ARRAYS(TYPED_ARRAY_FUN)
#undef TYPED_ARRAY_FUN
1501

1502 1503
    default:
      UNREACHABLE();
1504
      return NULL;
1505
  }
1506 1507 1508 1509 1510
}


Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
  Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1511 1512 1513

  CALL_HEAP_FUNCTION(
      isolate(),
1514
      isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1515 1516 1517 1518
      JSTypedArray);
}


1519 1520 1521 1522 1523 1524 1525 1526 1527
Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
                                    Handle<Object> prototype) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSProxy(*handler, *prototype),
      JSProxy);
}


1528
void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1529 1530
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
      isolate()->heap()->ReinitializeJSReceiver(
          *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
}


void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      isolate()->heap()->ReinitializeJSReceiver(
          *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1541 1542 1543
}


1544
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1545 1546
    Handle<String> name,
    int number_of_literals,
1547
    bool is_generator,
1548
    Handle<Code> code,
1549
    Handle<ScopeInfo> scope_info) {
1550 1551
  Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
  shared->set_code(*code);
1552
  shared->set_scope_info(*scope_info);
1553 1554 1555 1556 1557 1558 1559 1560
  int literals_array_size = number_of_literals;
  // If the function contains object, regexp or array literals,
  // allocate extra space for a literals array prefix containing the
  // context.
  if (number_of_literals > 0) {
    literals_array_size += JSFunction::kLiteralsPrefixSize;
  }
  shared->set_num_literals(literals_array_size);
1561 1562
  if (is_generator) {
    shared->set_instance_class_name(isolate()->heap()->Generator_string());
1563
    shared->DisableOptimization(kGenerator);
1564
  }
1565 1566 1567 1568
  return shared;
}


1569 1570 1571 1572 1573 1574 1575
Handle<JSMessageObject> Factory::NewJSMessageObject(
    Handle<String> type,
    Handle<JSArray> arguments,
    int start_position,
    int end_position,
    Handle<Object> script,
    Handle<Object> stack_frames) {
1576 1577 1578 1579 1580 1581 1582
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateJSMessageObject(*type,
                         *arguments,
                         start_position,
                         end_position,
                         *script,
                         *stack_frames),
1583 1584 1585
                     JSMessageObject);
}

1586

1587
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1588 1589
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateSharedFunctionInfo(*name),
1590 1591 1592 1593
                     SharedFunctionInfo);
}


1594
Handle<String> Factory::NumberToString(Handle<Object> number) {
1595 1596
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->NumberToString(*number), String);
1597 1598 1599
}


1600 1601 1602 1603 1604 1605
Handle<String> Factory::Uint32ToString(uint32_t value) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->Uint32ToString(value), String);
}


1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
    Handle<SeededNumberDictionary> dictionary,
    uint32_t key,
    Handle<Object> value) {
  CALL_HEAP_FUNCTION(isolate(),
                     dictionary->AtNumberPut(key, *value),
                     SeededNumberDictionary);
}


Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
    Handle<UnseededNumberDictionary> dictionary,
1618 1619
    uint32_t key,
    Handle<Object> value) {
1620 1621
  CALL_HEAP_FUNCTION(isolate(),
                     dictionary->AtNumberPut(key, *value),
1622
                     UnseededNumberDictionary);
1623 1624 1625 1626 1627 1628
}


Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
                                              Handle<Object> prototype) {
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1629 1630 1631 1632 1633 1634
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFunction(*isolate()->function_map(),
                                          *function_share,
                                          *prototype),
      JSFunction);
1635 1636 1637 1638 1639 1640
}


Handle<JSFunction> Factory::NewFunction(Handle<String> name,
                                        Handle<Object> prototype) {
  Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1641
  fun->set_context(isolate()->context()->native_context());
1642 1643 1644 1645
  return fun;
}


1646
Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1647
    Handle<String> name,
1648
    LanguageMode language_mode) {
1649
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1650 1651 1652
  Handle<Map> map = (language_mode == CLASSIC_MODE)
      ? isolate()->function_without_prototype_map()
      : isolate()->strict_mode_function_without_prototype_map();
1653 1654
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateFunction(
1655
                         *map,
1656 1657 1658 1659 1660 1661
                         *function_share,
                         *the_hole_value()),
                     JSFunction);
}


1662 1663
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
    Handle<String> name,
1664 1665 1666
    LanguageMode language_mode) {
  Handle<JSFunction> fun =
      NewFunctionWithoutPrototypeHelper(name, language_mode);
1667
  fun->set_context(isolate()->context()->native_context());
1668 1669 1670 1671
  return fun;
}


sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
1672
Handle<Object> Factory::ToObject(Handle<Object> object) {
1673
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
1674 1675 1676
}


1677
Handle<Object> Factory::ToObject(Handle<Object> object,
1678 1679
                                 Handle<Context> native_context) {
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1680 1681 1682
}


1683
#ifdef ENABLE_DEBUGGER_SUPPORT
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
  // Get the original code of the function.
  Handle<Code> code(shared->code());

  // Create a copy of the code before allocating the debug info object to avoid
  // allocation while setting up the debug info object.
  Handle<Code> original_code(*Factory::CopyCode(code));

  // Allocate initial fixed array for active break points before allocating the
  // debug info object to avoid allocation while setting up the debug info
  // object.
  Handle<FixedArray> break_points(
1696
      NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1697 1698 1699 1700 1701

  // Create and set up the debug info object. Debug info contains function, a
  // copy of the original code, the executing code and initial fixed array for
  // active break points.
  Handle<DebugInfo> debug_info =
1702
      Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
  debug_info->set_shared(*shared);
  debug_info->set_original_code(*original_code);
  debug_info->set_code(*code);
  debug_info->set_break_points(*break_points);

  // Link debug info to function.
  shared->set_debug_info(*debug_info);

  return debug_info;
}
1713
#endif
1714 1715


1716 1717
Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
                                             int length) {
1718 1719 1720
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1721 1722 1723 1724
}


Handle<JSFunction> Factory::CreateApiFunction(
1725
    Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1726 1727
  Handle<Code> code = isolate()->builtins()->HandleApiCall();
  Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1728

1729 1730 1731 1732 1733 1734 1735 1736 1737
  int internal_field_count = 0;
  if (!obj->instance_template()->IsUndefined()) {
    Handle<ObjectTemplateInfo> instance_template =
        Handle<ObjectTemplateInfo>(
            ObjectTemplateInfo::cast(obj->instance_template()));
    internal_field_count =
        Smi::cast(instance_template->internal_field_count())->value();
  }

1738 1739
  // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
  // JSObject::GetHeaderSize.
1740
  int instance_size = kPointerSize * internal_field_count;
1741
  InstanceType type;
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
  switch (instance_type) {
    case JavaScriptObject:
      type = JS_OBJECT_TYPE;
      instance_size += JSObject::kHeaderSize;
      break;
    case InnerGlobalObject:
      type = JS_GLOBAL_OBJECT_TYPE;
      instance_size += JSGlobalObject::kSize;
      break;
    case OuterGlobalObject:
      type = JS_GLOBAL_PROXY_TYPE;
      instance_size += JSGlobalProxy::kSize;
      break;
    default:
1756 1757
      UNREACHABLE();
      type = JS_OBJECT_TYPE;  // Keep the compiler happy.
1758
      break;
1759 1760 1761
  }

  Handle<JSFunction> result =
1762
      NewFunction(Factory::empty_string(),
1763 1764 1765 1766
                  type,
                  instance_size,
                  code,
                  true);
1767 1768 1769 1770

  // Set length.
  result->shared()->set_length(obj->length());

1771
  // Set class name.
1772
  Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
  if (class_name->IsString()) {
    result->shared()->set_instance_class_name(*class_name);
    result->shared()->set_name(*class_name);
  }

  Handle<Map> map = Handle<Map>(result->initial_map());

  // Mark as undetectable if needed.
  if (obj->undetectable()) {
    map->set_is_undetectable();
  }

  // Mark as hidden for the __proto__ accessor if needed.
  if (obj->hidden_prototype()) {
    map->set_is_hidden_prototype();
  }

  // Mark as needs_access_check if needed.
  if (obj->needs_access_check()) {
1792
    map->set_is_access_check_needed(true);
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
  }

  // Set interceptor information in the map.
  if (!obj->named_property_handler()->IsUndefined()) {
    map->set_has_named_interceptor();
  }
  if (!obj->indexed_property_handler()->IsUndefined()) {
    map->set_has_indexed_interceptor();
  }

  // Set instance call-as-function information in the map.
  if (!obj->instance_call_handler()->IsUndefined()) {
    map->set_has_instance_call_handler();
  }

  result->shared()->set_function_data(*obj);
1809
  result->shared()->set_construct_stub(*construct_stub);
1810
  result->shared()->DontAdaptArguments();
1811

1812 1813
  // Recursively copy parent instance templates' accessors,
  // 'data' may be modified.
1814
  int max_number_of_additional_properties = 0;
1815
  int max_number_of_static_properties = 0;
1816 1817
  FunctionTemplateInfo* info = *obj;
  while (true) {
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
    if (!info->instance_template()->IsUndefined()) {
      Object* props =
          ObjectTemplateInfo::cast(
              info->instance_template())->property_accessors();
      if (!props->IsUndefined()) {
        Handle<Object> props_handle(props, isolate());
        NeanderArray props_array(props_handle);
        max_number_of_additional_properties += props_array.length();
      }
    }
    if (!info->property_accessors()->IsUndefined()) {
      Object* props = info->property_accessors();
      if (!props->IsUndefined()) {
        Handle<Object> props_handle(props, isolate());
        NeanderArray props_array(props_handle);
        max_number_of_static_properties += props_array.length();
      }
1835 1836 1837 1838 1839 1840 1841 1842
    }
    Object* parent = info->parent_template();
    if (parent->IsUndefined()) break;
    info = FunctionTemplateInfo::cast(parent);
  }

  Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);

1843 1844 1845 1846 1847 1848 1849
  // Use a temporary FixedArray to acculumate static accessors
  int valid_descriptors = 0;
  Handle<FixedArray> array;
  if (max_number_of_static_properties > 0) {
    array = NewFixedArray(max_number_of_static_properties);
  }

1850
  while (true) {
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
    // Install instance descriptors
    if (!obj->instance_template()->IsUndefined()) {
      Handle<ObjectTemplateInfo> instance =
          Handle<ObjectTemplateInfo>(
              ObjectTemplateInfo::cast(obj->instance_template()), isolate());
      Handle<Object> props = Handle<Object>(instance->property_accessors(),
                                            isolate());
      if (!props->IsUndefined()) {
        Map::AppendCallbackDescriptors(map, props);
      }
    }
    // Accumulate static accessors
    if (!obj->property_accessors()->IsUndefined()) {
      Handle<Object> props = Handle<Object>(obj->property_accessors(),
                                            isolate());
      valid_descriptors =
          AccessorInfo::AppendUnique(props, array, valid_descriptors);
1868
    }
1869
    // Climb parent chain
1870
    Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1871 1872 1873 1874
    if (parent->IsUndefined()) break;
    obj = Handle<FunctionTemplateInfo>::cast(parent);
  }

1875 1876 1877 1878 1879 1880
  // Install accumulated static accessors
  for (int i = 0; i < valid_descriptors; i++) {
    Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
    JSObject::SetAccessor(result, accessor);
  }

1881
  ASSERT(result->shared()->IsApiFunction());
1882 1883 1884 1885
  return result;
}


1886
Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1887
  CALL_HEAP_FUNCTION(isolate(),
1888 1889 1890
                     MapCache::Allocate(isolate()->heap(),
                                        at_least_space_for),
                     MapCache);
1891 1892 1893
}


1894 1895 1896 1897 1898 1899 1900 1901 1902
MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
                                                       FixedArray* keys,
                                                       Map* map) {
  Object* result;
  { MaybeObject* maybe_result =
        MapCache::cast(context->map_cache())->Put(keys, map);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
  context->set_map_cache(MapCache::cast(result));
1903 1904 1905 1906 1907 1908 1909
  return result;
}


Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
                                        Handle<FixedArray> keys,
                                        Handle<Map> map) {
1910 1911
  CALL_HEAP_FUNCTION(isolate(),
                     UpdateMapCacheWith(*context, *keys, *map), MapCache);
1912 1913 1914 1915 1916 1917
}


Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
                                               Handle<FixedArray> keys) {
  if (context->map_cache()->IsUndefined()) {
1918
    // Allocate the new map cache for the native context.
1919 1920 1921
    Handle<MapCache> new_cache = NewMapCache(24);
    context->set_map_cache(*new_cache);
  }
1922
  // Check to see whether there is a matching element in the cache.
1923 1924
  Handle<MapCache> cache =
      Handle<MapCache>(MapCache::cast(context->map_cache()));
1925
  Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1926 1927 1928
  if (result->IsMap()) return Handle<Map>::cast(result);
  // Create a new map and add it to the cache.
  Handle<Map> map =
1929 1930
      CopyMap(Handle<Map>(context->object_function()->initial_map()),
              keys->length());
1931 1932 1933 1934 1935
  AddToMapCache(context, keys, map);
  return Handle<Map>(map);
}


1936 1937 1938 1939 1940 1941 1942
void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
                                JSRegExp::Type type,
                                Handle<String> source,
                                JSRegExp::Flags flags,
                                Handle<Object> data) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);

1943 1944 1945 1946 1947 1948 1949
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
  store->set(JSRegExp::kAtomPatternIndex, *data);
  regexp->set_data(*store);
}

1950 1951 1952 1953 1954 1955
void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
                                    JSRegExp::Type type,
                                    Handle<String> source,
                                    JSRegExp::Flags flags,
                                    int capture_count) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1956
  Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1957 1958 1959
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1960 1961 1962 1963
  store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
  store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
  store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
  store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1964 1965 1966 1967 1968 1969 1970
  store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
  store->set(JSRegExp::kIrregexpCaptureCountIndex,
             Smi::FromInt(capture_count));
  regexp->set_data(*store);
}


1971

1972 1973 1974 1975 1976
void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
                                Handle<JSObject> instance,
                                bool* pending_exception) {
  // Configure the instance by adding the properties specified by the
  // instance template.
1977
  Handle<Object> instance_template(desc->instance_template(), isolate());
1978
  if (!instance_template->IsUndefined()) {
1979 1980
    Execution::ConfigureInstance(isolate(),
                                 instance,
1981 1982 1983 1984 1985 1986 1987 1988
                                 instance_template,
                                 pending_exception);
  } else {
    *pending_exception = false;
  }
}


1989 1990
Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
  Heap* h = isolate()->heap();
1991 1992 1993
  if (name->Equals(h->undefined_string())) return undefined_value();
  if (name->Equals(h->nan_string())) return nan_value();
  if (name->Equals(h->infinity_string())) return infinity_value();
1994 1995 1996 1997
  return Handle<Object>::null();
}


1998
Handle<Object> Factory::ToBoolean(bool value) {
1999
  return value ? true_value() : false_value();
2000 2001 2002
}


2003
} }  // namespace v8::internal