runtime-literals.cc 26.9 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/ast/ast.h"
6
#include "src/common/globals.h"
7 8
#include "src/execution/arguments-inl.h"
#include "src/execution/isolate-inl.h"
9
#include "src/logging/counters.h"
10
#include "src/objects/allocation-site-scopes-inl.h"
11
#include "src/objects/hash-table-inl.h"
12
#include "src/objects/heap-number-inl.h"
13
#include "src/objects/heap-object-inl.h"
14
#include "src/objects/js-regexp-inl.h"
15
#include "src/objects/literal-objects-inl.h"
16
#include "src/runtime/runtime-utils.h"
17 18 19 20 21
#include "src/runtime/runtime.h"

namespace v8 {
namespace internal {

22
namespace {
23

24
bool IsUninitializedLiteralSite(Object literal_site) {
25
  return literal_site == Smi::zero();
26 27
}

28
bool HasBoilerplate(Handle<Object> literal_site) {
29 30
  return !literal_site->IsSmi();
}
31

32 33
void PreInitializeLiteralSite(Handle<FeedbackVector> vector,
                              FeedbackSlot slot) {
34
  vector->SynchronizedSet(slot, Smi::FromInt(1));
35 36
}

37 38 39 40 41 42 43 44
enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };

template <class ContextObject>
class JSObjectWalkVisitor {
 public:
  JSObjectWalkVisitor(ContextObject* site_context, DeepCopyHints hints)
      : site_context_(site_context), hints_(hints) {}

45 46
  V8_WARN_UNUSED_RESULT MaybeHandle<JSObject> StructureWalk(
      Handle<JSObject> object);
47 48

 protected:
49
  V8_WARN_UNUSED_RESULT inline MaybeHandle<JSObject> VisitElementOrProperty(
50
      Handle<JSObject> object, Handle<JSObject> value) {
51 52 53 54 55
    // Dont create allocation sites for nested object literals
    if (!value->IsJSArray()) {
      return StructureWalk(value);
    }

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    Handle<AllocationSite> current_site = site_context()->EnterNewScope();
    MaybeHandle<JSObject> copy_of_value = StructureWalk(value);
    site_context()->ExitScope(current_site, value);
    return copy_of_value;
  }

  inline ContextObject* site_context() { return site_context_; }
  inline Isolate* isolate() { return site_context()->isolate(); }

 private:
  ContextObject* site_context_;
  const DeepCopyHints hints_;
};

template <class ContextObject>
MaybeHandle<JSObject> JSObjectWalkVisitor<ContextObject>::StructureWalk(
    Handle<JSObject> object) {
  Isolate* isolate = this->isolate();
  bool copying = ContextObject::kCopying;
  bool shallow = hints_ == kObjectIsShallow;

  if (!shallow) {
    StackLimitCheck check(isolate);

    if (check.HasOverflowed()) {
      isolate->StackOverflow();
      return MaybeHandle<JSObject>();
    }
  }

86
  if (object->map(isolate).is_deprecated()) {
87
    JSObject::MigrateInstance(isolate, object);
88 89 90 91 92
  }

  Handle<JSObject> copy;
  if (copying) {
    // JSFunction objects are not allowed to be in normal boilerplates at all.
93
    DCHECK(!object->IsJSFunction(isolate));
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    Handle<AllocationSite> site_to_pass;
    if (site_context()->ShouldCreateMemento(object)) {
      site_to_pass = site_context()->current();
    }
    copy = isolate->factory()->CopyJSObjectWithAllocationSite(object,
                                                              site_to_pass);
  } else {
    copy = object;
  }

  DCHECK(copying || copy.is_identical_to(object));

  if (shallow) return copy;

  HandleScope scope(isolate);

  // Deep copy own properties. Arrays only have 1 property "length".
111 112 113
  if (!copy->IsJSArray(isolate)) {
    if (copy->HasFastProperties(isolate)) {
      Handle<DescriptorArray> descriptors(
114
          copy->map(isolate).instance_descriptors(isolate), isolate);
115
      for (InternalIndex i : copy->map(isolate).IterateOwnDescriptors()) {
116 117 118 119 120 121
        PropertyDetails details = descriptors->GetDetails(i);
        DCHECK_EQ(kField, details.location());
        DCHECK_EQ(kData, details.kind());
        FieldIndex index = FieldIndex::ForPropertyIndex(
            copy->map(isolate), details.field_index(),
            details.representation());
122 123
        Object raw = copy->RawFastPropertyAt(isolate, index);
        if (raw.IsJSObject(isolate)) {
124 125 126 127
          Handle<JSObject> value(JSObject::cast(raw), isolate);
          ASSIGN_RETURN_ON_EXCEPTION(
              isolate, value, VisitElementOrProperty(copy, value), JSObject);
          if (copying) copy->FastPropertyAtPut(index, *value);
128 129 130
        } else if (copying && details.representation().IsDouble()) {
          uint64_t double_value = HeapNumber::cast(raw).value_as_bits();
          auto value = isolate->factory()->NewHeapNumberFromBits(double_value);
131 132 133 134
          copy->FastPropertyAtPut(index, *value);
        }
      }
    } else {
135
      if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
136 137
        Handle<SwissNameDictionary> dict(
            copy->property_dictionary_swiss(isolate), isolate);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        for (InternalIndex i : dict->IterateEntries()) {
          Object raw = dict->ValueAt(i);
          if (!raw.IsJSObject(isolate)) continue;
          DCHECK(dict->KeyAt(i).IsName());
          Handle<JSObject> value(JSObject::cast(raw), isolate);
          ASSIGN_RETURN_ON_EXCEPTION(
              isolate, value, VisitElementOrProperty(copy, value), JSObject);
          if (copying) dict->ValueAtPut(i, *value);
        }
      } else {
        Handle<NameDictionary> dict(copy->property_dictionary(isolate),
                                    isolate);
        for (InternalIndex i : dict->IterateEntries()) {
          Object raw = dict->ValueAt(isolate, i);
          if (!raw.IsJSObject(isolate)) continue;
          DCHECK(dict->KeyAt(isolate, i).IsName());
          Handle<JSObject> value(JSObject::cast(raw), isolate);
          ASSIGN_RETURN_ON_EXCEPTION(
              isolate, value, VisitElementOrProperty(copy, value), JSObject);
          if (copying) dict->ValueAtPut(i, *value);
        }
159 160 161 162
      }
    }

    // Assume non-arrays don't end up having elements.
163
    if (copy->elements(isolate).length() == 0) return copy;
164 165 166
  }

  // Deep copy own elements.
167
  switch (copy->GetElementsKind(isolate)) {
168
    case PACKED_ELEMENTS:
169 170
    case PACKED_FROZEN_ELEMENTS:
    case PACKED_SEALED_ELEMENTS:
171
    case PACKED_NONEXTENSIBLE_ELEMENTS:
172 173
    case HOLEY_FROZEN_ELEMENTS:
    case HOLEY_SEALED_ELEMENTS:
174
    case HOLEY_NONEXTENSIBLE_ELEMENTS:
175
    case HOLEY_ELEMENTS: {
176 177 178 179
      Handle<FixedArray> elements(FixedArray::cast(copy->elements(isolate)),
                                  isolate);
      if (elements->map(isolate) ==
          ReadOnlyRoots(isolate).fixed_cow_array_map()) {
180 181
#ifdef DEBUG
        for (int i = 0; i < elements->length(); i++) {
182
          DCHECK(!elements->get(i).IsJSObject());
183 184 185 186
        }
#endif
      } else {
        for (int i = 0; i < elements->length(); i++) {
187 188
          Object raw = elements->get(isolate, i);
          if (!raw.IsJSObject(isolate)) continue;
189 190 191 192 193 194 195 196 197
          Handle<JSObject> value(JSObject::cast(raw), isolate);
          ASSIGN_RETURN_ON_EXCEPTION(
              isolate, value, VisitElementOrProperty(copy, value), JSObject);
          if (copying) elements->set(i, *value);
        }
      }
      break;
    }
    case DICTIONARY_ELEMENTS: {
198 199
      Handle<NumberDictionary> element_dictionary(
          copy->element_dictionary(isolate), isolate);
200
      for (InternalIndex i : element_dictionary->IterateEntries()) {
201 202
        Object raw = element_dictionary->ValueAt(isolate, i);
        if (!raw.IsJSObject(isolate)) continue;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        Handle<JSObject> value(JSObject::cast(raw), isolate);
        ASSIGN_RETURN_ON_EXCEPTION(
            isolate, value, VisitElementOrProperty(copy, value), JSObject);
        if (copying) element_dictionary->ValueAtPut(i, *value);
      }
      break;
    }
    case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
    case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
      UNIMPLEMENTED();
      break;
    case FAST_STRING_WRAPPER_ELEMENTS:
    case SLOW_STRING_WRAPPER_ELEMENTS:
      UNREACHABLE();

218
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) case TYPE##_ELEMENTS:
219 220 221 222 223 224

      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
      // Typed elements cannot be created using an object literal.
      UNREACHABLE();

225 226 227 228
    case PACKED_SMI_ELEMENTS:
    case HOLEY_SMI_ELEMENTS:
    case PACKED_DOUBLE_ELEMENTS:
    case HOLEY_DOUBLE_ELEMENTS:
229 230 231 232 233 234 235 236
    case NO_ELEMENTS:
      // No contained objects, nothing to do.
      break;
  }

  return copy;
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
class DeprecationUpdateContext {
 public:
  explicit DeprecationUpdateContext(Isolate* isolate) { isolate_ = isolate; }
  Isolate* isolate() { return isolate_; }
  bool ShouldCreateMemento(Handle<JSObject> object) { return false; }
  inline void ExitScope(Handle<AllocationSite> scope_site,
                        Handle<JSObject> object) {}
  Handle<AllocationSite> EnterNewScope() { return Handle<AllocationSite>(); }
  Handle<AllocationSite> current() {
    UNREACHABLE();
    return Handle<AllocationSite>();
  }

  static const bool kCopying = false;

 private:
  Isolate* isolate_;
};

256 257 258 259 260 261 262 263 264 265 266 267
// AllocationSiteCreationContext aids in the creation of AllocationSites to
// accompany object literals.
class AllocationSiteCreationContext : public AllocationSiteContext {
 public:
  explicit AllocationSiteCreationContext(Isolate* isolate)
      : AllocationSiteContext(isolate) {}

  Handle<AllocationSite> EnterNewScope() {
    Handle<AllocationSite> scope_site;
    if (top().is_null()) {
      // We are creating the top level AllocationSite as opposed to a nested
      // AllocationSite.
268
      InitializeTraversal(isolate()->factory()->NewAllocationSite(true));
269 270
      scope_site = Handle<AllocationSite>(*top(), isolate());
      if (FLAG_trace_creation_allocation_sites) {
271
        PrintF("*** Creating top level %s AllocationSite %p\n", "Fat",
272
               reinterpret_cast<void*>(scope_site->ptr()));
273 274 275
      }
    } else {
      DCHECK(!current().is_null());
276
      scope_site = isolate()->factory()->NewAllocationSite(false);
277
      if (FLAG_trace_creation_allocation_sites) {
278 279 280 281
        PrintF(
            "*** Creating nested %s AllocationSite (top, current, new) (%p, "
            "%p, "
            "%p)\n",
282 283 284
            "Slim", reinterpret_cast<void*>(top()->ptr()),
            reinterpret_cast<void*>(current()->ptr()),
            reinterpret_cast<void*>(scope_site->ptr()));
285 286 287 288 289 290 291 292 293
      }
      current()->set_nested_site(*scope_site);
      update_current_site(*scope_site);
    }
    DCHECK(!scope_site.is_null());
    return scope_site;
  }
  void ExitScope(Handle<AllocationSite> scope_site, Handle<JSObject> object) {
    if (object.is_null()) return;
294
    scope_site->set_boilerplate(*object);
295 296 297 298 299
    if (FLAG_trace_creation_allocation_sites) {
      bool top_level =
          !scope_site.is_null() && top().is_identical_to(scope_site);
      if (top_level) {
        PrintF("*** Setting AllocationSite %p transition_info %p\n",
300 301
               reinterpret_cast<void*>(scope_site->ptr()),
               reinterpret_cast<void*>(object->ptr()));
302
      } else {
303
        PrintF("*** Setting AllocationSite (%p, %p) transition_info %p\n",
304 305 306
               reinterpret_cast<void*>(top()->ptr()),
               reinterpret_cast<void*>(scope_site->ptr()),
               reinterpret_cast<void*>(object->ptr()));
307 308 309 310 311 312
      }
    }
  }
  static const bool kCopying = false;
};

313 314 315 316 317 318 319 320 321
MaybeHandle<JSObject> DeepWalk(Handle<JSObject> object,
                               DeprecationUpdateContext* site_context) {
  JSObjectWalkVisitor<DeprecationUpdateContext> v(site_context, kNoHints);
  MaybeHandle<JSObject> result = v.StructureWalk(object);
  Handle<JSObject> for_assert;
  DCHECK(!result.ToHandle(&for_assert) || for_assert.is_identical_to(object));
  return result;
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
MaybeHandle<JSObject> DeepWalk(Handle<JSObject> object,
                               AllocationSiteCreationContext* site_context) {
  JSObjectWalkVisitor<AllocationSiteCreationContext> v(site_context, kNoHints);
  MaybeHandle<JSObject> result = v.StructureWalk(object);
  Handle<JSObject> for_assert;
  DCHECK(!result.ToHandle(&for_assert) || for_assert.is_identical_to(object));
  return result;
}

MaybeHandle<JSObject> DeepCopy(Handle<JSObject> object,
                               AllocationSiteUsageContext* site_context,
                               DeepCopyHints hints) {
  JSObjectWalkVisitor<AllocationSiteUsageContext> v(site_context, hints);
  MaybeHandle<JSObject> copy = v.StructureWalk(object);
  Handle<JSObject> for_assert;
  DCHECK(!copy.ToHandle(&for_assert) || !for_assert.is_identical_to(object));
  return copy;
}

341 342 343 344 345 346 347 348 349 350
Handle<JSObject> CreateObjectLiteral(
    Isolate* isolate,
    Handle<ObjectBoilerplateDescription> object_boilerplate_description,
    int flags, AllocationType allocation);

Handle<JSObject> CreateArrayLiteral(
    Isolate* isolate,
    Handle<ArrayBoilerplateDescription> array_boilerplate_description,
    AllocationType allocation);

351
struct ObjectLiteralHelper {
352 353 354
  static inline Handle<JSObject> Create(Isolate* isolate,
                                        Handle<HeapObject> description,
                                        int flags, AllocationType allocation) {
355 356
    Handle<ObjectBoilerplateDescription> object_boilerplate_description =
        Handle<ObjectBoilerplateDescription>::cast(description);
357 358
    return CreateObjectLiteral(isolate, object_boilerplate_description, flags,
                               allocation);
359
  }
360 361
};

362
struct ArrayLiteralHelper {
363 364 365 366
  static inline Handle<JSObject> Create(Isolate* isolate,
                                        Handle<HeapObject> description,
                                        int flags_not_used,
                                        AllocationType allocation) {
367 368
    Handle<ArrayBoilerplateDescription> array_boilerplate_description =
        Handle<ArrayBoilerplateDescription>::cast(description);
369 370 371 372
    return CreateArrayLiteral(isolate, array_boilerplate_description,
                              allocation);
  }
};
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
Handle<JSObject> CreateObjectLiteral(
    Isolate* isolate,
    Handle<ObjectBoilerplateDescription> object_boilerplate_description,
    int flags, AllocationType allocation) {
  Handle<NativeContext> native_context = isolate->native_context();
  bool use_fast_elements = (flags & ObjectLiteral::kFastElements) != 0;
  bool has_null_prototype = (flags & ObjectLiteral::kHasNullPrototype) != 0;

  // In case we have function literals, we want the object to be in
  // slow properties mode for now. We don't go in the map cache because
  // maps with constant functions can't be shared if the functions are
  // not the same (which is the common case).
  int number_of_properties =
      object_boilerplate_description->backing_store_size();

  // Ignoring number_of_properties for force dictionary map with
  // __proto__:null.
  Handle<Map> map =
      has_null_prototype
          ? handle(native_context->slow_object_with_null_prototype_map(),
                   isolate)
          : isolate->factory()->ObjectLiteralMapFromCache(native_context,
                                                          number_of_properties);

  Handle<JSObject> boilerplate =
      isolate->factory()->NewFastOrSlowJSObjectFromMap(
          map, number_of_properties, allocation);

  // Normalize the elements of the boilerplate to save space if needed.
  if (!use_fast_elements) JSObject::NormalizeElements(boilerplate);

  // Add the constant properties to the boilerplate.
  int length = object_boilerplate_description->size();
  // TODO(verwaest): Support tracking representations in the boilerplate.
  for (int index = 0; index < length; index++) {
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    Handle<Object> key(object_boilerplate_description->name(isolate, index),
                       isolate);
    Handle<Object> value(object_boilerplate_description->value(isolate, index),
                         isolate);

    if (value->IsHeapObject()) {
      if (HeapObject::cast(*value).IsArrayBoilerplateDescription(isolate)) {
        Handle<ArrayBoilerplateDescription> boilerplate =
            Handle<ArrayBoilerplateDescription>::cast(value);
        value = CreateArrayLiteral(isolate, boilerplate, allocation);

      } else if (HeapObject::cast(*value).IsObjectBoilerplateDescription(
                     isolate)) {
        Handle<ObjectBoilerplateDescription> boilerplate =
            Handle<ObjectBoilerplateDescription>::cast(value);
        value = CreateObjectLiteral(isolate, boilerplate, boilerplate->flags(),
                                    allocation);
      }
427
    }
428

429 430 431 432
    uint32_t element_index = 0;
    if (key->ToArrayIndex(&element_index)) {
      // Array index (uint32).
      if (value->IsUninitialized(isolate)) {
433
        value = handle(Smi::zero(), isolate);
434
      }
435 436 437
      JSObject::SetOwnElementIgnoreAttributes(boilerplate, element_index, value,
                                              NONE)
          .Check();
438 439 440
    } else {
      Handle<String> name = Handle<String>::cast(key);
      DCHECK(!name->AsArrayIndex(&element_index));
441 442
      JSObject::SetOwnPropertyIgnoreAttributes(boilerplate, name, value, NONE)
          .Check();
443 444
    }
  }
445

446 447 448 449 450 451 452 453
  if (map->is_dictionary_map() && !has_null_prototype) {
    // TODO(cbruni): avoid making the boilerplate fast again, the clone stub
    // supports dict-mode objects directly.
    JSObject::MigrateSlowToFast(
        boilerplate, boilerplate->map().UnusedPropertyFields(), "FastLiteral");
  }
  return boilerplate;
}
454

455 456 457 458 459 460 461 462
Handle<JSObject> CreateArrayLiteral(
    Isolate* isolate,
    Handle<ArrayBoilerplateDescription> array_boilerplate_description,
    AllocationType allocation) {
  ElementsKind constant_elements_kind =
      array_boilerplate_description->elements_kind();

  Handle<FixedArrayBase> constant_elements_values(
463
      array_boilerplate_description->constant_elements(isolate), isolate);
464 465 466 467 468 469 470 471

  // Create the JSArray.
  Handle<FixedArrayBase> copied_elements_values;
  if (IsDoubleElementsKind(constant_elements_kind)) {
    copied_elements_values = isolate->factory()->CopyFixedDoubleArray(
        Handle<FixedDoubleArray>::cast(constant_elements_values));
  } else {
    DCHECK(IsSmiOrObjectElementsKind(constant_elements_kind));
472
    const bool is_cow = (constant_elements_values->map(isolate) ==
473 474 475 476
                         ReadOnlyRoots(isolate).fixed_cow_array_map());
    if (is_cow) {
      copied_elements_values = constant_elements_values;
      if (DEBUG_BOOL) {
477 478 479
        Handle<FixedArray> fixed_array_values =
            Handle<FixedArray>::cast(copied_elements_values);
        for (int i = 0; i < fixed_array_values->length(); i++) {
480
          DCHECK(!fixed_array_values->get(i).IsFixedArray());
481 482
        }
      }
483 484 485 486 487 488
    } else {
      Handle<FixedArray> fixed_array_values =
          Handle<FixedArray>::cast(constant_elements_values);
      Handle<FixedArray> fixed_array_values_copy =
          isolate->factory()->CopyFixedArray(fixed_array_values);
      copied_elements_values = fixed_array_values_copy;
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
      for (int i = 0; i < fixed_array_values->length(); i++) {
        Object value = fixed_array_values_copy->get(isolate, i);
        HeapObject value_heap_object;
        if (value.GetHeapObject(isolate, &value_heap_object)) {
          if (value_heap_object.IsArrayBoilerplateDescription(isolate)) {
            HandleScope sub_scope(isolate);
            Handle<ArrayBoilerplateDescription> boilerplate(
                ArrayBoilerplateDescription::cast(value_heap_object), isolate);
            Handle<JSObject> result =
                CreateArrayLiteral(isolate, boilerplate, allocation);
            fixed_array_values_copy->set(i, *result);

          } else if (value_heap_object.IsObjectBoilerplateDescription(
                         isolate)) {
            HandleScope sub_scope(isolate);
            Handle<ObjectBoilerplateDescription> boilerplate(
                ObjectBoilerplateDescription::cast(value_heap_object), isolate);
            Handle<JSObject> result = CreateObjectLiteral(
                isolate, boilerplate, boilerplate->flags(), allocation);
            fixed_array_values_copy->set(i, *result);
          }
        }
      }
512 513
    }
  }
514 515 516 517
  return isolate->factory()->NewJSArrayWithElements(
      copied_elements_values, constant_elements_kind,
      copied_elements_values->length(), allocation);
}
518

519 520 521
inline DeepCopyHints DecodeCopyHints(int flags) {
  DeepCopyHints copy_hints =
      (flags & AggregateLiteral::kIsShallow) ? kObjectIsShallow : kNoHints;
522
  if (FLAG_track_double_fields) {
523 524 525 526 527 528 529 530 531
    // Make sure we properly clone mutable heap numbers on 32-bit platforms.
    copy_hints = kNoHints;
  }
  return copy_hints;
}

template <typename LiteralHelper>
MaybeHandle<JSObject> CreateLiteralWithoutAllocationSite(
    Isolate* isolate, Handle<HeapObject> description, int flags) {
532 533
  Handle<JSObject> literal = LiteralHelper::Create(isolate, description, flags,
                                                   AllocationType::kYoung);
534 535 536 537 538 539 540 541 542
  DeepCopyHints copy_hints = DecodeCopyHints(flags);
  if (copy_hints == kNoHints) {
    DeprecationUpdateContext update_context(isolate);
    RETURN_ON_EXCEPTION(isolate, DeepWalk(literal, &update_context), JSObject);
  }
  return literal;
}

template <typename LiteralHelper>
543
MaybeHandle<JSObject> CreateLiteral(Isolate* isolate,
544
                                    MaybeHandle<FeedbackVector> maybe_vector,
545 546
                                    int literals_index,
                                    Handle<HeapObject> description, int flags) {
547 548 549 550 551 552
  if (maybe_vector.is_null()) {
    return CreateLiteralWithoutAllocationSite<LiteralHelper>(
        isolate, description, flags);
  }

  Handle<FeedbackVector> vector = maybe_vector.ToHandleChecked();
553
  FeedbackSlot literals_slot(FeedbackVector::ToSlot(literals_index));
554
  CHECK(literals_slot.ToInt() < vector->length());
555 556
  Handle<Object> literal_site(vector->Get(literals_slot)->cast<Object>(),
                              isolate);
557
  DeepCopyHints copy_hints = DecodeCopyHints(flags);
558

559 560
  Handle<AllocationSite> site;
  Handle<JSObject> boilerplate;
561

562
  if (HasBoilerplate(literal_site)) {
563
    site = Handle<AllocationSite>::cast(literal_site);
564
    boilerplate = Handle<JSObject>(site->boilerplate(), isolate);
565
  } else {
566 567 568 569
    // Eagerly create AllocationSites for literals that contain an Array.
    bool needs_initial_allocation_site =
        (flags & AggregateLiteral::kNeedsInitialAllocationSite) != 0;
    if (!needs_initial_allocation_site &&
570
        IsUninitializedLiteralSite(*literal_site)) {
571
      PreInitializeLiteralSite(vector, literals_slot);
572 573
      return CreateLiteralWithoutAllocationSite<LiteralHelper>(
          isolate, description, flags);
574
    } else {
575 576
      boilerplate = LiteralHelper::Create(isolate, description, flags,
                                          AllocationType::kOld);
577
    }
578
    // Install AllocationSite objects.
579 580
    AllocationSiteCreationContext creation_context(isolate);
    site = creation_context.EnterNewScope();
581 582
    RETURN_ON_EXCEPTION(isolate, DeepWalk(boilerplate, &creation_context),
                        JSObject);
583 584
    creation_context.ExitScope(site, boilerplate);

585
    vector->SynchronizedSet(literals_slot, *site);
586 587
  }

588 589 590
  STATIC_ASSERT(static_cast<int>(ObjectLiteral::kDisableMementos) ==
                static_cast<int>(ArrayLiteral::kDisableMementos));
  bool enable_mementos = (flags & ObjectLiteral::kDisableMementos) == 0;
591

592
  // Copy the existing boilerplate.
593 594 595
  AllocationSiteUsageContext usage_context(isolate, site, enable_mementos);
  usage_context.EnterNewScope();
  MaybeHandle<JSObject> copy =
596
      DeepCopy(boilerplate, &usage_context, copy_hints);
597 598 599
  usage_context.ExitScope(site, boilerplate);
  return copy;
}
600

601
}  // namespace
602

603 604 605
RUNTIME_FUNCTION(Runtime_CreateObjectLiteral) {
  HandleScope scope(isolate);
  DCHECK_EQ(4, args.length());
606
  CONVERT_ARG_HANDLE_CHECKED(HeapObject, maybe_vector, 0);
607
  CONVERT_TAGGED_INDEX_ARG_CHECKED(literals_index, 1);
608
  CONVERT_ARG_HANDLE_CHECKED(ObjectBoilerplateDescription, description, 2);
609
  CONVERT_SMI_ARG_CHECKED(flags, 3);
610 611
  Handle<FeedbackVector> vector;
  if (maybe_vector->IsFeedbackVector()) {
612
    vector = Handle<FeedbackVector>::cast(maybe_vector);
613 614
  } else {
    DCHECK(maybe_vector->IsUndefined());
615
  }
616
  RETURN_RESULT_OR_FAILURE(
617 618 619 620 621 622 623 624 625 626 627 628
      isolate, CreateLiteral<ObjectLiteralHelper>(
                   isolate, vector, literals_index, description, flags));
}

RUNTIME_FUNCTION(Runtime_CreateObjectLiteralWithoutAllocationSite) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(ObjectBoilerplateDescription, description, 0);
  CONVERT_SMI_ARG_CHECKED(flags, 1);
  RETURN_RESULT_OR_FAILURE(
      isolate, CreateLiteralWithoutAllocationSite<ObjectLiteralHelper>(
                   isolate, description, flags));
629
}
630

631 632 633 634 635 636 637 638 639 640
RUNTIME_FUNCTION(Runtime_CreateArrayLiteralWithoutAllocationSite) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(ArrayBoilerplateDescription, description, 0);
  CONVERT_SMI_ARG_CHECKED(flags, 1);
  RETURN_RESULT_OR_FAILURE(
      isolate, CreateLiteralWithoutAllocationSite<ArrayLiteralHelper>(
                   isolate, description, flags));
}

641 642
RUNTIME_FUNCTION(Runtime_CreateArrayLiteral) {
  HandleScope scope(isolate);
643
  DCHECK_EQ(4, args.length());
644
  CONVERT_ARG_HANDLE_CHECKED(HeapObject, maybe_vector, 0);
645
  CONVERT_TAGGED_INDEX_ARG_CHECKED(literals_index, 1);
646
  CONVERT_ARG_HANDLE_CHECKED(ArrayBoilerplateDescription, elements, 2);
647
  CONVERT_SMI_ARG_CHECKED(flags, 3);
648 649
  Handle<FeedbackVector> vector;
  if (maybe_vector->IsFeedbackVector()) {
650
    vector = Handle<FeedbackVector>::cast(maybe_vector);
651 652
  } else {
    DCHECK(maybe_vector->IsUndefined());
653
  }
654
  RETURN_RESULT_OR_FAILURE(
655 656
      isolate, CreateLiteral<ArrayLiteralHelper>(
                   isolate, vector, literals_index, elements, flags));
657 658
}

659 660 661
RUNTIME_FUNCTION(Runtime_CreateRegExpLiteral) {
  HandleScope scope(isolate);
  DCHECK_EQ(4, args.length());
662
  CONVERT_ARG_HANDLE_CHECKED(HeapObject, maybe_vector, 0);
663
  CONVERT_TAGGED_INDEX_ARG_CHECKED(index, 1);
664 665
  CONVERT_ARG_HANDLE_CHECKED(String, pattern, 2);
  CONVERT_SMI_ARG_CHECKED(flags, 3);
666

667 668 669 670 671
  if (maybe_vector->IsUndefined()) {
    // We don't have a vector; don't create a boilerplate, simply construct a
    // plain JSRegExp instance and return it.
    RETURN_RESULT_OR_FAILURE(
        isolate, JSRegExp::New(isolate, pattern, JSRegExp::Flags(flags)));
672
  }
673

674
  Handle<FeedbackVector> vector = Handle<FeedbackVector>::cast(maybe_vector);
675
  FeedbackSlot literal_slot(FeedbackVector::ToSlot(index));
676 677
  Handle<Object> literal_site(vector->Get(literal_slot)->cast<Object>(),
                              isolate);
678 679 680 681

  // This function must not be called when a boilerplate already exists (if it
  // exists, callers should instead copy the boilerplate into a new JSRegExp
  // instance).
682 683
  CHECK(!HasBoilerplate(literal_site));

684
  Handle<JSRegExp> regexp_instance;
685
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
686
      isolate, regexp_instance,
687
      JSRegExp::New(isolate, pattern, JSRegExp::Flags(flags)));
688 689 690

  // JSRegExp literal sites are initialized in a two-step process:
  // Uninitialized-Preinitialized, and Preinitialized-Initialized.
691 692
  if (IsUninitializedLiteralSite(*literal_site)) {
    PreInitializeLiteralSite(vector, literal_slot);
693
    return *regexp_instance;
694
  }
695 696 697 698 699 700 701

  Handle<FixedArray> data(FixedArray::cast(regexp_instance->data()), isolate);
  Handle<String> source(String::cast(regexp_instance->source()), isolate);
  Handle<RegExpBoilerplateDescription> boilerplate =
      isolate->factory()->NewRegExpBoilerplateDescription(
          data, source, Smi::cast(regexp_instance->flags()));

702
  vector->SynchronizedSet(literal_slot, *boilerplate);
703 704 705 706
  DCHECK(HasBoilerplate(
      handle(vector->Get(literal_slot)->cast<Object>(), isolate)));

  return *regexp_instance;
707 708
}

709 710
}  // namespace internal
}  // namespace v8