com.oracle.truffle.object.ShapeImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of truffle-api Show documentation
Show all versions of truffle-api Show documentation
Truffle is a multi-language framework for executing dynamic languages
that achieves high performance when combined with Graal.
/*
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.object;
import static com.oracle.truffle.api.CompilerDirectives.shouldNotReachHere;
import static com.oracle.truffle.object.LocationImpl.neverValidAssumption;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import org.graalvm.collections.EconomicMap;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.object.DynamicObjectFactory;
import com.oracle.truffle.api.object.HiddenKey;
import com.oracle.truffle.api.object.Layout;
import com.oracle.truffle.api.object.Location;
import com.oracle.truffle.api.object.LocationFactory;
import com.oracle.truffle.api.object.ObjectType;
import com.oracle.truffle.api.object.Property;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.object.LocationImpl.LocationVisitor;
import com.oracle.truffle.object.Transition.AddPropertyTransition;
import com.oracle.truffle.object.Transition.ObjectFlagsTransition;
import com.oracle.truffle.object.Transition.ObjectTypeTransition;
import com.oracle.truffle.object.Transition.PropertyTransition;
import com.oracle.truffle.object.Transition.RemovePropertyTransition;
import com.oracle.truffle.object.Transition.ShareShapeTransition;
/**
* Shape objects create a mapping of Property objects to indexes. The mapping of those indexes to an
* actual store is not part of Shape's role, but DynamicObject's. Shapes are immutable; adding or
* deleting a property yields a new Shape which links to the old one. This allows inline caching to
* simply check the identity of an object's Shape to determine if the cache is valid. There is one
* exception to this immutability, the transition map, but that is used simply to assure that an
* identical series of property additions and deletions will yield the same Shape object.
*
* @see DynamicObject
* @see Property
* @since 0.17 or earlier
*/
@SuppressWarnings("deprecation")
public abstract class ShapeImpl extends Shape {
/** Shape and object flags. */
protected final int flags;
/** @since 0.17 or earlier */
protected final LayoutImpl layout;
/** @since 0.17 or earlier */
protected final Object objectType;
/** @since 0.17 or earlier */
protected final ShapeImpl parent;
/** @since 0.17 or earlier */
protected final PropertyMap propertyMap;
protected final Object sharedData;
private final ShapeImpl root;
/** @since 0.17 or earlier */
protected final int objectArraySize;
/** @since 0.17 or earlier */
protected final int objectArrayCapacity;
/** @since 0.17 or earlier */
protected final int objectFieldSize;
/** @since 0.17 or earlier */
protected final int primitiveFieldSize;
/** @since 0.17 or earlier */
protected final int primitiveArraySize;
/** @since 0.17 or earlier */
protected final int primitiveArrayCapacity;
/** @since 0.17 or earlier */
protected final boolean hasPrimitiveArray;
/** @since 0.17 or earlier */
protected final int depth;
/** @since 0.17 or earlier */
protected final int propertyCount;
/** @since 0.17 or earlier */
protected final Assumption validAssumption;
/** @since 0.17 or earlier */
@CompilationFinal protected volatile Assumption leafAssumption;
/**
* Shape transition map; lazily initialized. One of:
*
* - {@code null}: empty map
*
- {@link StrongKeyWeakValueEntry}: immutable single entry map
*
- {@link TransitionMap}: mutable multiple entry map
*
*
* @see #queryTransition(Transition)
* @see #addTransitionInternal(Transition, ShapeImpl)
*/
private volatile Object transitionMap;
private final Transition transitionFromParent;
private volatile PropertyAssumptions sharedPropertyAssumptions;
private static final AtomicReferenceFieldUpdater TRANSITION_MAP_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ShapeImpl.class, Object.class, "transitionMap");
private static final AtomicReferenceFieldUpdater LEAF_ASSUMPTION_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ShapeImpl.class, Assumption.class, "leafAssumption");
private static final AtomicReferenceFieldUpdater PROPERTY_ASSUMPTIONS_UPDATER = //
AtomicReferenceFieldUpdater.newUpdater(ShapeImpl.class, PropertyAssumptions.class, "sharedPropertyAssumptions");
/** Shared shape flag. */
protected static final int FLAG_SHARED_SHAPE = 1 << 16;
/** Flag that is set if {@link Shape.Builder#propertyAssumptions(boolean)} is true. */
protected static final int FLAG_ALLOW_PROPERTY_ASSUMPTIONS = 1 << 17;
/** Automatic flag that is set if the shape has instance properties. */
protected static final int FLAG_HAS_INSTANCE_PROPERTIES = 1 << 18;
/**
* Private constructor.
*
* @param parent predecessor shape
* @param transitionFromParent direct transition from parent shape
*
* @see #ShapeImpl(Layout, ShapeImpl, Object, Object, PropertyMap, Transition, BaseAllocator,
* int)
*/
private ShapeImpl(Layout layout, ShapeImpl parent, Object objectType, Object sharedData, PropertyMap propertyMap, Transition transitionFromParent, int objectArraySize, int objectFieldSize,
int primitiveFieldSize, int primitiveArraySize, boolean hasPrimitiveArray, int flags, Assumption singleContextAssumption) {
this.layout = (LayoutImpl) layout;
this.objectType = Objects.requireNonNull(objectType);
this.propertyMap = Objects.requireNonNull(propertyMap);
this.root = parent != null ? parent.getRoot() : this;
this.parent = parent;
this.objectArraySize = objectArraySize;
this.objectArrayCapacity = capacityFromSize(objectArraySize);
this.objectFieldSize = objectFieldSize;
this.primitiveFieldSize = primitiveFieldSize;
this.primitiveArraySize = primitiveArraySize;
this.primitiveArrayCapacity = capacityFromSize(primitiveArraySize);
this.hasPrimitiveArray = hasPrimitiveArray;
if (parent != null) {
this.propertyCount = makePropertyCount(parent, propertyMap, transitionFromParent);
this.depth = parent.depth + 1;
} else {
this.propertyCount = 0;
this.depth = 0;
}
this.validAssumption = createValidAssumption();
int allFlags = flags;
if ((allFlags & FLAG_HAS_INSTANCE_PROPERTIES) == 0) {
if (objectFieldSize != 0 || objectArraySize != 0 || primitiveFieldSize != 0 || primitiveArraySize != 0) {
allFlags |= FLAG_HAS_INSTANCE_PROPERTIES;
}
}
this.flags = allFlags;
this.transitionFromParent = transitionFromParent;
this.sharedData = sharedData;
assert parent == null || this.sharedData == parent.sharedData;
this.sharedPropertyAssumptions = parent == null && (flags & FLAG_ALLOW_PROPERTY_ASSUMPTIONS) != 0 && singleContextAssumption != null
? new PropertyAssumptions(singleContextAssumption)
: null;
shapeCount.inc();
if (ObjectStorageOptions.DumpShapes) {
Debug.trackShape(this);
}
}
/** @since 0.17 or earlier */
protected ShapeImpl(Layout layout, ShapeImpl parent, Object objectType, Object sharedData, PropertyMap propertyMap, Transition transition, Allocator allocator, int flags) {
this(layout, parent, objectType, sharedData, propertyMap, transition, ((BaseAllocator) allocator).objectArraySize, ((BaseAllocator) allocator).objectFieldSize,
((BaseAllocator) allocator).primitiveFieldSize, ((BaseAllocator) allocator).primitiveArraySize, ((BaseAllocator) allocator).hasPrimitiveArray, flags, null);
}
/** @since 0.17 or earlier */
@SuppressWarnings("hiding")
protected abstract ShapeImpl createShape(Layout layout, Object sharedData, ShapeImpl parent, Object objectType, PropertyMap propertyMap, Transition transition, Allocator allocator, int id);
/** @since 0.17 or earlier */
protected ShapeImpl(Layout layout, Object dynamicType, Object sharedData, int flags, Assumption constantObjectAssumption) {
this(layout, null, dynamicType, sharedData, PropertyMap.empty(), null, 0, 0, 0, 0, true, flags, constantObjectAssumption);
}
private static int makePropertyCount(ShapeImpl parent, PropertyMap propertyMap, Transition transitionFromParent) {
int thisSize = propertyMap.size();
int parentSize = parent.propertyMap.size();
if (thisSize > parentSize) {
Property lastProperty = propertyMap.getLastProperty();
if (!lastProperty.isHidden()) {
return parent.propertyCount + 1;
}
} else if (thisSize < parentSize && transitionFromParent instanceof RemovePropertyTransition) {
if (!(((RemovePropertyTransition) transitionFromParent).getPropertyKey() instanceof HiddenKey)) {
return parent.propertyCount - 1;
}
}
return parent.propertyCount;
}
/** @since 0.17 or earlier */
@Override
public final Property getLastProperty() {
return propertyMap.getLastProperty();
}
/** @since 0.17 or earlier */
@Override
public final int getId() {
return getObjectFlags(flags);
}
@Override
public final int getFlags() {
return getObjectFlags(flags);
}
public final int getFlagsInternal() {
return flags;
}
/**
* Calculate array size for the given number of elements.
*/
private static int capacityFromSize(int size) {
if (size == 0) {
return 0;
} else if (size <= 4) {
return 4;
} else if (size <= 8) {
return 8;
} else {
// round up to (3/2) * highestOneBit or the next power of 2, alternately;
// i.e., the next in the sequence: 8, 12, 16, 24, 32, 48, 64, 96, 128, ...
int hi = Integer.highestOneBit(size);
int cap = hi;
if (cap < size) {
cap = hi + (hi >>> 1);
if (cap < size) {
cap = hi << 1;
if (cap < size) {
// handle potential overflow
cap = size;
}
}
}
return cap;
}
}
/** @since 0.17 or earlier */
public final int getObjectArraySize() {
return objectArraySize;
}
/** @since 0.17 or earlier */
public final int getObjectFieldSize() {
return objectFieldSize;
}
/** @since 0.17 or earlier */
public final int getPrimitiveFieldSize() {
return primitiveFieldSize;
}
/** @since 0.17 or earlier */
public final int getObjectArrayCapacity() {
return objectArrayCapacity;
}
/** @since 0.17 or earlier */
public final int getPrimitiveArrayCapacity() {
return primitiveArrayCapacity;
}
/** @since 0.17 or earlier */
public final int getPrimitiveArraySize() {
return primitiveArraySize;
}
/** @since 0.17 or earlier */
public final boolean hasPrimitiveArray() {
return hasPrimitiveArray;
}
/**
* @return true if this shape has instance properties.
*/
@Override
protected boolean hasInstanceProperties() {
return (flags & FLAG_HAS_INSTANCE_PROPERTIES) != 0;
}
/**
* Get a property entry by string name.
*
* @param key the name to look up
* @return a Property object, or null if not found
* @since 0.17 or earlier
*/
@Override
@TruffleBoundary
public Property getProperty(Object key) {
return propertyMap.get(key);
}
/** @since 0.17 or earlier */
public final PropertyMap getPropertyMap() {
return propertyMap;
}
/** @since 0.17 or earlier */
public final void addDirectTransition(Transition transition, ShapeImpl next) {
assert next.getParent() == this && transition.isDirect();
addTransitionInternal(transition, next);
}
/** @since 0.17 or earlier */
public final void addIndirectTransition(Transition transition, ShapeImpl next) {
assert !isShared();
assert next.getParent() != this && !transition.isDirect();
addTransitionInternal(transition, next);
}
private void addTransitionInternal(Transition transition, ShapeImpl successor) {
CompilerAsserts.neverPartOfCompilation();
Object prev;
Object next;
do {
prev = TRANSITION_MAP_UPDATER.get(this);
if (prev == null) {
invalidateLeafAssumption();
next = newSingleEntry(transition, successor);
} else if (isSingleEntry(prev)) {
StrongKeyWeakValueEntry entry = asSingleEntry(prev);
Transition exTra = entry.getKey();
ShapeImpl exSucc = entry.getValue();
if (exSucc != null) {
next = newTransitionMap(exTra, exSucc, transition, successor);
} else {
next = newSingleEntry(transition, successor);
}
} else {
next = addToTransitionMap(transition, successor, prev);
}
if (prev == next) {
break;
}
} while (!TRANSITION_MAP_UPDATER.compareAndSet(this, prev, next));
}
private static Object newTransitionMap(Transition firstTransition, ShapeImpl firstShape, Transition secondTransition, ShapeImpl secondShape) {
TransitionMap map = newTransitionMap();
map.put(firstTransition, firstShape);
map.put(secondTransition, secondShape);
return map;
}
private static Object addToTransitionMap(Transition transition, ShapeImpl successor, Object prevMap) {
assert isTransitionMap(prevMap);
TransitionMap map = asTransitionMap(prevMap);
map.put(transition, successor);
return map;
}
private static TransitionMap newTransitionMap() {
return new TransitionMap<>();
}
@SuppressWarnings("unchecked")
private static TransitionMap asTransitionMap(Object map) {
return (TransitionMap) map;
}
private static boolean isTransitionMap(Object trans) {
return trans instanceof TransitionMap, ?>;
}
private static Object newSingleEntry(Transition transition, ShapeImpl successor) {
return new StrongKeyWeakValueEntry<>(transition, successor);
}
private static boolean isSingleEntry(Object trans) {
return trans instanceof StrongKeyWeakValueEntry;
}
@SuppressWarnings("unchecked")
private static StrongKeyWeakValueEntry asSingleEntry(Object trans) {
return (StrongKeyWeakValueEntry) trans;
}
/**
* @since 0.17 or earlier
* @deprecated use {@link #forEachTransition(BiConsumer)} instead.
*/
@Deprecated
public final Map getTransitionMapForRead() {
Map snapshot = new HashMap<>();
forEachTransition(new BiConsumer() {
@Override
public void accept(Transition t, ShapeImpl s) {
snapshot.put(t, s);
}
});
return snapshot;
}
public final void forEachTransition(BiConsumer consumer) {
Object trans = transitionMap;
if (trans == null) {
return;
} else if (isSingleEntry(trans)) {
StrongKeyWeakValueEntry entry = asSingleEntry(trans);
ShapeImpl shape = entry.getValue();
if (shape != null) {
Transition key = entry.getKey();
consumer.accept(key, shape);
}
} else {
assert isTransitionMap(trans);
TransitionMap map = asTransitionMap(trans);
map.forEach(consumer);
}
}
private ShapeImpl queryTransitionImpl(Transition transition) {
Object trans = transitionMap;
if (trans == null) {
return null;
} else if (isSingleEntry(trans)) {
StrongKeyWeakValueEntry entry = asSingleEntry(trans);
Transition key = entry.getKey();
if (transition.equals(key)) {
return entry.getValue();
} else {
return null;
}
} else {
assert isTransitionMap(trans);
TransitionMap map = asTransitionMap(trans);
return map.get(transition);
}
}
/** @since 0.17 or earlier */
public final ShapeImpl queryTransition(Transition transition) {
ShapeImpl cachedShape = queryTransitionImpl(transition);
if (cachedShape != null) {
shapeCacheHitCount.inc();
return cachedShape;
}
shapeCacheMissCount.inc();
return null;
}
public final R iterateTransitions(BiFunction consumer) {
Object trans = transitionMap;
if (trans == null) {
return null;
} else if (isSingleEntry(trans)) {
StrongKeyWeakValueEntry entry = asSingleEntry(trans);
ShapeImpl shape = entry.getValue();
if (shape != null) {
Transition key = entry.getKey();
return consumer.apply(key, shape);
}
return null;
} else {
assert isTransitionMap(trans);
TransitionMap map = asTransitionMap(trans);
return map.iterateEntries(consumer);
}
}
/**
* Add a new property in the map, yielding a new or cached Shape object.
*
* @param property the property to add
* @return the new Shape
* @since 0.17 or earlier
*/
@TruffleBoundary
@Override
public ShapeImpl addProperty(Property property) {
assert isValid();
return layout.getStrategy().addProperty(this, property);
}
/** @since 0.17 or earlier */
@TruffleBoundary
protected void onPropertyTransition(Property property) {
onPropertyTransitionWithKey(property.getKey());
}
final void onPropertyTransitionWithKey(Object propertyKey) {
if (allowPropertyAssumptions()) {
PropertyAssumptions propertyAssumptions = getPropertyAssumptions();
if (propertyAssumptions != null) {
propertyAssumptions.invalidatePropertyAssumption(propertyKey);
}
}
if (sharedData instanceof com.oracle.truffle.api.object.ShapeListener) {
((com.oracle.truffle.api.object.ShapeListener) sharedData).onPropertyTransition(propertyKey);
}
}
/** @since 0.17 or earlier */
@TruffleBoundary
@Override
public ShapeImpl defineProperty(Object key, Object value, int propertyFlags) {
return layout.getStrategy().defineProperty(this, key, value, propertyFlags, null);
}
/** @since 0.17 or earlier */
@TruffleBoundary
@Override
public ShapeImpl defineProperty(Object key, Object value, int propertyFlags, LocationFactory locationFactory) {
return layout.getStrategy().defineProperty(this, key, value, propertyFlags, locationFactory);
}
/** @since 0.17 or earlier */
protected ShapeImpl cloneRoot(ShapeImpl from, Object newSharedData) {
return createShape(from.layout, newSharedData, null, from.objectType, from.propertyMap, null, from.allocator(), from.flags);
}
/**
* Create a separate clone of a shape.
*
* @param newParent the cloned parent shape
* @since 0.17 or earlier
*/
protected final ShapeImpl cloneOnto(ShapeImpl newParent) {
ShapeImpl from = this;
ShapeImpl newShape = createShape(newParent.layout, newParent.sharedData, newParent, from.objectType, from.propertyMap, from.transitionFromParent, from.allocator(), newParent.flags);
shapeCloneCount.inc();
newParent.addDirectTransition(from.transitionFromParent, newShape);
return newShape;
}
/** @since 0.17 or earlier */
public final Transition getTransitionFromParent() {
return transitionFromParent;
}
/**
* Create a new shape that adds a property to the parent shape.
*
* @since 0.17 or earlier
*/
protected static ShapeImpl makeShapeWithAddedProperty(ShapeImpl parent, AddPropertyTransition addTransition) {
Property addend = addTransition.getProperty();
BaseAllocator allocator = parent.allocator().addLocation(addend.getLocation());
PropertyMap newPropertyMap = parent.propertyMap.putCopy(addend);
ShapeImpl newShape = parent.createShape(parent.layout, parent.sharedData, parent, parent.objectType, newPropertyMap, addTransition, allocator, parent.flags);
assert ((LocationImpl) addend.getLocation()).primitiveArrayCount() == 0 || newShape.hasPrimitiveArray;
assert newShape.depth == allocator.depth;
return newShape;
}
/**
* Create a new shape that reserves the primitive extension array field.
*
* @since 0.17 or earlier
*/
protected static ShapeImpl makeShapeWithPrimitiveExtensionArray(ShapeImpl parent, Transition transition) {
assert parent.getLayout().hasPrimitiveExtensionArray();
assert !parent.hasPrimitiveArray();
BaseAllocator allocator = parent.allocator().addLocation(parent.getLayout().getPrimitiveArrayLocation());
ShapeImpl newShape = parent.createShape(parent.layout, parent.sharedData, parent, parent.objectType, parent.propertyMap, transition, allocator, parent.flags);
assert newShape.hasPrimitiveArray();
assert newShape.depth == allocator.depth;
return newShape;
}
/**
* Are these two shapes related, i.e. do they have the same root?
*
* @param other Shape to compare to
* @return true if one shape is an upcast of the other, or the Shapes are equal
* @since 0.17 or earlier
*/
@Override
public boolean isRelated(Shape other) {
if (this == other) {
return true;
}
if (this.getRoot() == getRoot()) {
return true;
}
return false;
}
/**
* Get a list of all properties that this Shape stores.
*
* @return list of properties
* @since 0.17 or earlier
*/
@TruffleBoundary
@Override
public final List getPropertyList(Pred filter) {
ArrayDeque props = new ArrayDeque<>();
for (Iterator it = this.propertyMap.reverseOrderedValueIterator(); it.hasNext();) {
Property currentProperty = it.next();
if (!currentProperty.isHidden() && filter.test(currentProperty)) {
props.addFirst(currentProperty);
}
}
return Arrays.asList(props.toArray(new Property[0]));
}
/** @since 0.17 or earlier */
@TruffleBoundary
@Override
public final List getPropertyList() {
return Arrays.asList(getPropertyArray());
}
@TruffleBoundary
public final Property[] getPropertyArray() {
Property[] props = new Property[getPropertyCount()];
int i = props.length;
for (Iterator it = this.propertyMap.reverseOrderedValueIterator(); it.hasNext();) {
Property currentProperty = it.next();
if (!currentProperty.isHidden()) {
props[--i] = currentProperty;
}
}
return props;
}
/**
* Returns all (also hidden) Property objects in this shape.
*
* @param ascending desired order
* @since 0.17 or earlier
*/
@TruffleBoundary
@Override
public final List getPropertyListInternal(boolean ascending) {
Property[] props = new Property[this.propertyMap.size()];
int i = ascending ? props.length : 0;
for (Iterator it = this.propertyMap.reverseOrderedValueIterator(); it.hasNext();) {
Property current = it.next();
if (ascending) {
props[--i] = current;
} else {
props[i++] = current;
}
}
return Arrays.asList(props);
}
/**
* Get a list of all (visible) property names in insertion order.
*
* @return list of property names
* @since 0.17 or earlier
*/
@TruffleBoundary
@Override
public final List