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