diff --git a/docs/how/wasm/test/wasm_skips.txt b/docs/how/wasm/test/wasm_skips.txt index a2468fa71..bdd46a316 100644 --- a/docs/how/wasm/test/wasm_skips.txt +++ b/docs/how/wasm/test/wasm_skips.txt @@ -11,7 +11,6 @@ internals.ts # inline_asm with x86 instructions fetch.ts # (default library) fetch(): the host has no network, so the request throws # compiler gaps on wasm, each to be fixed and taken off this list -00object_func2.ts # a function called through a pointer of another signature: wasm's call_indirect traps 00class_accessor_implements_field.ts wasm32 # interface accessor cell tag (address + 0x80000000) folded into an i32.const: wasm-ld "LEB is outside Varint32 range" 00interface_field_getter_owned.ts wasm32 # interface accessor cell tag (address + 0x80000000) folded into an i32.const: wasm-ld "LEB is outside Varint32 range" 00class_accessor_increment.ts wasm32 # the same accessor cell tag (--di --opt_level=0 programs) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 721e001cf..b11b9bc33 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -3,6 +3,9 @@ #include "MLIRGenImpl.h" #include "TypeScript/MLIRLogic/MLIRRTTIHelperVC.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/xxhash.h" + // the RTTI helper undefines it on the way out #undef DEBUG_TYPE #define DEBUG_TYPE "mlir" @@ -2454,6 +2457,160 @@ namespace mlirgen mlir::FlatSymbolRefAttr::get(builder.getContext(), thunkName)); } + // A bound method given as a function type that takes more parameters than the method does, the extra ones + // first: `call_func(user.sayHi, user)` where `call_func` takes `(o: object) => void` (an object parameter + // first is taken as a `this` when the types are matched). The function value is called with its `this` and + // every argument the type says - `sayHi(user, user)` - which natively the method got away with, and which + // wasm's call_indirect checks against the signature and traps on. What the method's `this` is, and the method + // itself, are known only at run time (read from a field, `user.sayHi`), so the adapter cannot name it: the + // bound method goes into a box, as a closure's captures do - the box and the adapter bound to it are again two + // words, as a bound method's `this` and its function are - and the adapter calls the method with its `this` + // and the last arguments, as many as the method takes. Null where it is not that. + mlir::Value MLIRGenImpl::boundMethodWiderTypeAdapter(mlir::Location location, mlir::Value value, mlir::Type type, + const GenContext &genContext) + { + // -mm=own does not take a bound method given as a function value yet ("takes a second reference"), and + // says so where it is given; an adapter would only add an error of its own, without a place in the source + auto boundType = dyn_cast(value.getType()); + if (compileOptions.memoryModel == MemoryModelOwn || !boundType + || !isa(type)) + { + return mlir::Value(); + } + + auto methodType = mth.GetFunctionType(boundType); + auto destType = mth.GetFunctionType(type); + if (!methodType || !destType || methodType.getNumInputs() == 0 || methodType.isVarArg() || methodType.isCVarArg() + || destType.isVarArg() || destType.isCVarArg()) + { + return mlir::Value(); + } + + // the method's own parameters, after its `this`, are the type's last ones + auto ownParams = methodType.getNumInputs() - 1; + if (destType.getNumInputs() <= ownParams) + { + return mlir::Value(); + } + + auto isVoid = [](mlir::TypeRange results) { + return results.empty() || (results.size() == 1 && isa(results.front())); + }; + + if (!(methodType.getResults() == destType.getResults() + || (isVoid(methodType.getResults()) && isVoid(destType.getResults())))) + { + return mlir::Value(); + } + + auto thisType = methodType.getInput(0); + // the bound method itself, its `this` and its function: a bound method keeps its receiver as every + // memory model expects one to (under rc a reference to it, with the receiver's own type tag) + SmallVector fields{ + {MLIRHelper::TupleFieldName("method", builder.getContext()), boundType, false, mlir_ts::AccessLevel::Public}}; + auto boxStorageType = mlir_ts::TupleType::get(builder.getContext(), fields); + auto boxType = mlir_ts::RefType::get(boxStorageType); + + SmallVector thunkInputs{boxType}; + thunkInputs.append(destType.getInputs().begin(), destType.getInputs().end()); + auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), thunkInputs, destType.getResults(), false); + + // one adapter for each pair of types: the name is the types', printed (deterministic, unlike their pointers) + std::string typesText; + llvm::raw_string_ostream typesStream(typesText); + typesStream << methodType << "|" << thunkType; + auto thunkName = ".bound_adapter." + llvm::utohexstr(llvm::xxh3_64bits(typesText)); + if (!theModule.lookupSymbol(thunkName)) + { + mlir::OpBuilder::InsertionGuard guard(builder); + + mlir::Location noLocation = mlir::UnknownLoc::get(builder.getContext()); + auto funcOp = mlir_ts::FuncOp::create(noLocation, thunkName, thunkType); + funcOp.setPrivate(); + funcOp->setAttr("internal_linkage", builder.getUnitAttr()); + + // with --di a subprogram of its own at the file's place, as virtualSlotAdapterThunk's + DITableScopeT debugFuncScope(debugScope); + auto fileLoc = location->findInstanceOf(); + if (!fileLoc) + { + fileLoc = mlir::FileLineColLoc::get(builder.getStringAttr(mainSourceFileName), 1, 1); + } + + if (compileOptions.generateDebugInfo && fileLoc) + { + MLIRDebugInfoHelper mdi(builder, debugScope); + mlir::Location plainLocation = fileLoc; + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + noLocation = locFuseWithScope(plainLocation); + } + + auto &entryBlock = *funcOp.addEntryBlock(); + builder.setInsertionPointToStart(&entryBlock); + + auto results = methodType.getResults(); + auto hasResult = !results.empty() && !isa(results.front()); + auto entryOp = builder.create( + noLocation, hasResult ? mlir::Type(mlir_ts::RefType::get(results.front())) : mlir::Type()); + + auto box = entryBlock.getArgument(0); + auto boundRef = builder.create(noLocation, mlir_ts::RefType::get(boundType), box, + builder.getI32IntegerAttr(0)); + auto bound = builder.create(noLocation, boundType, boundRef); + SmallVector operands{builder.create(noLocation, thisType, bound)}; + auto firstOwn = entryBlock.getNumArguments() - ownParams; + for (auto index = 0u; index < ownParams; index++) + { + mlir::Value argument = entryBlock.getArgument(firstOwn + index); + auto paramType = methodType.getInput(index + 1); + if (argument.getType() != paramType) + { + auto castResult = cast(noLocation, paramType, argument, genContext); + if (castResult.failed_or_no_value()) + { + funcOp.erase(); + return mlir::Value(); + } + + argument = V(castResult); + } + + operands.push_back(argument); + } + + auto method = builder.create(noLocation, methodType, bound); + auto callOp = builder.create(noLocation, method, operands); + if (hasResult) + { + // handed on as `return f(x)` hands it: owned, and taken over by the return + if (mth.ownsHeapMemory(noLocation, results.front())) + { + callOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + callOp->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, builder.getUnitAttr()); + } + + builder.create(noLocation, callOp.getResult(0), entryOp.getReference()); + } + + builder.create(noLocation, hasResult ? entryOp.getReference() : mlir::Value()); + + theModule.push_back(funcOp); + } + + // the box is the adapter's own, as a closure's capture box is (resolveFunctionWithCapture): it holds a + // reference to the bound method of its own, released with the box + mlirGenRetainCaptured(location, mlir::ValueRange{value}); + auto boxValue = builder.create(location, boxType, mlir::ValueRange{value}); + auto thunkRef = builder.create(location, thunkType, + mlir::FlatSymbolRefAttr::get(builder.getContext(), thunkName)); + auto boundFuncVal = builder.create(location, getBoundFunctionType(thunkType), + boxValue, thunkRef); + boundFuncVal->setAttr(OWNS_CAPTURE_ATTR_NAME, builder.getUnitAttr()); + builder.create(location, boundFuncVal); + boundFuncVal->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + return boundFuncVal; + } + mlir::LogicalResult MLIRGenImpl::verifyFunctionCastRules(mlir::Location location, mlir::Type type, mlir::Value &value, mlir::Type &valueType, const GenContext &genContext) { if (mth.isAnyFunctionType(valueType) && mth.isAnyFunctionType(type)) { @@ -2512,6 +2669,12 @@ namespace mlirgen emitFunctionTypeMismatch(location, valueType, type, test); return mlir::failure(); } + + if (auto adapter = boundMethodWiderTypeAdapter(location, value, type, genContext)) + { + value = adapter; + valueType = adapter.getType(); + } } } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 188cae34a..ae1d61fdc 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -15448,6 +15448,8 @@ class MLIRGenImpl mlir::Type interfaceMemberFitting(mlir_ts::UnionType unionType, mlir::Type valueType); mlir::Value fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type); + mlir::Value boundMethodWiderTypeAdapter(mlir::Location location, mlir::Value value, mlir::Type type, + const GenContext &genContext); // optional // TODO: it is in CastLogic as well, review usage and remove from here diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index c5c6ab9a4..cdf5ce8bb 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -298,6 +298,7 @@ tslang_add_test(NAME test-compile-00-funcs-vararg COMMAND test-runner "${PROJECT tslang_add_test(NAME test-compile-00-declare-function-twice COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00declare_function_twice.ts") tslang_add_test(NAME test-compile-00-function-overloads COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_overloads.ts") tslang_add_test(NAME test-compile-00-class-override-arity COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_override_arity.ts") +tslang_add_test(NAME test-compile-00-bound-method-wider-callback COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00bound_method_wider_callback.ts") tslang_add_test(NAME test-compile-00-gc-allocations-distinct COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00gc_allocations_distinct.ts") tslang_add_test(NAME test-compile-00-assert-message COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00assert_message.ts") tslang_add_test(NAME test-compile-01-funcs-vararg COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01funcs_vararg.ts") @@ -978,6 +979,7 @@ tslang_add_test(NAME test-jit-00-funcs-vararg COMMAND test-runner -jit "${PROJEC tslang_add_test(NAME test-jit-00-declare-function-twice COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00declare_function_twice.ts") tslang_add_test(NAME test-jit-00-function-overloads COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_overloads.ts") tslang_add_test(NAME test-jit-00-class-override-arity COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_override_arity.ts") +tslang_add_test(NAME test-jit-00-bound-method-wider-callback COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00bound_method_wider_callback.ts") tslang_add_test(NAME test-jit-00-gc-allocations-distinct COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00gc_allocations_distinct.ts") tslang_add_test(NAME test-jit-00-assert-message COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00assert_message.ts") tslang_add_test(NAME test-jit-01-funcs-vararg COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01funcs_vararg.ts") @@ -2596,6 +2598,7 @@ set(TSLANG_CORPUS 00funcs_vararg.ts 00function_overloads.ts 00class_override_arity.ts + 00bound_method_wider_callback.ts 00gc_allocations_distinct.ts 00assert_message.ts 00funcs.ts diff --git a/tslang/test/tester/tests/00bound_method_wider_callback.ts b/tslang/test/tester/tests/00bound_method_wider_callback.ts new file mode 100644 index 000000000..eeb83ee74 --- /dev/null +++ b/tslang/test/tester/tests/00bound_method_wider_callback.ts @@ -0,0 +1,49 @@ +// a bound method given as a function type with more parameters than the method takes, the extra ones first + +class Counter { + n = 0; + bump() { + this.n++; + } + add(x: number): number { + this.n += x; + return this.n; + } +} + +function callWithObject(f: (o: object) => void, o: object) { + f(o); +} + +function callWithObjectAndNumber(f: (o: object, x: number) => number, o: object, x: number) { + return f(o, x); +} + +function main() { + const c = new Counter(); + const other = new Counter(); + for (let i = 0; i < 1000; i++) { + callWithObject(c.bump, other); + } + + assert(c.n == 1000, "the method's own this, not the argument"); + assert(other.n == 0); + + assert(callWithObjectAndNumber(c.add, other, 5) == 1005, "the last argument goes to the method"); + + const user = { + firstName: "World", + count: 0, + sayHi() { + this.count++; + }, + }; + + for (let i = 0; i < 100; i++) { + callWithObject(user.sayHi, user); + } + + assert(user.count == 100); + + print("done."); +}