Remove excessive headers from JavaScriptCore
[WebKit-https.git] / Source / JavaScriptCore / runtime / Structure.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2013-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "Structure.h"
28
29 #include "CodeBlock.h"
30 #include "DumpContext.h"
31 #include "JSCInlines.h"
32 #include "JSObject.h"
33 #include "JSPropertyNameEnumerator.h"
34 #include "Lookup.h"
35 #include "PropertyMapHashTable.h"
36 #include "PropertyNameArray.h"
37 #include "StructureChain.h"
38 #include "StructureRareDataInlines.h"
39 #include "WeakGCMapInlines.h"
40 #include <wtf/CommaPrinter.h>
41 #include <wtf/NeverDestroyed.h>
42 #include <wtf/ProcessID.h>
43 #include <wtf/RefPtr.h>
44 #include <wtf/Threading.h>
45
46 #define DUMP_STRUCTURE_ID_STATISTICS 0
47
48 using namespace std;
49 using namespace WTF;
50
51 namespace JSC {
52
53 #if DUMP_STRUCTURE_ID_STATISTICS
54 static HashSet<Structure*>& liveStructureSet = *(new HashSet<Structure*>);
55 #endif
56
57 class SingleSlotTransitionWeakOwner final : public WeakHandleOwner {
58     void finalize(Handle<Unknown>, void* context) override
59     {
60         StructureTransitionTable* table = reinterpret_cast<StructureTransitionTable*>(context);
61         ASSERT(table->isUsingSingleSlot());
62         WeakSet::deallocate(table->weakImpl());
63         table->m_data = StructureTransitionTable::UsingSingleSlotFlag;
64     }
65 };
66
67 static SingleSlotTransitionWeakOwner& singleSlotTransitionWeakOwner()
68 {
69     static NeverDestroyed<SingleSlotTransitionWeakOwner> owner;
70     return owner;
71 }
72
73 inline Structure* StructureTransitionTable::singleTransition() const
74 {
75     ASSERT(isUsingSingleSlot());
76     if (WeakImpl* impl = this->weakImpl()) {
77         if (impl->state() == WeakImpl::Live)
78             return jsCast<Structure*>(impl->jsValue().asCell());
79     }
80     return nullptr;
81 }
82
83 inline void StructureTransitionTable::setSingleTransition(Structure* structure)
84 {
85     ASSERT(isUsingSingleSlot());
86     if (WeakImpl* impl = this->weakImpl())
87         WeakSet::deallocate(impl);
88     WeakImpl* impl = WeakSet::allocate(structure, &singleSlotTransitionWeakOwner(), this);
89     m_data = reinterpret_cast<intptr_t>(impl) | UsingSingleSlotFlag;
90 }
91
92 bool StructureTransitionTable::contains(UniquedStringImpl* rep, unsigned attributes) const
93 {
94     if (isUsingSingleSlot()) {
95         Structure* transition = singleTransition();
96         return transition && transition->m_nameInPrevious == rep && transition->attributesInPrevious() == attributes;
97     }
98     return map()->get(std::make_pair(rep, attributes));
99 }
100
101 Structure* StructureTransitionTable::get(UniquedStringImpl* rep, unsigned attributes) const
102 {
103     if (isUsingSingleSlot()) {
104         Structure* transition = singleTransition();
105         return (transition && transition->m_nameInPrevious == rep && transition->attributesInPrevious() == attributes) ? transition : 0;
106     }
107     return map()->get(std::make_pair(rep, attributes));
108 }
109
110 void StructureTransitionTable::add(VM& vm, Structure* structure)
111 {
112     if (isUsingSingleSlot()) {
113         Structure* existingTransition = singleTransition();
114
115         // This handles the first transition being added.
116         if (!existingTransition) {
117             setSingleTransition(structure);
118             return;
119         }
120
121         // This handles the second transition being added
122         // (or the first transition being despecified!)
123         setMap(new TransitionMap(vm));
124         add(vm, existingTransition);
125     }
126
127     // Add the structure to the map.
128
129     // Newer versions of the STL have an std::make_pair function that takes rvalue references.
130     // When either of the parameters are bitfields, the C++ compiler will try to bind them as lvalues, which is invalid. To work around this, use unary "+" to make the parameter an rvalue.
131     // See https://bugs.webkit.org/show_bug.cgi?id=59261 for more details
132     map()->set(std::make_pair(structure->m_nameInPrevious.get(), +structure->attributesInPrevious()), structure);
133 }
134
135 void Structure::dumpStatistics()
136 {
137 #if DUMP_STRUCTURE_ID_STATISTICS
138     unsigned numberLeaf = 0;
139     unsigned numberUsingSingleSlot = 0;
140     unsigned numberSingletons = 0;
141     unsigned numberWithPropertyMaps = 0;
142     unsigned totalPropertyMapsSize = 0;
143
144     HashSet<Structure*>::const_iterator end = liveStructureSet.end();
145     for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
146         Structure* structure = *it;
147
148         switch (structure->m_transitionTable.size()) {
149             case 0:
150                 ++numberLeaf;
151                 if (!structure->previousID())
152                     ++numberSingletons;
153                 break;
154
155             case 1:
156                 ++numberUsingSingleSlot;
157                 break;
158         }
159
160         if (PropertyTable* table = structure->propertyTableOrNull()) {
161             ++numberWithPropertyMaps;
162             totalPropertyMapsSize += table->sizeInMemory();
163         }
164     }
165
166     dataLogF("Number of live Structures: %d\n", liveStructureSet.size());
167     dataLogF("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
168     dataLogF("Number of Structures that are leaf nodes: %d\n", numberLeaf);
169     dataLogF("Number of Structures that singletons: %d\n", numberSingletons);
170     dataLogF("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);
171
172     dataLogF("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
173     dataLogF("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
174     dataLogF("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
175 #else
176     dataLogF("Dumping Structure statistics is not enabled.\n");
177 #endif
178 }
179
180 Structure::Structure(VM& vm, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
181     : JSCell(vm, vm.structureStructure.get())
182     , m_blob(vm.heap.structureIDTable().allocateID(this), indexingType, typeInfo)
183     , m_outOfLineTypeFlags(typeInfo.outOfLineTypeFlags())
184     , m_inlineCapacity(inlineCapacity)
185     , m_bitField(0)
186     , m_globalObject(vm, this, globalObject, WriteBarrier<JSGlobalObject>::MayBeNull)
187     , m_prototype(vm, this, prototype)
188     , m_classInfo(classInfo)
189     , m_transitionWatchpointSet(IsWatched)
190     , m_offset(invalidOffset)
191 {
192     setDictionaryKind(NoneDictionaryKind);
193     setIsPinnedPropertyTable(false);
194     setHasGetterSetterProperties(classInfo->hasStaticSetterOrReadonlyProperties());
195     setHasCustomGetterSetterProperties(false);
196     setHasReadOnlyOrGetterSetterPropertiesExcludingProto(classInfo->hasStaticSetterOrReadonlyProperties());
197     setIsQuickPropertyAccessAllowedForEnumeration(true);
198     setAttributesInPrevious(0);
199     setDidPreventExtensions(false);
200     setDidTransition(false);
201     setStaticPropertiesReified(false);
202     setTransitionWatchpointIsLikelyToBeFired(false);
203     setHasBeenDictionary(false);
204     setIsAddingPropertyForTransition(false);
205  
206     ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity());
207     ASSERT(static_cast<PropertyOffset>(inlineCapacity) < firstOutOfLineOffset);
208     ASSERT(!hasRareData());
209     ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
210     ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
211 }
212
213 const ClassInfo Structure::s_info = { "Structure", nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(Structure) };
214
215 Structure::Structure(VM& vm)
216     : JSCell(CreatingEarlyCell)
217     , m_inlineCapacity(0)
218     , m_bitField(0)
219     , m_prototype(vm, this, jsNull())
220     , m_classInfo(info())
221     , m_transitionWatchpointSet(IsWatched)
222     , m_offset(invalidOffset)
223 {
224     setDictionaryKind(NoneDictionaryKind);
225     setIsPinnedPropertyTable(false);
226     setHasGetterSetterProperties(m_classInfo->hasStaticSetterOrReadonlyProperties());
227     setHasCustomGetterSetterProperties(false);
228     setHasReadOnlyOrGetterSetterPropertiesExcludingProto(m_classInfo->hasStaticSetterOrReadonlyProperties());
229     setIsQuickPropertyAccessAllowedForEnumeration(true);
230     setAttributesInPrevious(0);
231     setDidPreventExtensions(false);
232     setDidTransition(false);
233     setStaticPropertiesReified(false);
234     setTransitionWatchpointIsLikelyToBeFired(false);
235     setHasBeenDictionary(false);
236     setIsAddingPropertyForTransition(false);
237  
238     TypeInfo typeInfo = TypeInfo(CellType, StructureFlags);
239     m_blob = StructureIDBlob(vm.heap.structureIDTable().allocateID(this), 0, typeInfo);
240     m_outOfLineTypeFlags = typeInfo.outOfLineTypeFlags();
241
242     ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
243     ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
244 }
245
246 Structure::Structure(VM& vm, Structure* previous, DeferredStructureTransitionWatchpointFire* deferred)
247     : JSCell(vm, vm.structureStructure.get())
248     , m_inlineCapacity(previous->m_inlineCapacity)
249     , m_bitField(0)
250     , m_prototype(vm, this, previous->storedPrototype())
251     , m_classInfo(previous->m_classInfo)
252     , m_transitionWatchpointSet(IsWatched)
253     , m_offset(invalidOffset)
254 {
255     setDictionaryKind(previous->dictionaryKind());
256     setIsPinnedPropertyTable(previous->hasBeenFlattenedBefore());
257     setHasGetterSetterProperties(previous->hasGetterSetterProperties());
258     setHasCustomGetterSetterProperties(previous->hasCustomGetterSetterProperties());
259     setHasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->hasReadOnlyOrGetterSetterPropertiesExcludingProto());
260     setIsQuickPropertyAccessAllowedForEnumeration(previous->isQuickPropertyAccessAllowedForEnumeration());
261     setAttributesInPrevious(0);
262     setDidPreventExtensions(previous->didPreventExtensions());
263     setDidTransition(true);
264     setStaticPropertiesReified(previous->staticPropertiesReified());
265     setHasBeenDictionary(previous->hasBeenDictionary());
266     setIsAddingPropertyForTransition(false);
267  
268     TypeInfo typeInfo = previous->typeInfo();
269     m_blob = StructureIDBlob(vm.heap.structureIDTable().allocateID(this), previous->indexingTypeIncludingHistory(), typeInfo);
270     m_outOfLineTypeFlags = typeInfo.outOfLineTypeFlags();
271
272     ASSERT(!previous->typeInfo().structureIsImmortal());
273     setPreviousID(vm, previous);
274
275     previous->didTransitionFromThisStructure(deferred);
276     
277     // Copy this bit now, in case previous was being watched.
278     setTransitionWatchpointIsLikelyToBeFired(previous->transitionWatchpointIsLikelyToBeFired());
279
280     if (previous->m_globalObject)
281         m_globalObject.set(vm, this, previous->m_globalObject.get());
282     ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
283     ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
284 }
285
286 Structure::~Structure()
287 {
288     if (typeInfo().structureIsImmortal())
289         return;
290     Heap::heap(this)->structureIDTable().deallocateID(this, m_blob.structureID());
291 }
292
293 void Structure::destroy(JSCell* cell)
294 {
295     static_cast<Structure*>(cell)->Structure::~Structure();
296 }
297
298 void Structure::findStructuresAndMapForMaterialization(Vector<Structure*, 8>& structures, Structure*& structure, PropertyTable*& table)
299 {
300     ASSERT(structures.isEmpty());
301     table = 0;
302
303     for (structure = this; structure; structure = structure->previousID()) {
304         structure->m_lock.lock();
305         
306         table = structure->propertyTableOrNull();
307         if (table) {
308             // Leave the structure locked, so that the caller can do things to it atomically
309             // before it loses its property table.
310             return;
311         }
312         
313         structures.append(structure);
314         structure->m_lock.unlock();
315     }
316     
317     ASSERT(!structure);
318     ASSERT(!table);
319 }
320
321 PropertyTable* Structure::materializePropertyTable(VM& vm, bool setPropertyTable)
322 {
323     ASSERT(structure()->classInfo() == info());
324     ASSERT(!isAddingPropertyForTransition());
325     
326     DeferGC deferGC(vm.heap);
327     
328     Vector<Structure*, 8> structures;
329     Structure* structure;
330     PropertyTable* table;
331     
332     findStructuresAndMapForMaterialization(structures, structure, table);
333     
334     unsigned capacity = numberOfSlotsForLastOffset(m_offset, m_inlineCapacity);
335     if (table) {
336         table = table->copy(vm, capacity);
337         structure->m_lock.unlock();
338     } else
339         table = PropertyTable::create(vm, capacity);
340     
341     // Must hold the lock on this structure, since we will be modifying this structure's
342     // property map. We don't want getConcurrently() to see the property map in a half-baked
343     // state.
344     GCSafeConcurrentJSLocker locker(m_lock, vm.heap);
345     if (setPropertyTable)
346         this->setPropertyTable(vm, table);
347
348     InferredTypeTable* typeTable = m_inferredTypeTable.get();
349
350     for (size_t i = structures.size(); i--;) {
351         structure = structures[i];
352         if (!structure->m_nameInPrevious)
353             continue;
354         PropertyMapEntry entry(structure->m_nameInPrevious.get(), structure->m_offset, structure->attributesInPrevious());
355         if (typeTable && typeTable->get(structure->m_nameInPrevious.get()))
356             entry.hasInferredType = true;
357         table->add(entry, m_offset, PropertyTable::PropertyOffsetMustNotChange);
358     }
359     
360     checkOffsetConsistency(
361         table,
362         [&] () {
363             dataLog("Detected in materializePropertyTable.\n");
364             dataLog("Found structure = ", RawPointer(structure), "\n");
365             dataLog("structures = ");
366             CommaPrinter comma;
367             for (Structure* structure : structures)
368                 dataLog(comma, RawPointer(structure));
369             dataLog("\n");
370         });
371     
372     return table;
373 }
374
375 Structure* Structure::addPropertyTransitionToExistingStructureImpl(Structure* structure, UniquedStringImpl* uid, unsigned attributes, PropertyOffset& offset)
376 {
377     ASSERT(!structure->isDictionary());
378     ASSERT(structure->isObject());
379
380     if (Structure* existingTransition = structure->m_transitionTable.get(uid, attributes)) {
381         validateOffset(existingTransition->m_offset, existingTransition->inlineCapacity());
382         offset = existingTransition->m_offset;
383         return existingTransition;
384     }
385
386     return 0;
387 }
388
389 Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset)
390 {
391     ASSERT(!isCompilationThread());
392     return addPropertyTransitionToExistingStructureImpl(structure, propertyName.uid(), attributes, offset);
393 }
394
395 Structure* Structure::addPropertyTransitionToExistingStructureConcurrently(Structure* structure, UniquedStringImpl* uid, unsigned attributes, PropertyOffset& offset)
396 {
397     ConcurrentJSLocker locker(structure->m_lock);
398     return addPropertyTransitionToExistingStructureImpl(structure, uid, attributes, offset);
399 }
400
401 bool Structure::anyObjectInChainMayInterceptIndexedAccesses() const
402 {
403     for (const Structure* current = this; ;) {
404         if (current->mayInterceptIndexedAccesses())
405             return true;
406         
407         JSValue prototype = current->storedPrototype();
408         if (prototype.isNull())
409             return false;
410         
411         current = asObject(prototype)->structure();
412     }
413 }
414
415 bool Structure::holesMustForwardToPrototype(VM& vm) const
416 {
417     if (this->mayInterceptIndexedAccesses())
418         return true;
419
420     JSValue prototype = this->storedPrototype();
421     if (!prototype.isObject())
422         return false;
423     JSObject* object = asObject(prototype);
424
425     while (true) {
426         Structure& structure = *object->structure(vm);
427         if (hasIndexedProperties(object->indexingType()) || structure.mayInterceptIndexedAccesses())
428             return true;
429         prototype = structure.storedPrototype();
430         if (!prototype.isObject())
431             return false;
432         object = asObject(prototype);
433     }
434
435     RELEASE_ASSERT_NOT_REACHED();
436     return false;
437 }
438
439 bool Structure::needsSlowPutIndexing() const
440 {
441     return anyObjectInChainMayInterceptIndexedAccesses()
442         || globalObject()->isHavingABadTime();
443 }
444
445 NonPropertyTransition Structure::suggestedArrayStorageTransition() const
446 {
447     if (needsSlowPutIndexing())
448         return NonPropertyTransition::AllocateSlowPutArrayStorage;
449     
450     return NonPropertyTransition::AllocateArrayStorage;
451 }
452
453 Structure* Structure::addPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset)
454 {
455     Structure* newStructure = addPropertyTransitionToExistingStructure(
456         structure, propertyName, attributes, offset);
457     if (newStructure)
458         return newStructure;
459
460     return addNewPropertyTransition(
461         vm, structure, propertyName, attributes, offset, PutPropertySlot::UnknownContext);
462 }
463
464 Structure* Structure::addNewPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset, PutPropertySlot::Context context, DeferredStructureTransitionWatchpointFire* deferred)
465 {
466     ASSERT(!structure->isDictionary());
467     ASSERT(structure->isObject());
468     ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, offset));
469     
470     int maxTransitionLength;
471     if (context == PutPropertySlot::PutById)
472         maxTransitionLength = s_maxTransitionLengthForNonEvalPutById;
473     else
474         maxTransitionLength = s_maxTransitionLength;
475     if (structure->transitionCount() > maxTransitionLength) {
476         Structure* transition = toCacheableDictionaryTransition(vm, structure, deferred);
477         ASSERT(structure != transition);
478         offset = transition->add(vm, propertyName, attributes);
479         return transition;
480     }
481     
482     Structure* transition = create(vm, structure, deferred);
483
484     transition->m_cachedPrototypeChain.setMayBeNull(vm, transition, structure->m_cachedPrototypeChain.get());
485     
486     // While we are adding the property, rematerializing the property table is super weird: we already
487     // have a m_nameInPrevious and attributesInPrevious but the m_offset is still wrong. If the
488     // materialization algorithm runs, it'll build a property table that already has the property but
489     // at a bogus offset. Rather than try to teach the materialization code how to create a table under
490     // those conditions, we just tell the GC not to blow the table away during this period of time.
491     // Holding the lock ensures that we either do this before the GC starts scanning the structure, in
492     // which case the GC will not blow the table away, or we do it after the GC already ran in which
493     // case all is well.  If it wasn't for the lock, the GC would have TOCTOU: if could read
494     // isAddingPropertyForTransition before we set it to true, and then blow the table away after.
495     {
496         ConcurrentJSLocker locker(transition->m_lock);
497         transition->setIsAddingPropertyForTransition(true);
498     }
499     
500     transition->m_nameInPrevious = propertyName.uid();
501     transition->setAttributesInPrevious(attributes);
502     transition->setPropertyTable(vm, structure->takePropertyTableOrCloneIfPinned(vm));
503     transition->m_offset = structure->m_offset;
504     transition->m_inferredTypeTable.setMayBeNull(vm, transition, structure->m_inferredTypeTable.get());
505
506     offset = transition->add(vm, propertyName, attributes);
507
508     // Now that everything is fine with the new structure's bookkeeping, the GC is free to blow the
509     // table away if it wants. We can now rebuild it fine.
510     WTF::storeStoreFence();
511     transition->setIsAddingPropertyForTransition(false);
512
513     checkOffset(transition->m_offset, transition->inlineCapacity());
514     {
515         ConcurrentJSLocker locker(structure->m_lock);
516         structure->m_transitionTable.add(vm, transition);
517     }
518     transition->checkOffsetConsistency();
519     structure->checkOffsetConsistency();
520     return transition;
521 }
522
523 Structure* Structure::removePropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, PropertyOffset& offset)
524 {
525     // NOTE: There are some good reasons why this goes directly to uncacheable dictionary rather than
526     // caching the removal. We can fix all of these things, but we must remember to do so, if we ever try
527     // to optimize this case.
528     //
529     // - Cached transitions usually steal the property table, and assume that this is possible because they
530     //   can just rebuild the table by looking at past transitions. That code assumes that the table only
531     //   grew and never shrank. To support removals, we'd have to change the property table materialization
532     //   code to handle deletions. Also, we have logic to get the list of properties on a structure that
533     //   lacks a property table by just looking back through the set of transitions since the last
534     //   structure that had a pinned table. That logic would also have to be changed to handle cached
535     //   removals.
536     //
537     // - InferredTypeTable assumes that removal has never happened. This is important since if we could
538     //   remove a property and then re-add it later, then the "absence means top" optimization wouldn't
539     //   work anymore, unless removal also either poisoned type inference (by doing something equivalent to
540     //   hasBeenDictionary) or by strongly marking the entry as Top by ensuring that it is not absent, but
541     //   instead, has a null entry.
542     
543     ASSERT(!structure->isUncacheableDictionary());
544
545     Structure* transition = toUncacheableDictionaryTransition(vm, structure);
546
547     offset = transition->remove(propertyName);
548
549     transition->checkOffsetConsistency();
550     return transition;
551 }
552
553 Structure* Structure::changePrototypeTransition(VM& vm, Structure* structure, JSValue prototype)
554 {
555     DeferGC deferGC(vm.heap);
556     Structure* transition = create(vm, structure);
557
558     transition->m_prototype.set(vm, transition, prototype);
559
560     PropertyTable* table = structure->copyPropertyTableForPinning(vm);
561     transition->pin(holdLock(transition->m_lock), vm, table);
562     transition->m_offset = structure->m_offset;
563     
564     transition->checkOffsetConsistency();
565     return transition;
566 }
567
568 Structure* Structure::attributeChangeTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes)
569 {
570     if (!structure->isUncacheableDictionary()) {
571         Structure* transition = create(vm, structure);
572
573         PropertyTable* table = structure->copyPropertyTableForPinning(vm);
574         transition->pin(holdLock(transition->m_lock), vm, table);
575         transition->m_offset = structure->m_offset;
576         
577         structure = transition;
578     }
579
580     PropertyMapEntry* entry = structure->ensurePropertyTable(vm)->get(propertyName.uid());
581     ASSERT(entry);
582     entry->attributes = attributes;
583
584     structure->checkOffsetConsistency();
585     return structure;
586 }
587
588 Structure* Structure::toDictionaryTransition(VM& vm, Structure* structure, DictionaryKind kind, DeferredStructureTransitionWatchpointFire* deferred)
589 {
590     ASSERT(!structure->isUncacheableDictionary());
591     DeferGC deferGC(vm.heap);
592     
593     Structure* transition = create(vm, structure, deferred);
594
595     PropertyTable* table = structure->copyPropertyTableForPinning(vm);
596     transition->pin(holdLock(transition->m_lock), vm, table);
597     transition->m_offset = structure->m_offset;
598     transition->setDictionaryKind(kind);
599     transition->setHasBeenDictionary(true);
600     
601     transition->checkOffsetConsistency();
602     return transition;
603 }
604
605 Structure* Structure::toCacheableDictionaryTransition(VM& vm, Structure* structure, DeferredStructureTransitionWatchpointFire* deferred)
606 {
607     return toDictionaryTransition(vm, structure, CachedDictionaryKind, deferred);
608 }
609
610 Structure* Structure::toUncacheableDictionaryTransition(VM& vm, Structure* structure)
611 {
612     return toDictionaryTransition(vm, structure, UncachedDictionaryKind);
613 }
614
615 Structure* Structure::sealTransition(VM& vm, Structure* structure)
616 {
617     return nonPropertyTransition(vm, structure, NonPropertyTransition::Seal);
618 }
619
620 Structure* Structure::freezeTransition(VM& vm, Structure* structure)
621 {
622     return nonPropertyTransition(vm, structure, NonPropertyTransition::Freeze);
623 }
624
625 Structure* Structure::preventExtensionsTransition(VM& vm, Structure* structure)
626 {
627     return nonPropertyTransition(vm, structure, NonPropertyTransition::PreventExtensions);
628 }
629
630 PropertyTable* Structure::takePropertyTableOrCloneIfPinned(VM& vm)
631 {
632     // This must always return a property table. It can't return null.
633     PropertyTable* result = propertyTableOrNull();
634     if (result) {
635         if (isPinnedPropertyTable())
636             return result->copy(vm, result->size() + 1);
637         ConcurrentJSLocker locker(m_lock);
638         setPropertyTable(vm, nullptr);
639         return result;
640     }
641     bool setPropertyTable = false;
642     return materializePropertyTable(vm, setPropertyTable);
643 }
644
645 Structure* Structure::nonPropertyTransition(VM& vm, Structure* structure, NonPropertyTransition transitionKind)
646 {
647     unsigned attributes = toAttributes(transitionKind);
648     IndexingType indexingTypeIncludingHistory = newIndexingType(structure->indexingTypeIncludingHistory(), transitionKind);
649     
650     if (changesIndexingType(transitionKind)) {
651         if (JSGlobalObject* globalObject = structure->m_globalObject.get()) {
652             if (globalObject->isOriginalArrayStructure(structure)) {
653                 Structure* result = globalObject->originalArrayStructureForIndexingType(indexingTypeIncludingHistory);
654                 if (result->indexingTypeIncludingHistory() == indexingTypeIncludingHistory) {
655                     structure->didTransitionFromThisStructure();
656                     return result;
657                 }
658             }
659         }
660     }
661     
662     Structure* existingTransition;
663     if (!structure->isDictionary() && (existingTransition = structure->m_transitionTable.get(0, attributes))) {
664         ASSERT(existingTransition->attributesInPrevious() == attributes);
665         ASSERT(existingTransition->indexingTypeIncludingHistory() == indexingTypeIncludingHistory);
666         return existingTransition;
667     }
668     
669     DeferGC deferGC(vm.heap);
670     
671     Structure* transition = create(vm, structure);
672     transition->setAttributesInPrevious(attributes);
673     transition->m_blob.setIndexingTypeIncludingHistory(indexingTypeIncludingHistory);
674     
675     if (preventsExtensions(transitionKind))
676         transition->setDidPreventExtensions(true);
677     
678     if (setsDontDeleteOnAllProperties(transitionKind)
679         || setsReadOnlyOnNonAccessorProperties(transitionKind)) {
680         // We pin the property table on transitions that do wholesale editing of the property
681         // table, since our logic for walking the property transition chain to rematerialize the
682         // table doesn't know how to take into account such wholesale edits.
683
684         PropertyTable* table = structure->copyPropertyTableForPinning(vm);
685         transition->pinForCaching(holdLock(transition->m_lock), vm, table);
686         transition->m_offset = structure->m_offset;
687         
688         table = transition->propertyTableOrNull();
689         RELEASE_ASSERT(table);
690         for (auto& entry : *table) {
691             if (setsDontDeleteOnAllProperties(transitionKind))
692                 entry.attributes |= DontDelete;
693             if (setsReadOnlyOnNonAccessorProperties(transitionKind) && !(entry.attributes & Accessor))
694                 entry.attributes |= ReadOnly;
695         }
696     } else {
697         transition->setPropertyTable(vm, structure->takePropertyTableOrCloneIfPinned(vm));
698         transition->m_offset = structure->m_offset;
699         checkOffset(transition->m_offset, transition->inlineCapacity());
700     }
701     
702     if (setsReadOnlyOnNonAccessorProperties(transitionKind)
703         && !transition->propertyTableOrNull()->isEmpty())
704         transition->setHasReadOnlyOrGetterSetterPropertiesExcludingProto(true);
705     
706     if (structure->isDictionary()) {
707         PropertyTable* table = transition->ensurePropertyTable(vm);
708         transition->pin(holdLock(transition->m_lock), vm, table);
709     } else {
710         auto locker = holdLock(structure->m_lock);
711         structure->m_transitionTable.add(vm, transition);
712     }
713
714     transition->checkOffsetConsistency();
715     return transition;
716 }
717
718 // In future we may want to cache this property.
719 bool Structure::isSealed(VM& vm)
720 {
721     if (isStructureExtensible())
722         return false;
723
724     PropertyTable* table = ensurePropertyTableIfNotEmpty(vm);
725     if (!table)
726         return true;
727     
728     PropertyTable::iterator end = table->end();
729     for (PropertyTable::iterator iter = table->begin(); iter != end; ++iter) {
730         if ((iter->attributes & DontDelete) != DontDelete)
731             return false;
732     }
733     return true;
734 }
735
736 // In future we may want to cache this property.
737 bool Structure::isFrozen(VM& vm)
738 {
739     if (isStructureExtensible())
740         return false;
741
742     PropertyTable* table = ensurePropertyTableIfNotEmpty(vm);
743     if (!table)
744         return true;
745     
746     PropertyTable::iterator end = table->end();
747     for (PropertyTable::iterator iter = table->begin(); iter != end; ++iter) {
748         if (!(iter->attributes & DontDelete))
749             return false;
750         if (!(iter->attributes & (ReadOnly | Accessor)))
751             return false;
752     }
753     return true;
754 }
755
756 Structure* Structure::flattenDictionaryStructure(VM& vm, JSObject* object)
757 {
758     checkOffsetConsistency();
759     ASSERT(isDictionary());
760     
761     GCSafeConcurrentJSLocker locker(m_lock, vm.heap);
762     
763     object->setStructureIDDirectly(nuke(id()));
764     WTF::storeStoreFence();
765
766     size_t beforeOutOfLineCapacity = this->outOfLineCapacity();
767     if (isUncacheableDictionary()) {
768         PropertyTable* table = propertyTableOrNull();
769         ASSERT(table);
770
771         size_t propertyCount = table->size();
772
773         // Holds our values compacted by insertion order.
774         Vector<JSValue> values(propertyCount);
775
776         // Copies out our values from their hashed locations, compacting property table offsets as we go.
777         unsigned i = 0;
778         PropertyTable::iterator end = table->end();
779         m_offset = invalidOffset;
780         for (PropertyTable::iterator iter = table->begin(); iter != end; ++iter, ++i) {
781             values[i] = object->getDirect(iter->offset);
782             m_offset = iter->offset = offsetForPropertyNumber(i, m_inlineCapacity);
783         }
784         
785         // Copies in our values to their compacted locations.
786         for (unsigned i = 0; i < propertyCount; i++)
787             object->putDirect(vm, offsetForPropertyNumber(i, m_inlineCapacity), values[i]);
788
789         table->clearDeletedOffsets();
790         checkOffsetConsistency();
791     }
792
793     setDictionaryKind(NoneDictionaryKind);
794     setHasBeenFlattenedBefore(true);
795
796     size_t afterOutOfLineCapacity = this->outOfLineCapacity();
797
798     if (object->butterfly() && beforeOutOfLineCapacity != afterOutOfLineCapacity) {
799         ASSERT(beforeOutOfLineCapacity > afterOutOfLineCapacity);
800         // If the object had a Butterfly but after flattening/compacting we no longer have need of it,
801         // we need to zero it out because the collector depends on the Structure to know the size for copying.
802         if (!afterOutOfLineCapacity && !this->hasIndexingHeader(object))
803             object->setButterfly(vm, nullptr);
804         // If the object was down-sized to the point where the base of the Butterfly is no longer within the 
805         // first CopiedBlock::blockSize bytes, we'll get the wrong answer if we try to mask the base back to 
806         // the CopiedBlock header. To prevent this case we need to memmove the Butterfly down.
807         else
808             object->shiftButterflyAfterFlattening(locker, vm, this, afterOutOfLineCapacity);
809     }
810     
811     WTF::storeStoreFence();
812     object->setStructureIDDirectly(id());
813
814     // FIXME: This is probably no longer needed since we have a stronger mechanism
815     // for detecting races and rescanning an object.
816     // https://bugs.webkit.org/show_bug.cgi?id=166989
817     vm.heap.writeBarrier(object);
818
819     return this;
820 }
821
822 void Structure::pin(const AbstractLocker&, VM& vm, PropertyTable* table)
823 {
824     setIsPinnedPropertyTable(true);
825     setPropertyTable(vm, table);
826     clearPreviousID();
827     m_nameInPrevious = nullptr;
828 }
829
830 void Structure::pinForCaching(const AbstractLocker&, VM& vm, PropertyTable* table)
831 {
832     setIsPinnedPropertyTable(true);
833     setPropertyTable(vm, table);
834     m_nameInPrevious = nullptr;
835 }
836
837 void Structure::allocateRareData(VM& vm)
838 {
839     ASSERT(!hasRareData());
840     StructureRareData* rareData = StructureRareData::create(vm, previousID());
841     WTF::storeStoreFence();
842     m_previousOrRareData.set(vm, this, rareData);
843     ASSERT(hasRareData());
844 }
845
846 WatchpointSet* Structure::ensurePropertyReplacementWatchpointSet(VM& vm, PropertyOffset offset)
847 {
848     ASSERT(!isUncacheableDictionary());
849
850     // In some places it's convenient to call this with an invalid offset. So, we do the check here.
851     if (!isValidOffset(offset))
852         return nullptr;
853     
854     if (!hasRareData())
855         allocateRareData(vm);
856     ConcurrentJSLocker locker(m_lock);
857     StructureRareData* rareData = this->rareData();
858     if (!rareData->m_replacementWatchpointSets) {
859         rareData->m_replacementWatchpointSets =
860             std::make_unique<StructureRareData::PropertyWatchpointMap>();
861         WTF::storeStoreFence();
862     }
863     auto result = rareData->m_replacementWatchpointSets->add(offset, nullptr);
864     if (result.isNewEntry)
865         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
866     return result.iterator->value.get();
867 }
868
869 void Structure::startWatchingPropertyForReplacements(VM& vm, PropertyName propertyName)
870 {
871     ASSERT(!isUncacheableDictionary());
872     
873     startWatchingPropertyForReplacements(vm, get(vm, propertyName));
874 }
875
876 void Structure::didCachePropertyReplacement(VM& vm, PropertyOffset offset)
877 {
878     ensurePropertyReplacementWatchpointSet(vm, offset)->fireAll(vm, "Did cache property replacement");
879 }
880
881 void Structure::startWatchingInternalProperties(VM& vm)
882 {
883     if (!isUncacheableDictionary()) {
884         startWatchingPropertyForReplacements(vm, vm.propertyNames->toString);
885         startWatchingPropertyForReplacements(vm, vm.propertyNames->valueOf);
886     }
887     setDidWatchInternalProperties(true);
888 }
889
890 void Structure::willStoreValueSlow(
891     VM& vm, PropertyName propertyName, JSValue value, bool shouldOptimize,
892     InferredTypeTable::StoredPropertyAge age)
893 {
894     ASSERT(!isCompilationThread());
895     ASSERT(structure()->classInfo() == info());
896     ASSERT(!hasBeenDictionary());
897
898     // Create the inferred type table before doing anything else, so that we don't GC after we have already
899     // grabbed a pointer into the property map.
900     InferredTypeTable* table = m_inferredTypeTable.get();
901     if (!table) {
902         table = InferredTypeTable::create(vm);
903         WTF::storeStoreFence();
904         m_inferredTypeTable.set(vm, this, table);
905     }
906
907     // This only works if we've got a property table.
908     PropertyTable* propertyTable = ensurePropertyTable(vm);
909     
910     // We must be calling this after having created the given property or confirmed that it was present
911     // already, so the property must be present.
912     PropertyMapEntry* entry = propertyTable->get(propertyName.uid());
913     ASSERT(entry);
914     
915     if (shouldOptimize)
916         entry->hasInferredType = table->willStoreValue(vm, propertyName, value, age);
917     else {
918         table->makeTop(vm, propertyName, age);
919         entry->hasInferredType = false;
920     }
921     
922     propertyTable->use(); // This makes it safe to use entry above.
923 }
924
925 #if DUMP_PROPERTYMAP_STATS
926
927 PropertyMapHashTableStats* propertyMapHashTableStats = 0;
928
929 struct PropertyMapStatisticsExitLogger {
930     PropertyMapStatisticsExitLogger();
931     ~PropertyMapStatisticsExitLogger();
932 };
933
934 DEFINE_GLOBAL_FOR_LOGGING(PropertyMapStatisticsExitLogger, logger, );
935
936 PropertyMapStatisticsExitLogger::PropertyMapStatisticsExitLogger()
937 {
938     propertyMapHashTableStats = adoptPtr(new PropertyMapHashTableStats()).leakPtr();
939 }
940
941 PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
942 {
943     unsigned finds = propertyMapHashTableStats->numFinds;
944     unsigned collisions = propertyMapHashTableStats->numCollisions;
945     dataLogF("\nJSC::PropertyMap statistics for process %d\n\n", getCurrentProcessID());
946     dataLogF("%d finds\n", finds);
947     dataLogF("%d collisions (%.1f%%)\n", collisions, 100.0 * collisions / finds);
948     dataLogF("%d lookups\n", propertyMapHashTableStats->numLookups.load());
949     dataLogF("%d lookup probings\n", propertyMapHashTableStats->numLookupProbing.load());
950     dataLogF("%d adds\n", propertyMapHashTableStats->numAdds.load());
951     dataLogF("%d removes\n", propertyMapHashTableStats->numRemoves.load());
952     dataLogF("%d rehashes\n", propertyMapHashTableStats->numRehashes.load());
953     dataLogF("%d reinserts\n", propertyMapHashTableStats->numReinserts.load());
954 }
955
956 #endif
957
958 PropertyTable* Structure::copyPropertyTableForPinning(VM& vm)
959 {
960     if (PropertyTable* table = propertyTableOrNull())
961         return PropertyTable::clone(vm, *table);
962     bool setPropertyTable = false;
963     return materializePropertyTable(vm, setPropertyTable);
964 }
965
966 PropertyOffset Structure::getConcurrently(UniquedStringImpl* uid, unsigned& attributes)
967 {
968     PropertyOffset result = invalidOffset;
969     
970     forEachPropertyConcurrently(
971         [&] (const PropertyMapEntry& candidate) -> bool {
972             if (candidate.key != uid)
973                 return true;
974             
975             result = candidate.offset;
976             attributes = candidate.attributes;
977             return false;
978         });
979     
980     return result;
981 }
982
983 Vector<PropertyMapEntry> Structure::getPropertiesConcurrently()
984 {
985     Vector<PropertyMapEntry> result;
986
987     forEachPropertyConcurrently(
988         [&] (const PropertyMapEntry& entry) -> bool {
989             result.append(entry);
990             return true;
991         });
992     
993     return result;
994 }
995
996 PropertyOffset Structure::add(VM& vm, PropertyName propertyName, unsigned attributes)
997 {
998     return add<ShouldPin::No>(
999         vm, propertyName, attributes,
1000         [this] (const GCSafeConcurrentJSLocker&, PropertyOffset, PropertyOffset newLastOffset) {
1001             setLastOffset(newLastOffset);
1002         });
1003 }
1004
1005 PropertyOffset Structure::remove(PropertyName propertyName)
1006 {
1007     return remove(propertyName, [] (const ConcurrentJSLocker&, PropertyOffset) { });
1008 }
1009
1010 void Structure::getPropertyNamesFromStructure(VM& vm, PropertyNameArray& propertyNames, EnumerationMode mode)
1011 {
1012     PropertyTable* table = ensurePropertyTableIfNotEmpty(vm);
1013     if (!table)
1014         return;
1015     
1016     bool knownUnique = propertyNames.canAddKnownUniqueForStructure();
1017     
1018     PropertyTable::iterator end = table->end();
1019     for (PropertyTable::iterator iter = table->begin(); iter != end; ++iter) {
1020         ASSERT(!isQuickPropertyAccessAllowedForEnumeration() || !(iter->attributes & DontEnum));
1021         ASSERT(!isQuickPropertyAccessAllowedForEnumeration() || !iter->key->isSymbol());
1022         if (!(iter->attributes & DontEnum) || mode.includeDontEnumProperties()) {
1023             if (iter->key->isSymbol() && !propertyNames.includeSymbolProperties())
1024                 continue;
1025             if (knownUnique)
1026                 propertyNames.addUnchecked(iter->key);
1027             else
1028                 propertyNames.add(iter->key);
1029         }
1030     }
1031 }
1032
1033 void StructureFireDetail::dump(PrintStream& out) const
1034 {
1035     out.print("Structure transition from ", *m_structure);
1036 }
1037
1038 DeferredStructureTransitionWatchpointFire::DeferredStructureTransitionWatchpointFire()
1039     : m_structure(nullptr)
1040 {
1041 }
1042
1043 DeferredStructureTransitionWatchpointFire::~DeferredStructureTransitionWatchpointFire()
1044 {
1045     if (m_structure)
1046         m_structure->transitionWatchpointSet().fireAll(*m_structure->vm(), StructureFireDetail(m_structure));
1047 }
1048
1049 void DeferredStructureTransitionWatchpointFire::add(const Structure* structure)
1050 {
1051     RELEASE_ASSERT(!m_structure);
1052     RELEASE_ASSERT(structure);
1053     m_structure = structure;
1054 }
1055
1056 void Structure::didTransitionFromThisStructure(DeferredStructureTransitionWatchpointFire* deferred) const
1057 {
1058     // If the structure is being watched, and this is the kind of structure that the DFG would
1059     // like to watch, then make sure to note for all future versions of this structure that it's
1060     // unwise to watch it.
1061     if (m_transitionWatchpointSet.isBeingWatched())
1062         const_cast<Structure*>(this)->setTransitionWatchpointIsLikelyToBeFired(true);
1063     
1064     if (deferred)
1065         deferred->add(this);
1066     else
1067         m_transitionWatchpointSet.fireAll(*vm(), StructureFireDetail(this));
1068 }
1069
1070 JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
1071 {
1072     return prototypeForLookup(codeBlock->globalObject());
1073 }
1074
1075 void Structure::visitChildren(JSCell* cell, SlotVisitor& visitor)
1076 {
1077     Structure* thisObject = jsCast<Structure*>(cell);
1078     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1079
1080     JSCell::visitChildren(thisObject, visitor);
1081     
1082     ConcurrentJSLocker locker(thisObject->m_lock);
1083     
1084     visitor.append(thisObject->m_globalObject);
1085     if (!thisObject->isObject())
1086         thisObject->m_cachedPrototypeChain.clear();
1087     else {
1088         visitor.append(thisObject->m_prototype);
1089         visitor.append(thisObject->m_cachedPrototypeChain);
1090     }
1091     visitor.append(thisObject->m_previousOrRareData);
1092
1093     if (thisObject->isPinnedPropertyTable() || thisObject->isAddingPropertyForTransition()) {
1094         // NOTE: This can interleave in pin(), in which case it may see a null property table.
1095         // That's fine, because then the barrier will fire and we will scan this again.
1096         visitor.append(thisObject->m_propertyTableUnsafe);
1097     } else if (visitor.isBuildingHeapSnapshot())
1098         visitor.append(thisObject->m_propertyTableUnsafe);
1099     else if (thisObject->m_propertyTableUnsafe)
1100         thisObject->m_propertyTableUnsafe.clear();
1101
1102     visitor.append(thisObject->m_inferredTypeTable);
1103 }
1104
1105 bool Structure::isCheapDuringGC()
1106 {
1107     // FIXME: We could make this even safer by returning false if this structure's property table
1108     // has any large property names.
1109     // https://bugs.webkit.org/show_bug.cgi?id=157334
1110     
1111     return (!m_globalObject || Heap::isMarkedConcurrently(m_globalObject.get()))
1112         && (!storedPrototypeObject() || Heap::isMarkedConcurrently(storedPrototypeObject()));
1113 }
1114
1115 bool Structure::markIfCheap(SlotVisitor& visitor)
1116 {
1117     if (!isCheapDuringGC())
1118         return Heap::isMarkedConcurrently(this);
1119     
1120     visitor.appendUnbarriered(this);
1121     return true;
1122 }
1123
1124 bool Structure::prototypeChainMayInterceptStoreTo(VM& vm, PropertyName propertyName)
1125 {
1126     if (parseIndex(propertyName))
1127         return anyObjectInChainMayInterceptIndexedAccesses();
1128     
1129     for (Structure* current = this; ;) {
1130         JSValue prototype = current->storedPrototype();
1131         if (prototype.isNull())
1132             return false;
1133         
1134         current = prototype.asCell()->structure(vm);
1135         
1136         unsigned attributes;
1137         PropertyOffset offset = current->get(vm, propertyName, attributes);
1138         if (!JSC::isValidOffset(offset))
1139             continue;
1140         
1141         if (attributes & (ReadOnly | Accessor))
1142             return true;
1143         
1144         return false;
1145     }
1146 }
1147
1148 Ref<StructureShape> Structure::toStructureShape(JSValue value)
1149 {
1150     Ref<StructureShape> baseShape = StructureShape::create();
1151     RefPtr<StructureShape> curShape = baseShape.ptr();
1152     Structure* curStructure = this;
1153     JSValue curValue = value;
1154     while (curStructure) {
1155         curStructure->forEachPropertyConcurrently(
1156             [&] (const PropertyMapEntry& entry) -> bool {
1157                 curShape->addProperty(*entry.key);
1158                 return true;
1159             });
1160
1161         if (JSObject* curObject = curValue.getObject())
1162             curShape->setConstructorName(JSObject::calculatedClassName(curObject));
1163         else
1164             curShape->setConstructorName(curStructure->classInfo()->className);
1165
1166         if (curStructure->isDictionary())
1167             curShape->enterDictionaryMode();
1168
1169         curShape->markAsFinal();
1170
1171         if (curStructure->storedPrototypeStructure()) {
1172             auto newShape = StructureShape::create();
1173             curShape->setProto(newShape.copyRef());
1174             curShape = WTFMove(newShape);
1175             curValue = curStructure->storedPrototype();
1176         }
1177
1178         curStructure = curStructure->storedPrototypeStructure();
1179     }
1180     
1181     return baseShape;
1182 }
1183
1184 bool Structure::canUseForAllocationsOf(Structure* other)
1185 {
1186     return inlineCapacity() == other->inlineCapacity()
1187         && storedPrototype() == other->storedPrototype()
1188         && objectInitializationBlob() == other->objectInitializationBlob();
1189 }
1190
1191 void Structure::dump(PrintStream& out) const
1192 {
1193     out.print(RawPointer(this), ":[", classInfo()->className, ", {");
1194     
1195     CommaPrinter comma;
1196     
1197     const_cast<Structure*>(this)->forEachPropertyConcurrently(
1198         [&] (const PropertyMapEntry& entry) -> bool {
1199             out.print(comma, entry.key, ":", static_cast<int>(entry.offset));
1200             return true;
1201         });
1202     
1203     out.print("}, ", IndexingTypeDump(indexingType()));
1204     
1205     if (m_prototype.get().isCell())
1206         out.print(", Proto:", RawPointer(m_prototype.get().asCell()));
1207
1208     switch (dictionaryKind()) {
1209     case NoneDictionaryKind:
1210         if (hasBeenDictionary())
1211             out.print(", Has been dictionary");
1212         break;
1213     case CachedDictionaryKind:
1214         out.print(", Dictionary");
1215         break;
1216     case UncachedDictionaryKind:
1217         out.print(", UncacheableDictionary");
1218         break;
1219     }
1220
1221     if (transitionWatchpointSetIsStillValid())
1222         out.print(", Leaf");
1223     else if (transitionWatchpointIsLikelyToBeFired())
1224         out.print(", Shady leaf");
1225     
1226     out.print("]");
1227 }
1228
1229 void Structure::dumpInContext(PrintStream& out, DumpContext* context) const
1230 {
1231     if (context)
1232         context->structures.dumpBrief(this, out);
1233     else
1234         dump(out);
1235 }
1236
1237 void Structure::dumpBrief(PrintStream& out, const CString& string) const
1238 {
1239     out.print("%", string, ":", classInfo()->className);
1240 }
1241
1242 void Structure::dumpContextHeader(PrintStream& out)
1243 {
1244     out.print("Structures:");
1245 }
1246
1247 bool ClassInfo::hasStaticSetterOrReadonlyProperties() const
1248 {
1249     for (const ClassInfo* ci = this; ci; ci = ci->parentClass) {
1250         if (const HashTable* table = ci->staticPropHashTable) {
1251             if (table->hasSetterOrReadonlyProperties)
1252                 return true;
1253         }
1254     }
1255     return false;
1256 }
1257
1258 void Structure::setCachedPropertyNameEnumerator(VM& vm, JSPropertyNameEnumerator* enumerator)
1259 {
1260     ASSERT(!isDictionary());
1261     if (!hasRareData())
1262         allocateRareData(vm);
1263     rareData()->setCachedPropertyNameEnumerator(vm, enumerator);
1264 }
1265
1266 JSPropertyNameEnumerator* Structure::cachedPropertyNameEnumerator() const
1267 {
1268     if (!hasRareData())
1269         return nullptr;
1270     return rareData()->cachedPropertyNameEnumerator();
1271 }
1272
1273 bool Structure::canCachePropertyNameEnumerator() const
1274 {
1275     if (isDictionary())
1276         return false;
1277
1278     if (hasIndexedProperties(indexingType()))
1279         return false;
1280
1281     if (typeInfo().overridesGetPropertyNames())
1282         return false;
1283
1284     StructureChain* structureChain = m_cachedPrototypeChain.get();
1285     ASSERT(structureChain);
1286     WriteBarrier<Structure>* structure = structureChain->head();
1287     while (true) {
1288         if (!structure->get())
1289             break;
1290         if (structure->get()->typeInfo().overridesGetPropertyNames())
1291             return false;
1292         structure++;
1293     }
1294     
1295     return true;
1296 }
1297     
1298 bool Structure::canAccessPropertiesQuicklyForEnumeration() const
1299 {
1300     if (!isQuickPropertyAccessAllowedForEnumeration())
1301         return false;
1302     if (hasGetterSetterProperties())
1303         return false;
1304     if (isUncacheableDictionary())
1305         return false;
1306     return true;
1307 }
1308
1309 } // namespace JSC