Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/own-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -698,9 +698,10 @@ a reference gives it back on every path out of a function.

- The default library has an `-mm=own` build, and arrays, strings and their methods work. `Map`
and `Set` work with number, boolean and string keys and values (`new Map<string, number>()`,
`new Set([1, 2])`): their iterators borrow the container, and strings go in as copies. With
`any` or object keys or values they do not compile yet, which includes a `new Map()` with no
type arguments and nothing to infer them from.
`new Set([1, 2])`): their iterators borrow the container, and strings go in as copies. An
object goes in as a `Shared<T>` handle (`new Map<string, Shared<Node>>()`); a plain object or
`any` key or value is a compile error that points at `Shared<T>`, which includes a `new Map()`
with no type arguments and nothing to infer them from.
- Array methods that keep elements of the source in a new array (`filter` over class instances)
give each such element a second owner, which is an error by design. Use `Shared<T>` elements,
or build the result from copies.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ kinds:

## 4. Not here

- `any` or object keys and values. The constructor from an array (`new Map([[k, v]])`) cannot take
- `any` or object keys and values (settled in section 6: through `Shared<T>`). The constructor from an array (`new Map([[k, v]])`) cannot take
the elements out of the caller's array, and moving an object parameter into a tuple
(`Retain` of a tuple made of kept parameters) is "takes a second reference". This waits on the
ruling on containers of owned values (two sets sharing an element by `union` is two owners).
Expand All @@ -103,3 +103,39 @@ Positive, under own (AOT and JIT): `own_generator_method_this`, `own_string_copy
`own_length_drops_elements`, `own_tuple_param_kept`; each also prints the same under gc, rc and none.
Errors: `own_err_generator_method_reassigned`, `own_err_callback_method_overridden`.
Retired: `own_err_param_kept_some_paths` (rule 5), `own_err_string_call_keeps_twice` (rule 4).

## 6. Objects in `Map` and `Set`: `Shared<T>`

Ruling (2026-10-26): under own an object goes into a `Map` or `Set` as a `Shared<T>` handle; a plain
object or `any` element is a compile error at the user's code that points at `Shared<T>`. A container
keeps what it is given and hands out borrows of it (`get`, the iterators), and `union` or two maps
holding one value would be two owners of a block with one owner. A handle is counted (spec 23.2),
so it can be in any number of entries; values and strings (copied in, rule 4) need nothing.

- **`@sharedElements`** (`SHARED_ELEMENTS_DECORATOR`), on a generic class: under own each type
argument has to be a value (owns no heap memory), a string, or a handle (`isSharedHandleType`, so
`Shared<T> | null` too). `checkSharedElements` runs where the class is specialized
(`instantiateSpecializedClassType`, both overloads), with the location of the user's `new` or type
annotation, before the members are generated, whose errors would point into the library:
`-mm=own: 'Map' cannot hold 'Node' (its 'V'): an element has to be a value, a string or a Shared<T>
handle; use 'Shared<Node>'`, and for `any` `give it one of those types`. Keys are checked as values
are. A `new` whose inferred type arguments were refused does not go on to the defaults
(`sharedElementsRefused`), which would report `any` too. The other models ignore it. DefaultLib puts
it on `Map` and `Set`; nothing in the compiler names them.
- **A handle in a tuple entry** (`copyIntoTuple`): a tuple made of a handle beside borrowed strings
retains the handle for the tuple, as it copies the strings (`<MapEntry<K, V>>[hash, next, key, value]`).
- **A handle a yield takes out of the state.** A field read only to be yielded
(`OWN_YIELDED_FIELDS_ATTR_NAME`) gives its value to the caller, who owns the record `next` returns
and releases it; the state's release of the old value is erased. A handle's counting is rc's and
stays (spec 23.2), and that kept this release too: each step released the previous handle twice,
once in the state and once in the caller (a `Map` of two handles walked by `for...of` freed the
first). The release of a yielded field is now erased for a handle as for anything else.
- **The owned result of a virtual call** (`OwnedReturnConsumptionPass`): whether every method a
vtable call can reach returns its result owned was decided over every method of that name in the
module, so with the default library loaded `A.get` stood beside `Headers.get` and the like, the
call was not +1, and an rc handle it returned leaked. Now only methods of a class on the receiver's
chain (its bases and the classes extending it) count (`onReceiverChain`).

Tests: `own_shared_elements` (a local `@sharedElements` container of numbers, strings and handles,
under every model), `own_shared_yield_count` (two entries walked, a pair yielded, a `break`; counts
under rc and own), `own_err_shared_elements_object`, `_any`, `_inferred`.
5 changes: 5 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,11 @@
// `@value class C` / `@value interface R`: a type whose values are copied, not shared - no identity,
// no vtable, no base (docs/superpowers/specs/2026-10-24-value-types-design.md)
#define VALUE_DECORATOR "value"
// `@sharedElements class Map<K, V>`: a container that keeps what it is given and hands out
// borrows of it. Under -mm=own each of its type arguments has to be a value, a string (copied) or
// a Shared<T> handle (counted): an object, whose block has one owner, goes through Shared<T>.
// The other memory models ignore it.
#define SHARED_ELEMENTS_DECORATOR "sharedElements"
// On a `ts.ThisVirtualSymbolRef` (a method's) or a `ts.VirtualSymbolRef` (an accessor's): the
// receiver's class is @final, but defined in another module, so the call still goes through the
// vtable. The slot holds the method the reference names, which
Expand Down
8 changes: 8 additions & 0 deletions tslang/lib/TypeScript/MLIRGenExpressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,8 @@ namespace mlirgen
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto value = V(result);
auto unspecialized = deferDefaults ? value : mlir::Value();
MLIRValueGuard<bool> sharedElementsRefusedGuard(sharedElementsRefused);
sharedElementsRefused = false;

// `new Set([2, 4, 6, 8])`: a generic class written without type arguments takes them from
// its constructor's arguments (see inferClassTypeFromConstructorArguments). Ahead of the
Expand Down Expand Up @@ -1341,6 +1343,12 @@ namespace mlirgen
}
}

// the inferred type arguments were refused (checkSharedElements): already reported
if (sharedElementsRefused)
{
return mlir::failure();
}

// `const m: Map<string, number[]> = new Map()`: a generic class written without type
// arguments takes them from the type it is given to, when that is the same class. Its
// type parameter defaults (`Map<K = any, V = any>`) made Map<any, any> otherwise, a
Expand Down
71 changes: 71 additions & 0 deletions tslang/lib/TypeScript/MLIRGenGenerics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,66 @@ namespace mlirgen
return {mlir::success(), funcProto};
}

// A @sharedElements container (Map, Set) keeps what it is given and hands out borrows of it, so
// under -mm=own each type argument has to be a value, a string (copied in) or a Shared<T> handle
// (counted in). Checked where the user names the type, before its members are generated: their
// errors would point into the library.
mlir::LogicalResult MLIRGenImpl::checkSharedElements(mlir::Location location,
GenericClassInfo::TypePtr genericClassInfo,
const GenContext &genericTypeGenContext,
const GenContext &genContext)
{
if (compileOptions.memoryModel != MemoryModelOwn)
{
return mlir::success();
}

auto sharedElements = false;
iterateDecorators(genericClassInfo->classDeclaration, genContext, [&](StringRef name, SmallVector<StringRef> args) {
sharedElements = sharedElements || name == SHARED_ELEMENTS_DECORATOR;
});
if (!sharedElements)
{
return mlir::success();
}

MLIRTypeHelper mth(builder.getContext(), compileOptions);
auto result = mlir::success();
for (auto &typeParam : genericClassInfo->typeParams)
{
auto found = genericTypeGenContext.typeParamsWithArgs.find(typeParam->getName());
if (found == genericTypeGenContext.typeParamsWithArgs.end())
{
continue;
}

auto type = mth.stripLiteralType(std::get<1>(found->getValue()));
if (!type || mlir::isa<mlir_ts::NamedGenericType>(type) || mlir::isa<mlir_ts::StringType>(type) ||
MLIRTypeHelper::isSharedHandleType(type) || !mth.ownsHeapMemory(location, type))
{
continue;
}

auto diag = emitError(location) << "-mm=own: '" << genericClassInfo->name << "' cannot hold '" << to_print(type)
<< "' (its '" << typeParam->getName()
<< "'): an element has to be a value, a string or a Shared<T> handle; ";
if (mlir::isa<mlir_ts::AnyType, mlir_ts::UnknownType>(type))
{
diag << "give it one of those types";
}
else
{
diag << "use 'Shared<" << to_print(type) << ">'";
}

result = mlir::failure();
}

sharedElementsRefused = sharedElementsRefused || mlir::failed(result);

return result;
}

std::pair<mlir::LogicalResult, mlir::Type> MLIRGenImpl::instantiateSpecializedClassType(mlir::Location location,
mlir_ts::ClassType genericClassType,
NodeArray<TypeNode> typeArguments,
Expand Down Expand Up @@ -1205,6 +1265,11 @@ namespace mlirgen
declarationMode = false;

// create new instance of interface with TypeArguments
if (mlir::failed(checkSharedElements(location, genericClassInfo, genericTypeGenContext, genContext)))
{
return {mlir::failure(), mlir::Type()};
}

auto ownLayout = suspendValueLayoutFrames();
if (mlir::failed(std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext))))
{
Expand Down Expand Up @@ -1288,6 +1353,12 @@ namespace mlirgen
MLIRValueGuard<bool> declarationModeGuard(declarationMode);
declarationMode = false;

if (mlir::failed(checkSharedElements(location, genericClassInfo, genericTypeGenContext, genContext)))
{
count--;
return {mlir::failure(), mlir::Type()};
}

auto ownLayout = suspendValueLayoutFrames();
auto res = std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext));
count--;
Expand Down
7 changes: 7 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1652,6 +1652,9 @@ class MLIRGenImpl
const GenContext &genContext,
bool allowNamedGenerics = false);

mlir::LogicalResult checkSharedElements(mlir::Location location, GenericClassInfo::TypePtr genericClassInfo,
const GenContext &genericTypeGenContext, const GenContext &genContext);

mlir_ts::ClassType inferClassTypeFromConstructorArguments(mlir::Location location,
GenericClassInfo::TypePtr genericClassInfo,
NodeArray<Expression> arguments,
Expand Down Expand Up @@ -15859,6 +15862,10 @@ class MLIRGenImpl
// on it (mlirGenOptionalChain)
llvm::DenseMap<const void *, mlir::Value> optionalChainObjects;

// set when checkSharedElements refuses a type argument: a `new` whose inferred type arguments
// were refused does not go on to the defaults (`any`), which would only be refused again
bool sharedElementsRefused = false;

// the declaration (no body) each declared function's full name came from, and the module it was
// generated into - discovery's is thrown away, and a library's __decls is parsed again for the
// next pass; see mlirGen(FunctionDeclaration)
Expand Down
74 changes: 63 additions & 11 deletions tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ class OwnedReturnConsumptionPass
}

llvm::DenseSet<mlir::StringRef> returnsOwned;
// Every method in the module, grouped by the name after the last dot: the candidate set
// for a virtual call, see virtualCallReturnsOwned.
llvm::StringMap<llvm::SmallVector<mlir::StringRef>> methodsByMemberName;
// Every method in the module, grouped by the name after the last dot, with the class it
// takes first: the candidate set for a virtual call, see virtualCallReturnsOwned.
llvm::StringMap<llvm::SmallVector<std::pair<mlir::StringRef, mlir::Type>>> methodsByMemberName;
// Is there any function here at all that hands back a heap value without retaining it?
// See callThroughValueReturnsOwned.
auto anyUnclassifiedOwningReturn = false;
Expand Down Expand Up @@ -121,7 +121,7 @@ class OwnedReturnConsumptionPass
auto dot = name.rfind('.');
if (isClassMethod && dot != mlir::StringRef::npos && dot + 1 < name.size())
{
methodsByMemberName[name.substr(dot + 1)].push_back(name);
methodsByMemberName[name.substr(dot + 1)].push_back({name, inputs.front()});
}
});

Expand Down Expand Up @@ -2274,7 +2274,7 @@ class OwnedReturnConsumptionPass
// callee's return had added. See section 9.53.
static bool virtualCallReturnsOwned(mlir_ts::CallIndirectOp callOp,
const llvm::DenseSet<mlir::StringRef> &returnsOwned,
const llvm::StringMap<llvm::SmallVector<mlir::StringRef>> &methodsByMemberName)
const llvm::StringMap<llvm::SmallVector<std::pair<mlir::StringRef, mlir::Type>>> &methodsByMemberName)
{
if (callOp.getNumOperands() == 0)
{
Expand All @@ -2293,13 +2293,56 @@ class OwnedReturnConsumptionPass
return false;
}

return everyOverrideReturnsOwned(virtualRefOp.getIdentifier(), returnsOwned, methodsByMemberName);
return everyOverrideReturnsOwned(virtualRefOp.getIdentifier(), returnsOwned, methodsByMemberName,
virtualRefOp.getThisVal().getType());
}

// Is `classType` the class `receiverType` names, or on its chain of bases or derived classes? A
// method of another class shares the member name only: no object of the receiver's type has
// it in that slot. A base is the first field of a class's storage; a class whose storage this
// cannot see may be on the chain.
static bool onReceiverChain(mlir::Type classType, mlir::Type receiverType)
{
auto storageOf = [](mlir::Type type) {
if (auto refClass = mlir::dyn_cast<mlir_ts::ClassType>(type))
{
return mlir::dyn_cast<mlir_ts::ClassStorageType>(refClass.getStorageType());
}

return mlir::dyn_cast<mlir_ts::ClassStorageType>(type);
};

auto candidate = storageOf(classType);
auto receiver = storageOf(receiverType);
if (!candidate || !receiver)
{
return true;
}

auto extends = [](mlir_ts::ClassStorageType derived, mlir_ts::ClassStorageType base) {
for (auto depth = 0; derived && depth < 64; ++depth)
{
if (derived.getName() == base.getName())
{
return true;
}

auto fields = derived.getFields();
derived = fields.empty() ? mlir_ts::ClassStorageType() : mlir::dyn_cast<mlir_ts::ClassStorageType>(fields.front().type);
}

return false;
};

return extends(candidate, receiver) || extends(receiver, candidate);
}

// Does every method that can be in the slot `identifier` was written against return owned?
// With the receiver's type, only methods of classes on its chain can be there.
static bool everyOverrideReturnsOwned(mlir::StringRef identifier,
const llvm::DenseSet<mlir::StringRef> &returnsOwned,
const llvm::StringMap<llvm::SmallVector<mlir::StringRef>> &methodsByMemberName)
const llvm::StringMap<llvm::SmallVector<std::pair<mlir::StringRef, mlir::Type>>> &methodsByMemberName,
mlir::Type receiverType = mlir::Type())
{
auto dot = identifier.rfind('.');
if (dot == mlir::StringRef::npos || dot + 1 >= identifier.size())
Expand All @@ -2313,15 +2356,24 @@ class OwnedReturnConsumptionPass
return false;
}

for (auto candidate : candidates->second)
// none on the chain: the method is not one this module has, unclassified
auto any = false;
for (auto [candidate, classType] : candidates->second)
{
if (receiverType && !onReceiverChain(classType, receiverType))
{
continue;
}

if (!returnsOwned.contains(candidate))
{
return false;
}

any = true;
}

return true;
return any;
}

// The same question for a call through an interface, where the member name is not enough to
Expand Down Expand Up @@ -2426,7 +2478,7 @@ class OwnedReturnConsumptionPass
// name), or an interface slot (what the vtables put there). A getter given as anything
// else - `ts.Undef` when there is only a setter - is unclassified.
static bool getterReturnsOwned(mlir::Operation *op, const llvm::DenseSet<mlir::StringRef> &returnsOwned,
const llvm::StringMap<llvm::SmallVector<mlir::StringRef>> &methodsByMemberName,
const llvm::StringMap<llvm::SmallVector<std::pair<mlir::StringRef, mlir::Type>>> &methodsByMemberName,
const llvm::StringMap<llvm::DenseMap<int64_t, mlir::StringRef>> &vtableSlots)
{
auto named = [&](mlir::FlatSymbolRefAttr getter) {
Expand Down Expand Up @@ -2459,7 +2511,7 @@ class OwnedReturnConsumptionPass
if (auto thisVirtualSymbolRefOp = mlir::dyn_cast<mlir_ts::ThisVirtualSymbolRefOp>(definingOp))
{
return everyOverrideReturnsOwned(thisVirtualSymbolRefOp.getIdentifier(), returnsOwned,
methodsByMemberName);
methodsByMemberName, thisVirtualSymbolRefOp.getThisVal().getType());
}

if (auto interfaceRefOp = mlir::dyn_cast<mlir_ts::InterfaceSymbolRefOp>(definingOp))
Expand Down
Loading
Loading