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
57 changes: 57 additions & 0 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3708,3 +3708,60 @@ array_class_splice.ts crashing in the debug JIT on Ubuntu 22.04/24.04 with no ou

Tests `00rc_splice_result_owned.ts` (gc, rc, none; under own the test's re-insertion of the removed elements is
refused).

207. Leftovers of 195, 196, 198 and 205. Fixed:
- A literal given to a generic call whose function member returns an integer, where the type parameter is a number
from another argument (`takeG({ produce: () => 44 }, 1.5)` for `takeG<D>(o: Options<D>, d: D)`): "can't assign
'() => s32' to '() => number'", and with the arguments the other way round `D` was `1.5 | s32`. The literal is typed
by the parameter once the call's other arguments give D (inferObjectLiteralArgumentReceivers, as a literal whose
members' parameters wait for D already was); its members are read one by one for the inference, without making them -
a member made then kept the `() => s32` it was made with.
- An `any` holding an object literal written with integers (`{ code: 7 }`, an s32 field) cast to an object type of
numbers (`<{ code: number }>a`): it threw "the object's fields are not those of type". A layout with s32 in place of
some of the number fields (three at most) is read as itself and converted (castAnyToTupleOfNumbers). Not under
-mm=own, where the value merged from those reads is a second reference: there the cast still throws.
- Under -mm=own, an object literal leaving out an optional field of the tuple it is given to (`const o: { disc?: false;
cb } = { cb }`): "a value that borrows a field cannot be stored". The literal is made with the missing optional
fields, undefined, and so is the receiver's tuple as it is, where it was converted by reading its fields out of its
slot.
- The rest of a `T | null` (`const { a, ...rest } = u`, and `({ a, ...rest } = u)`): "the rest of a value of type
'null | T' can't be taken". It is T's, read as the pattern's other names read T's fields.

Not yet (both fixed in 208):
- Under -mm=own, a tuple literal given to a callee that keeps it (`k.keepOne(["a" + i, i])`): "this function does not
own it". The same tuple in a local first (`const t: [string, number] = ["a" + i, i]; k.keepOne(t)`) works.
- A literal held by a variable first (`const t = { produce: () => 45 }; const o: Options<number> = t`): `t`'s member is
`() => s32`, which is not `() => number` (integer literals are s32, user ruling).

Tests `00tslang_issue_207.ts` (all models) and `00tslang_issue_207_any.ts` (gc, rc, none).

208. The "not yet" of 207. Fixed:
- A literal held by a variable first, whose function member returns an integer, given as an interface whose member
returns a number (`const t = { produce: () => 45 }; const o: Options<number> = t`, a `let` as well, and
`readOptions(t)` for a parameter `o: Options<number>`): "field "produce" not matching type: '() => number' and
'() => s32'". Integer literals stay s32 (user ruling); the function is adapted, as it already was given as a
`() => number` value (`let f: () => number = one`). The interface's slot calls the field through a thunk, as it calls
a closure field, and the thunk converts the result (isResultWideningFieldFunction): the object is given as it is,
with no copy, and no box for -mm=own to refuse. Where the object is copied for another field, the copy keeps the
function as it is for the same thunk; a field of a constant object read as a function value is its function, named
(fewerParametersThunk).
- Under -mm=own, a tuple or object literal given to a callee that keeps it (`k.keepOne(["a" + i, i])`,
`k.keepObj({ s: "b" + i, n: i })`): "this function does not own it". The literal is built in a slot nothing owns; as
an argument it now goes into a local of its own, as `const t = [...]; k.keepOne(t)` puts it (ownedLiteralArgument):
the local gives it to a callee that keeps it, and gives it back where the callee only reads it. 2M calls of either
stay at about 5 MB. Only a literal of new values or string constants (one holding what it borrows, or a closure, is a
borrowing record, as it was), and not inside `&&`/`?:`, whose region does not reach the scope's end.
- Under -mm=own, the same directly in a `try` body, and a declared local there (`try { const t = ["u" + n, 1];
k.keepOne(t); }`): "an object literal that holds a value it owns is moved only into a local". The local is made in
front of the `try` and given its value by a store right before its retain; that retain is now the literal's, as an
initializer's is (recordRetainOf).

Not yet:
- Under -mm=own, a value moved in a `try` body that other statements of the body can throw before
(`try { f(); const t = ["b" + i, i]; k.keepOne(t); g(); }`): "moved here on some paths only". The unwind leg reached
before the local is given its value is not known to find it empty. One statement per `try`, or a loop in it, works.
- Under -mm=own, a callee that keeps a parameter and throws before keeping it (`keep(c) { if (...) throw "no";
this.items.push(c); }`) leaks the parameter: 1M throws of `k.keep(new C(i))` grow to about 60 MB. Not new here (a
class instance leaks the same way); the callee's unwind does not give back a kept parameter.

Tests `00tslang_issue_208.ts` (all models).
29 changes: 28 additions & 1 deletion tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,32 @@ class MLIRTypeHelper
return false;
}

// A function field without `this` (isObjectFieldFunctionWithoutThis) whose result is an integer where the
// interface's member returns a number (`{ produce: () => 45 }`, a `() => s32`, for `produce: () => number`): the
// slot's thunk calls it and converts the result (generateSynthMethodToCallField), as it calls a closure field. The
// parameters have to match (TSLANG 208)
bool isResultWideningFieldFunction(mlir::Location location, mlir::Type fieldType, mlir::Type memberType)
{
if (!isObjectFieldFunctionWithoutThis(fieldType) || isa<mlir_ts::BoundFunctionType>(fieldType))
{
return false;
}

auto srcType = GetFunctionType(fieldType);
auto destType = dyn_cast<mlir_ts::FunctionType>(memberType);
if (!srcType || !destType || srcType.getNumResults() != 1 || destType.getNumResults() != 1
|| !isa<mlir::IntegerType>(srcType.getResult(0)) || !isa<mlir_ts::NumberType>(destType.getResult(0)))
{
return false;
}

// the field as if it returned the member's number: then it has to match
mlir::Type aligned = isa<mlir_ts::HybridFunctionType>(fieldType)
? mlir::Type(mlir_ts::HybridFunctionType::get(context, srcType.getInputs(), destType.getResults(), srcType.isVarArg()))
: mlir::Type(mlir_ts::FunctionType::get(context, srcType.getInputs(), destType.getResults(), srcType.isVarArg()));
return TestFunctionTypesMatchWithObjectMethods(location, aligned, memberType).result == MatchResultType::Match;
}

// An object-literal method (`this` first) an interface's function member can call through a thunk that gives
// it as many arguments as it takes: it takes fewer parameters than the member (`next()` for `next(value?)`,
// the rest ignored, as JavaScript does), or more, each of them optional (`next(value?)` for `next()`). The
Expand Down Expand Up @@ -1722,7 +1748,8 @@ class MLIRTypeHelper
if (isa<mlir_ts::FunctionType>(fieldType) && fieldType != foundField.type
&& isObjectFieldFunctionWithoutThis(foundField.type))
{
if (TestFunctionTypesMatchWithObjectMethods(location, foundField.type, fieldType).result == MatchResultType::Match)
if (TestFunctionTypesMatchWithObjectMethods(location, foundField.type, fieldType).result == MatchResultType::Match
|| isResultWideningFieldFunction(location, foundField.type, fieldType))
{
return {mlir_ts::FieldInfo{id, fieldType, false, mlir_ts::AccessLevel::Public}, mlir::success()};
}
Expand Down
141 changes: 137 additions & 4 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,14 @@ namespace mlirgen
// (a closure, see MLIRTypeHelper::isObjectFieldFunctionWithoutThis) keeps its
// own type: cast to the interface's it would lose its captures. Its slot calls a
// thunk reading the field instead (mlirGenObjectVirtualTableDefinitionForInterface).
// ...unless its type is not the member's, nor one the slot's thunk converts (`matches` says: an s32 result for a
// number, isResultWideningFieldFunction, TSLANG 208). Then the clone's field is a function value of the member's
// type, without its `this` (a type literal's field, as `{ produce: () => number }` has), which the cast into the
// clone adapts the function to (fewerParametersThunk, functionValueAdapter).
static mlir::LogicalResult getInterfaceCloneFields(mlir::ArrayRef<mlir_ts::FieldInfo> srcFields,
InterfaceInfo::TypePtr interfaceInfo, mlir::MLIRContext *context,
SmallVector<mlir_ts::FieldInfo> &fields)
SmallVector<mlir_ts::FieldInfo> &fields,
llvm::function_ref<bool(mlir::Type, mlir::Type)> matches)
{
// an interface not declared (yet) has no fields to clone
if (!interfaceInfo)
Expand All @@ -84,6 +89,21 @@ namespace mlirgen
auto keepsOwnType = interfaceField != interfaceFields.end()
&& isa<mlir_ts::FunctionType>(interfaceField->type)
&& MLIRTypeHelper::isObjectFieldFunctionWithoutThis(origField.type);
if (keepsOwnType && !matches(origField.type, interfaceField->type))
{
auto memberType = cast<mlir_ts::FunctionType>(interfaceField->type);
mlir::ArrayRef<mlir::Type> inputs = memberType.getInputs();
if (!inputs.empty() && isa<mlir_ts::OpaqueType>(inputs.front()))
{
inputs = inputs.drop_front();
}

auto valueType =
mlir_ts::HybridFunctionType::get(context, inputs, memberType.getResults(), memberType.isVarArg());
fields.push_back(mlir_ts::FieldInfo{origField.id, valueType, origField.isConditional, origField.accessLevel});
continue;
}

fields.push_back(interfaceField != interfaceFields.end() && !keepsOwnType ? *interfaceField : origField);
}

Expand Down Expand Up @@ -3703,7 +3723,7 @@ namespace mlirgen

if (isa<mlir_ts::TupleType>(type) && !genContext.allowPartialResolve)
{
return castAnyToTuple(location, type, value, genContext);
return castAnyToTupleOfNumbers(location, type, value, genContext);
}

// a union of object shapes (`<Shape>a`): the shape whose layout the box's tuple has, the last
Expand Down Expand Up @@ -4124,6 +4144,32 @@ namespace mlirgen
mlir::Value MLIRGenImpl::fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type,
const GenContext &genContext)
{
// a field of a constant object (`const t = { produce: () => 45 }` folds to a constant of the functions'
// names) is that function, named (TSLANG 208): read as a value, it would be boxed (functionValueAdapter),
// which -mm=own takes for a second reference of the box where the object holding it is stored
if (auto extractOp = value.getDefiningOp<mlir_ts::ExtractPropertyOp>(); extractOp && extractOp.getPosition().size() == 1)
{
if (auto constantOp = extractOp.getObject().getDefiningOp<mlir_ts::ConstantOp>())
{
auto elements = dyn_cast<mlir::ArrayAttr>(constantOp.getValue());
auto position = extractOp.getPosition().front();
auto symbol = elements && position >= 0 && position < (int64_t)elements.size()
? dyn_cast<mlir::FlatSymbolRefAttr>(elements[position])
: mlir::FlatSymbolRefAttr();
if (symbol && isa<mlir_ts::FunctionType>(value.getType()))
{
auto symbolValue = builder.create<mlir_ts::SymbolRefOp>(location, value.getType(), symbol);
if (auto thunk = fewerParametersThunk(location, symbolValue, type, genContext))
{
return thunk;
}

symbolValue->erase();
return mlir::Value();
}
}
}

auto boundOp = value.getDefiningOp<mlir_ts::CreateBoundFunctionOp>();
auto symbolRefOp = boundOp ? boundOp.getFunc().getDefiningOp<mlir_ts::SymbolRefOp>()
: value.getDefiningOp<mlir_ts::SymbolRefOp>();
Expand Down Expand Up @@ -5418,6 +5464,85 @@ namespace mlirgen
return V(builder.create<mlir_ts::CastOp>(location, type, value));
}

// `any` to an object type with number fields (`<{ code: number }>a`): an object literal boxed as it is holds the s32
// of an integer it was written with (`{ code: 7 }`), a layout of its own, and the cast threw "the object's fields
// are not those of type". Each layout with s32 in place of some of the number fields (three of them at most) is
// read as itself and converted, as the literal given to the type is. Anything else is castAnyToTuple's, and so is
// every cast under -mm=own.
ValueOrLogicalResult MLIRGenImpl::castAnyToTupleOfNumbers(mlir::Location location, mlir::Type type, mlir::Value value,
const GenContext &genContext)
{
auto tupleType = dyn_cast<mlir_ts::TupleType>(type);
SmallVector<unsigned> numberFields;
if (tupleType)
{
for (auto [index, field] : enumerate(tupleType.getFields()))
{
if (isa<mlir_ts::NumberType>(field.type))
{
numberFields.push_back(index);
}
}
}

// (not under -mm=own: a value merged from the branches is a second reference it can't classify yet, and the
// plain read is refused with it)
if (numberFields.empty() || numberFields.size() > 3 || compileOptions.memoryModel == MemoryModelOwn)
{
return castAnyToTuple(location, type, value, genContext);
}

// the type's own layout first: it is the one a value of the type has
SmallVector<mlir::Type> layouts{type};
auto s32Type = builder.getIntegerType(32, true);
for (unsigned mask = 1; mask < (1u << numberFields.size()); ++mask)
{
SmallVector<mlir_ts::FieldInfo> fields(tupleType.getFields().begin(), tupleType.getFields().end());
for (auto [bit, fieldIndex] : enumerate(numberFields))
{
if (mask & (1u << bit))
{
fields[fieldIndex].type = s32Type;
}
}

layouts.push_back(getTupleType(fields));
}

std::function<ValueOrLogicalResult(size_t)> castOf = [&](size_t index) -> ValueOrLogicalResult {
if (index == layouts.size())
{
// none of them: the checked read, which says what the box holds
return castAnyToTuple(location, type, value, genContext);
}

auto holds = builder.create<mlir_ts::IsTupleOfLayoutOp>(location, getBooleanType(), value,
mlir::TypeAttr::get(layouts[index]));
auto ifOp = builder.create<mlir_ts::IfOp>(location, mlir::TypeRange{type}, holds, true);

builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
mlir::Value thenValue = builder.create<mlir_ts::CastOp>(location, layouts[index], value);
if (index > 0)
{
auto converted = cast(location, type, thenValue, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(converted)
thenValue = V(converted);
}

builder.create<mlir_ts::ResultOp>(location, mlir::ValueRange{thenValue});

builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
auto elseValue = castOf(index + 1);
EXIT_IF_FAILED_OR_NO_VALUE(elseValue)
builder.create<mlir_ts::ResultOp>(location, mlir::ValueRange{V(elseValue)});

builder.setInsertionPointAfter(ifOp);
return V(ifOp.getResults().front());
};

return castOf(0);
}

ValueOrLogicalResult MLIRGenImpl::castAnyToUnionOfTuples(mlir::Location location, mlir_ts::UnionType unionType,
mlir::Value value, const GenContext &genContext)
{
Expand Down Expand Up @@ -6002,7 +6127,11 @@ namespace mlirgen
if (mlir::failed(mth.canCastTupleToInterface(location, srcTuple, interfaceInfo, true)))
{
SmallVector<mlir_ts::FieldInfo> fields;
if (mlir::failed(getInterfaceCloneFields(srcTuple.getFields(), interfaceInfo, builder.getContext(), fields)))
if (mlir::failed(getInterfaceCloneFields(srcTuple.getFields(), interfaceInfo, builder.getContext(), fields,
[&](mlir::Type src, mlir::Type dest) {
return mth.TestFunctionTypesMatchWithObjectMethods(location, src, dest).result == MatchResultType::Match
|| mth.isResultWideningFieldFunction(location, src, dest);
})))
{
return mlir::failure();
}
Expand Down Expand Up @@ -6130,7 +6259,11 @@ namespace mlirgen
if (mlir::failed(mth.canCastTupleToInterface(location, storageTuple, interfaceInfo, true)))
{
SmallVector<mlir_ts::FieldInfo> fields;
if (mlir::failed(getInterfaceCloneFields(storageTuple.getFields(), interfaceInfo, builder.getContext(), fields)))
if (mlir::failed(getInterfaceCloneFields(storageTuple.getFields(), interfaceInfo, builder.getContext(), fields,
[&](mlir::Type src, mlir::Type dest) {
return mth.TestFunctionTypesMatchWithObjectMethods(location, src, dest).result == MatchResultType::Match
|| mth.isResultWideningFieldFunction(location, src, dest);
})))
{
return mlir::failure();
}
Expand Down
Loading
Loading