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
5 changes: 5 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@
// MLIROwnedReference.h.
#define OWNED_RESULT_NAMED_ATTR_NAME "__owned_result_named"

// On a read through an interface's field that is owned under rc (MLIRGenImpl::InterfaceFieldAccess): a number
// of its own. A `ts.Load` only reads memory, so CSE would fold two reads of the same field into one - one
// reference taken, two given back. The number makes no two of them alike.
#define OWNED_READ_ID_ATTR_NAME "__owned_read"

// Marks a release MLIRGen put at the end of a hand-written `finally` for the exceptional leg only:
// what the scopes around the `try` owe once the exception carries on past it. The finally region
// is one region in MLIRGen but several copies after TryOpLowering - the copy the landing pad runs
Expand Down
28 changes: 27 additions & 1 deletion tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5243,12 +5243,23 @@ struct LoadOpLowering : public TsLlvmPattern<mlir_ts::LoadOp>
InterfaceAccessorCell::unwindBlockOf(loadOp));
};

// an owned read (InterfaceFieldAccess): the getter's result is retained, so what the slot holds is too
auto slotLoadFunc = [&](OpBuilder &builder, Location location) -> mlir::Value {
auto value = loadedValueFunc(builder, location);
retainOwnedInterfaceRead(loadOp, elementType, value, rewriter);
return value;
};

loadedValue = clh.conditionalExpressionLowering(loc, elementTypeConverted, accessorCell->isCell, getterCallFunc,
loadedValueFunc);
slotLoadFunc);
}
else
{
loadedValue = loadedValueFunc(rewriter, loc);
if (interfaceSymbolRefOp)
{
retainOwnedInterfaceRead(loadOp, elementType, loadedValue, rewriter);
}
}

if (!loadedValue)
Expand All @@ -5267,6 +5278,21 @@ struct LoadOpLowering : public TsLlvmPattern<mlir_ts::LoadOp>

return success();
}

private:
// A read through an interface's field that MLIRGen marked owned under rc: what a plain slot holds is retained,
// as the getter of a field filled by accessors retains its result
void retainOwnedInterfaceRead(mlir_ts::LoadOp loadOp, mlir::Type elementType, mlir::Value value,
ConversionPatternRewriter &rewriter) const
{
if (!tsLlvmContext->compileOptions.isRefCounted() || !loadOp->hasAttr(OWNED_RESULT_ATTR_NAME))
{
return;
}

OwnershipRoutineLogic orl(loadOp, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitRetainValue(elementType, value);
}
};

struct StoreOpLowering : public TsLlvmPattern<mlir_ts::StoreOp>
Expand Down
14 changes: 14 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -9393,6 +9393,17 @@ class MLIRGenImpl
{
value = builder.create<mlir_ts::LoadOp>(location, fieldRefType.getElementType(),
interfaceSymbolRefValue.getResult());

// Under rc the slot may name a cell of accessors (INTERFACE_ACCESSOR_CELL_TAG), and then the load
// calls the getter, which returns its result retained. So the load is owned on both paths: the
// lowering retains what a plain slot holds (LoadOpLowering), and a receiver takes the reference
// over or it is given back as a temporary (§9.30).
if (compileOptions.isRefCounted() && !isa<mlir_ts::FunctionType>(fieldInfo->type) &&
mth.ownsHeapMemory(location, fieldInfo->type))
{
value.getDefiningOp()->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr());
value.getDefiningOp()->setAttr(OWNED_READ_ID_ATTR_NAME, builder.getI32IntegerAttr(++ownedReads));
}
}
else
{
Expand Down Expand Up @@ -9444,6 +9455,9 @@ class MLIRGenImpl
// (InterfaceMethodInfo::genericSignature): the call unboxes its result (mlirGenCallExpression)
llvm::DenseMap<mlir::Operation *, SignatureDeclarationBase> erasedGenericCallees;

// the last OWNED_READ_ID_ATTR_NAME given
int ownedReads = 0;

// The result type of a call of the generic interface method `signature` for its type arguments: given,
// or inferred from the arguments. Null when they can't be had: the call's result stays `any`.
mlir::Type instantiateErasedGenericResultType(mlir::Location location, SignatureDeclarationBase signature,
Expand Down
18 changes: 18 additions & 0 deletions tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1702,12 +1702,25 @@ class OwnedReturnConsumptionPass
});

llvm::SmallVector<mlir::Operation *> discarded;
llvm::SmallVector<mlir::Operation *> unread;
module.walk([&](mlir::Operation *op) {
if (!op->hasAttr(OWNED_RESULT_ATTR_NAME) || op->hasAttr(OWNED_RESULT_CONSUMED_ATTR_NAME))
{
return;
}

// A read through an interface's field is owned only once it is lowered (InterfaceFieldAccess), so one
// nothing uses - what an assignment `i.f = v` leaves of the place it wrote - goes, rather than calling
// a getter to give its result back.
if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(op))
{
if (loadOp->use_empty() && loadOp.getReference().getDefiningOp<mlir_ts::InterfaceSymbolRefOp>())
{
unread.push_back(op);
return;
}
}

if (op->getNumResults() != 1 || !mth.ownsHeapMemory(op->getLoc(), op->getResult(0).getType()))
{
return;
Expand All @@ -1725,6 +1738,11 @@ class OwnedReturnConsumptionPass
discarded.push_back(op);
});

for (auto *op : unread)
{
op->erase();
}

mlir::OpBuilder builder(&getContext());
std::set<std::tuple<mlir::Operation *, mlir::Operation *, std::string>> placedAfterFinally;
for (auto *op : discarded)
Expand Down
11 changes: 11 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,8 @@ tslang_add_test(NAME test-compile-00-class-accessor-getter-only-abstract COMMAND
tslang_add_test(NAME test-compile-00-class-accessor-virtual COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts")
tslang_add_test(NAME test-compile-00-class-accessor-implements-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts")
tslang_add_test(NAME test-compile-00-object-literal-contextual-lambda COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts")
tslang_add_test(NAME test-compile-own-00-object-literal-contextual-lambda COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts")
tslang_add_test(NAME test-compile-00-interface-field-getter-owned COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_field_getter_owned.ts")
tslang_add_test(NAME test-compile-00-class-accessor-untyped-setter COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_untyped_setter.ts")
tslang_add_test(NAME test-compile-00-class-super COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_super.ts")
tslang_add_test(NAME test-compile-00-class-implicit-constructor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_implicit_constructor.ts")
Expand Down Expand Up @@ -1249,6 +1251,8 @@ tslang_add_test(NAME test-jit-00-class-accessor-getter-only-abstract COMMAND tes
tslang_add_test(NAME test-jit-00-class-accessor-virtual COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts")
tslang_add_test(NAME test-jit-00-class-accessor-implements-field COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts")
tslang_add_test(NAME test-jit-00-object-literal-contextual-lambda COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts")
tslang_add_test(NAME test-jit-own-00-object-literal-contextual-lambda COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts")
tslang_add_test(NAME test-jit-00-interface-field-getter-owned COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_field_getter_owned.ts")
tslang_add_test(NAME test-jit-00-class-accessor-untyped-setter COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_untyped_setter.ts")
tslang_add_test(NAME test-jit-00-class-super COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_super.ts")
tslang_add_test(NAME test-jit-00-class-implicit-constructor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_implicit_constructor.ts")
Expand Down Expand Up @@ -2262,6 +2266,7 @@ set(TSLANG_CORPUS
00class_accessor_virtual.ts
00class_accessor_implements_field.ts
00object_literal_contextual_lambda.ts
00interface_field_getter_owned.ts
00class_accessor_untyped_setter.ts
00class_accessor.ts
00class_accessor2.ts
Expand Down Expand Up @@ -4393,6 +4398,12 @@ add_test(NAME test-rc-conditional-named-const-release
COMMAND ${CMAKE_COMMAND} -DTSLANG=$<TARGET_FILE:tslang>
"-DFILE=${PROJECT_SOURCE_DIR}/test/tester/tests/00conditional_named_const_release.ts"
-P "${CMAKE_CURRENT_SOURCE_DIR}/conditional-named-const-release.cmake")
# A read through an interface field a getter may fill is owned under rc, and given back; no run can see
# the leak, so the IR is read.
add_test(NAME test-rc-interface-field-getter-owned
COMMAND ${CMAKE_COMMAND} -DTSLANG=$<TARGET_FILE:tslang>
"-DFILE=${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_field_getter_owned.ts"
-P "${CMAKE_CURRENT_SOURCE_DIR}/interface-field-getter-owned.cmake")

# A fresh object's field read after another allocation is the value just stored: the optimized IR
# loads nothing back, under none, rc and own (the allocator is declared as LLVM declares malloc).
Expand Down
76 changes: 76 additions & 0 deletions tslang/test/tester/interface-field-getter-owned.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Under rc a read through an interface's field is owned (00interface_field_getter_owned.ts): the field may be
# filled by a getter, which returns its result retained, so the lowering retains what a plain slot holds too.
# No run shows a leak, so the IR is read, after OwnedReturnConsumptionPass (--emit=mlir). Every read through
# an interface field in these functions is marked owned, and is taken over by its receiver or released exactly
# once; an assignment leaves no read of the place it wrote.
cmake_minimum_required(VERSION 3.17.3)
execute_process(COMMAND "${TSLANG}" --emit=mlir --no-default-lib -mm=rc "${FILE}"
OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result)
# the IR is printed to stderr
string(APPEND out "${err}")
if(NOT result EQUAL 0)
message(FATAL_ERROR "tslang failed (${result}):\n${out}")
endif()

# the body of a function, from its `ts.Func` to the next one
function(func_body function outVar)
string(FIND "${out}" "ts.Func @${function} " begin)
if(begin EQUAL -1)
message(FATAL_ERROR "no function `${function}` in:\n${out}")
endif()
string(SUBSTRING "${out}" ${begin} -1 body)
string(SUBSTRING "${body}" 1 -1 rest)
string(FIND "${rest}" "ts.Func @" end)
if(NOT end EQUAL -1)
math(EXPR end "${end} + 1")
string(SUBSTRING "${body}" 0 ${end} body)
endif()
set(${outVar} "${body}" PARENT_SCOPE)
endfunction()

# the reads through an interface field in `body`: the lines loading an InterfaceSymbolRef's result
function(interface_reads body outVar)
set(reads)
string(REGEX MATCHALL "%[0-9]+ = \"ts[.]InterfaceSymbolRef\"" refs "${body}")
foreach(ref IN LISTS refs)
string(REGEX MATCH "^%([0-9]+)" ignored "${ref}")
string(REGEX MATCHALL "%[0-9]+ = \"ts[.]Load\"[(]%${CMAKE_MATCH_1}[)][^\r\n]*" loads "${body}")
list(APPEND reads ${loads})
endforeach()
set(${outVar} "${reads}" PARENT_SCOPE)
endfunction()

# function name, then how many reads through an interface field it has
set(expected
"intoLocal:1"
"asTemporary:2"
"asArgument:1"
"returned:1"
"inLoop:1"
"storedLocal:1"
"stored:0")
foreach(entry IN LISTS expected)
string(REPLACE ":" ";" entry "${entry}")
list(GET entry 0 function)
list(GET entry 1 wanted)
func_body("${function}" body)
interface_reads("${body}" reads)
list(LENGTH reads count)
if(NOT count EQUAL wanted)
message(FATAL_ERROR "`${function}` has ${count} reads through an interface field, not ${wanted}:\n${body}")
endif()
foreach(read IN LISTS reads)
if(NOT read MATCHES "__owned_result")
message(FATAL_ERROR "`${function}` reads an interface field unowned:\n${read}\n${body}")
endif()
if(read MATCHES "__owned_result_consumed")
continue()
endif()
string(REGEX MATCH "^%([0-9]+)" ignored "${read}")
string(REGEX MATCHALL "\"ts[.]Release\"[(]%${CMAKE_MATCH_1}[)]" releases "${body}")
list(LENGTH releases n)
if(NOT n EQUAL 1)
message(FATAL_ERROR "`${function}` releases the read %${CMAKE_MATCH_1} ${n} times, not once:\n${body}")
endif()
endforeach()
endforeach()
Loading
Loading