diff --git a/docs/design/mono/webcil.md b/docs/design/mono/webcil.md index 1712c8863e71d3..2596530b010f01 100644 --- a/docs/design/mono/webcil.md +++ b/docs/design/mono/webcil.md @@ -235,6 +235,40 @@ In particular, `payloadSize` is still a little-endian `u32`; `getWebcilSize` wri 4 bytes, and its `memory.init` source offset and length operands remain `i32`. Memory64 is not supported by the passive version 0 wrapper. +##### Memory64 ReadyToRun wrappers + +A memory64 ReadyToRun wrapper follows the same rules with pointer-sized `i64` values. It imports an +`i64` memory, a table64 `__indirect_function_table` whose operands and element segment offset are +`i64`, and `i64` `__memory_base` and `__table_base` globals. The runtime globals it imports, such as +`__stack_pointer`, are also `i64`. The host supplies `__memory_base` and `__table_base` as immutable +`i64` `WebAssembly.Global` values with JavaScript `BigInt` values. + +`patchWebcilHeader` takes `(param $d i64) (param $n i32)`. The `TableBase` field of the `WebcilHeader` +stays a 32-bit value, so the function wraps `__table_base` to 32 bits with `i32.wrap_i64` before the +`i32.store`. `payloadSize` and `tableSize` in data segment 0 remain little-endian `u32` values. + +``` wat +;; ReadyToRun image, memory64. +(module + (import "webcil" "memory" (memory (;0;) i64 1)) + (import "webcil" "__stack_pointer" (global (;0;) (mut i64))) + (import "webcil" "__memory_base" (global (;1;) i64)) + (import "webcil" "__table_base" (global (;2;) i64)) + (import "webcil" "__indirect_function_table" (table (;0;) i64 1 funcref)) + (func (export "patchWebcilHeader") (param $d i64) (param $n i32) (result) + local.get 1 + i32.const 32 + i32.ge_s + if + local.get 0 + global.get 2 + i32.wrap_i64 + i32.store offset=28 + end + ) + (elem (;0;) (global.get 2) func 2)) ;; active at __table_base +``` + ##### WASI host composition WASI hosts use offline composition rather than instantiating R2R modules at runtime. diff --git a/eng/Subsets.props b/eng/Subsets.props index 18d3d4f34918b8..863c591301b847 100644 --- a/eng/Subsets.props +++ b/eng/Subsets.props @@ -343,8 +343,7 @@ <_CrossToolSubset Condition="'$(_BuildCrossComponents)' == 'true' and '$(TargetsWasmArch)' != 'true' and ($(_subset.Contains('+clr.tools+')) or $(_subset.Contains('+clr.nativecorelib+')) or $(_subset.Contains('+clr.crossarchtools+')))" Include="ClrJitSubset=true" /> - + <_CrossToolSubset Condition="'$(_BuildCrossComponents)' == 'true' and '$(TargetsWasmArch)' == 'true' and ($(_subset.Contains('+clr.tools+')) or $(_subset.Contains('+clr.nativecorelib+')) or $(_subset.Contains('+clr.crossarchtools+')))" Include="ClrWasmJitSubset=true" /> <_CrossToolSubset Condition="'$(_BuildCrossComponents)' == 'true' and '$(TargetsWindows)' == 'true'" Include="ClrDebugSubset=true" /> diff --git a/eng/codeOptimization.targets b/eng/codeOptimization.targets index fbb1dbec2cebd2..863818ef4f3ee1 100644 --- a/eng/codeOptimization.targets +++ b/eng/codeOptimization.targets @@ -57,7 +57,7 @@ - + $(PublishReadyToRunCrossgen2ExtraArgs);--embed-pgo-data diff --git a/eng/pipelines/common/templates/browser-wasm-coreclr-runtime-tests.yml b/eng/pipelines/common/templates/browser-wasm-coreclr-runtime-tests.yml index 4167bf99388c62..5af3d24ba38275 100644 --- a/eng/pipelines/common/templates/browser-wasm-coreclr-runtime-tests.yml +++ b/eng/pipelines/common/templates/browser-wasm-coreclr-runtime-tests.yml @@ -5,7 +5,6 @@ parameters: isExtraPlatformsBuild: false platforms: [] useHelixMonitor: false - runReadyToRunTests: true jobs: @@ -39,16 +38,15 @@ jobs: useHelixMonitor: ${{ parameters.useHelixMonitor }} # CrossgenFramework skips wasm, so regenerate CORE_ROOT from the same BCL # bits and enable Crossgen2 only for test assemblies on Helix. - - ${{ if eq(parameters.runReadyToRunTests, true) }}: - - template: /eng/pipelines/common/templates/runtimes/build-runtime-tests-and-send-to-helix.yml - parameters: - creator: dotnet-bot - readyToRun: true - testBuildArgs: generatelayoutonly crossgen2 -os browser /p:HostConfiguration=Release - testRunNamePrefixSuffix: CoreCLR_R2R_CG2_$(_BuildConfig) - timeoutPerTestInMinutes: 30 - timeoutPerTestCollectionInMinutes: 90 - useHelixMonitor: ${{ parameters.useHelixMonitor }} + - template: /eng/pipelines/common/templates/runtimes/build-runtime-tests-and-send-to-helix.yml + parameters: + creator: dotnet-bot + readyToRun: true + testBuildArgs: generatelayoutonly crossgen2 -os browser /p:HostConfiguration=Release + testRunNamePrefixSuffix: CoreCLR_R2R_CG2_$(_BuildConfig) + timeoutPerTestInMinutes: 30 + timeoutPerTestCollectionInMinutes: 90 + useHelixMonitor: ${{ parameters.useHelixMonitor }} extraVariablesTemplates: - template: /eng/pipelines/common/templates/runtimes/test-variables.yml parameters: diff --git a/eng/pipelines/runtime.yml b/eng/pipelines/runtime.yml index f2259f523800a4..abb2917481f4b9 100644 --- a/eng/pipelines/runtime.yml +++ b/eng/pipelines/runtime.yml @@ -279,8 +279,6 @@ extends: platforms: - browser_wasm64 nameSuffix: CoreCLR_ReleaseLibraries - # browser-wasm64 runs on the interpreter until ReadyToRun support is added. - runReadyToRunTests: false useHelixMonitor: ${{ variables.enableHelixJobMonitor }} condition: >- or( diff --git a/eng/restore/optimizationData.targets b/eng/restore/optimizationData.targets index 528b767483efa5..5c0603119988cc 100644 --- a/eng/restore/optimizationData.targets +++ b/eng/restore/optimizationData.targets @@ -7,6 +7,7 @@ + diff --git a/src/coreclr/CMakeLists.txt b/src/coreclr/CMakeLists.txt index bd5ffcd7b4ed7c..721b47ceb0ff13 100644 --- a/src/coreclr/CMakeLists.txt +++ b/src/coreclr/CMakeLists.txt @@ -248,12 +248,9 @@ if(CLR_CROSS_COMPONENTS_BUILD AND CLR_CMAKE_TARGET_ARCH_WASMARCH) add_subdirectory(nativeresources) add_subdirectory(dlls/mscorrc) endif (CLR_CMAKE_HOST_UNIX) - # There is no wasm64 JIT yet, so wasm64 cross-component builds produce only the jitinterface. - if(NOT CLR_CMAKE_TARGET_ARCH_WASM64) - add_subdirectory(utilcode) - add_subdirectory(gcinfo) - add_subdirectory(jit) - endif() + add_subdirectory(utilcode) + add_subdirectory(gcinfo) + add_subdirectory(jit) return() endif() diff --git a/src/coreclr/crossgen-corelib.proj b/src/coreclr/crossgen-corelib.proj index adab7126545100..c478c09cd9a900 100644 --- a/src/coreclr/crossgen-corelib.proj +++ b/src/coreclr/crossgen-corelib.proj @@ -1,7 +1,7 @@ + Condition="'$(TargetsWasmArch)' == 'true'" /> true false - - false CopyILCoreLib diff --git a/src/coreclr/gcinfo/CMakeLists.txt b/src/coreclr/gcinfo/CMakeLists.txt index 8925042b9588ba..65561ac30760c1 100644 --- a/src/coreclr/gcinfo/CMakeLists.txt +++ b/src/coreclr/gcinfo/CMakeLists.txt @@ -101,5 +101,8 @@ endif (NOT CLR_CMAKE_TARGET_ARCH_RISCV64) if (CLR_CMAKE_TARGET_ARCH_WASMARCH) create_gcinfo_lib(TARGET gcinfo_unix_wasm OS browser ARCH wasm) create_gcinfo_lib(TARGET gcinfo_universal_wasm OS universal ARCH wasm) + if (CLR_CROSS_COMPONENTS_BUILD AND CLR_CMAKE_TARGET_ARCH_WASM64) + create_gcinfo_lib(TARGET gcinfo_universal_wasm64 OS universal ARCH wasm64) + endif() install_clr(TARGETS gcinfo_unix_wasm DESTINATIONS sharedFramework COMPONENT runtime) endif (CLR_CMAKE_TARGET_ARCH_WASMARCH) diff --git a/src/coreclr/inc/corinfo.h b/src/coreclr/inc/corinfo.h index ed6b9b576c561f..b4f286ce7e8a11 100644 --- a/src/coreclr/inc/corinfo.h +++ b/src/coreclr/inc/corinfo.h @@ -937,6 +937,7 @@ enum class CorInfoReloc WASM_METHOD_RELATIVE_VIRTUAL_IP_I32, // Wasm: the current method's virtual IP relative to the image virtual IP base, stored as a 4-byte uint32. WASM_METHOD_FRAME_IDENTITY_SLEB, // Wasm: the current method's runtime-specific shadow-frame identity, encoded as a 5-byte varint32. WASM_DEFERRED_CALL, // Wasm: metadata for a deferred direct call; the target is its exact signature handle and the location is its first immediate byte. Does not write bytes. + WASM_METHOD_RELATIVE_VIRTUAL_IP_I64, // Wasm: the current method's virtual IP relative to the image virtual IP base, stored as an 8-byte uint64. }; enum CorInfoGCType @@ -1733,6 +1734,7 @@ enum CorInfoArch CORINFO_ARCH_LOONGARCH64, CORINFO_ARCH_RISCV64, CORINFO_ARCH_WASM32, + CORINFO_ARCH_WASM64, }; enum CORINFO_OS diff --git a/src/coreclr/inc/jiteeversionguid.h b/src/coreclr/inc/jiteeversionguid.h index 77a8a4e14f64be..ff7b32229ff730 100644 --- a/src/coreclr/inc/jiteeversionguid.h +++ b/src/coreclr/inc/jiteeversionguid.h @@ -37,11 +37,11 @@ #include -constexpr GUID JITEEVersionIdentifier = { /* c77c1a0f-c8c6-4a68-90db-4d8c1253c5ea */ - 0xc77c1a0f, - 0xc8c6, - 0x4a68, - {0x90, 0xdb, 0x4d, 0x8c, 0x12, 0x53, 0xc5, 0xea} +constexpr GUID JITEEVersionIdentifier = { /* d8f122f8-1793-4be8-964b-26bc38ea9fa6 */ + 0xd8f122f8, + 0x1793, + 0x4be8, + {0x96, 0x4b, 0x26, 0xbc, 0x38, 0xea, 0x9f, 0xa6} }; #endif // JIT_EE_VERSIONING_GUID_H diff --git a/src/coreclr/inc/jithelpers.h b/src/coreclr/inc/jithelpers.h index d736af59b527d0..c794ef23e9e920 100644 --- a/src/coreclr/inc/jithelpers.h +++ b/src/coreclr/inc/jithelpers.h @@ -63,9 +63,14 @@ JITHELPER(CORINFO_HELP_LRSZ, NULL, METHOD__NIL) JITHELPER(CORINFO_HELP_LMUL, NULL, METHOD__NIL) #endif // TARGET_64BIT -#ifndef TARGET_64BIT +#if !defined(TARGET_64BIT) || defined(TARGET_WASMARCH) DYNAMICJITHELPER(CORINFO_HELP_LMUL_OVF, NULL, METHOD__MATH__MULTIPLY_CHECKED_INT64) DYNAMICJITHELPER(CORINFO_HELP_ULMUL_OVF, NULL, METHOD__MATH__MULTIPLY_CHECKED_UINT64) +#else + JITHELPER(CORINFO_HELP_LMUL_OVF, NULL, METHOD__NIL) + JITHELPER(CORINFO_HELP_ULMUL_OVF, NULL, METHOD__NIL) +#endif +#ifndef TARGET_64BIT #if defined(TARGET_X86) && defined(TARGET_WINDOWS) JITHELPER(CORINFO_HELP_LDIV, JIT_LDiv, METHOD__NIL) JITHELPER(CORINFO_HELP_LMOD, JIT_LMod, METHOD__NIL) @@ -78,8 +83,6 @@ DYNAMICJITHELPER(CORINFO_HELP_ULMOD, NULL, METHOD__MATH__MOD_UINT64) #endif // TARGET_X86 && TARGET_WINDOWS #else // TARGET_64BIT - JITHELPER(CORINFO_HELP_LMUL_OVF, NULL, METHOD__NIL) - JITHELPER(CORINFO_HELP_ULMUL_OVF, NULL, METHOD__NIL) JITHELPER(CORINFO_HELP_LDIV, NULL, METHOD__NIL) JITHELPER(CORINFO_HELP_LMOD, NULL, METHOD__NIL) JITHELPER(CORINFO_HELP_ULDIV, NULL, METHOD__NIL) diff --git a/src/coreclr/jit/CMakeLists.txt b/src/coreclr/jit/CMakeLists.txt index 3a25ce6eae21c2..396de7e78e91b8 100644 --- a/src/coreclr/jit/CMakeLists.txt +++ b/src/coreclr/jit/CMakeLists.txt @@ -63,7 +63,7 @@ function(create_standalone_jit) elseif(TARGETDETAILS_ARCH STREQUAL "riscv64") set(JIT_ARCH_SOURCES ${JIT_RISCV64_SOURCES}) set(JIT_ARCH_HEADERS ${JIT_RISCV64_HEADERS}) - elseif(TARGETDETAILS_ARCH STREQUAL "wasm") + elseif(TARGETDETAILS_ARCH STREQUAL "wasm" OR TARGETDETAILS_ARCH STREQUAL "wasm64") set(JIT_ARCH_SOURCES ${JIT_WASM_SOURCES}) set(JIT_ARCH_HEADERS ${JIT_WASM_HEADERS}) else() @@ -84,7 +84,7 @@ function(create_standalone_jit) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE FEATURE_MASKED_HW_INTRINSICS) endif () - if (TARGETDETAILS_ARCH STREQUAL "wasm") + if (TARGETDETAILS_ARCH STREQUAL "wasm" OR TARGETDETAILS_ARCH STREQUAL "wasm64") target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE FEATURE_SIMD) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE FEATURE_HW_INTRINSICS) endif () @@ -743,7 +743,7 @@ if (CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_AMD64) endif (CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_AMD64) if (CLR_CMAKE_TARGET_ARCH_WASMARCH) - create_standalone_jit(TARGET clrjit_universal_wasm_${ARCH_HOST_NAME} OS universal ARCH wasm) + create_standalone_jit(TARGET clrjit_universal_${ARCH_TARGET_NAME}_${ARCH_HOST_NAME} OS universal ARCH ${ARCH_TARGET_NAME}) endif (CLR_CMAKE_TARGET_ARCH_WASMARCH) if (CLR_CMAKE_TARGET_ARCH_LOONGARCH64) @@ -759,7 +759,7 @@ else() endif (CLR_CMAKE_TARGET_ARCH_RISCV64) if (CLR_CMAKE_TARGET_UNIX) - if (NOT ARCH_TARGET_NAME STREQUAL s390x AND NOT ARCH_TARGET_NAME STREQUAL armv6 AND NOT ARCH_TARGET_NAME STREQUAL ppc64le AND NOT ARCH_TARGET_NAME STREQUAL riscv64 AND NOT ARCH_TARGET_NAME STREQUAL wasm) + if (NOT ARCH_TARGET_NAME STREQUAL s390x AND NOT ARCH_TARGET_NAME STREQUAL armv6 AND NOT ARCH_TARGET_NAME STREQUAL ppc64le AND NOT ARCH_TARGET_NAME STREQUAL riscv64 AND NOT CLR_CMAKE_TARGET_ARCH_WASMARCH) if(CLR_CMAKE_TARGET_ARCH_ARM OR CLR_CMAKE_TARGET_ARCH_ARM64) install_clr(TARGETS clrjit_universal_${ARCH_TARGET_NAME}_${ARCH_HOST_NAME} DESTINATIONS . COMPONENT jit) else() diff --git a/src/coreclr/jit/codegen.h b/src/coreclr/jit/codegen.h index 7b038623699e77..1fbf04f023d480 100644 --- a/src/coreclr/jit/codegen.h +++ b/src/coreclr/jit/codegen.h @@ -919,6 +919,9 @@ class CodeGen final : public CodeGenInterface void genCompareFloat(GenTreeOp* treeNode); void genCompareInt(GenTreeOp* treeNode); +#ifdef TARGET_WASMARCH + void genWidenCompareResult(GenTreeOp* treeNode); +#endif // TARGET_WASMARCH #ifdef TARGET_XARCH bool genCanAvoidEmittingCompareAgainstZero(GenTree* tree, emitAttr opSize); GenTree* genTryFindFlagsConsumer(GenTree* flagsProducer, GenCondition** condition); diff --git a/src/coreclr/jit/codegenwasm.cpp b/src/coreclr/jit/codegenwasm.cpp index b553d91408eeef..e6db6915195ff7 100644 --- a/src/coreclr/jit/codegenwasm.cpp +++ b/src/coreclr/jit/codegenwasm.cpp @@ -15,33 +15,33 @@ static const int LINEAR_MEMORY_INDEX = 0; #ifdef TARGET_64BIT -static const instruction INS_I_load = INS_i64_load; -static const instruction INS_I_store = INS_i64_store; -static const instruction INS_I_const = INS_i64_const; -static const instruction INS_I_add = INS_i64_add; -static const instruction INS_I_and = INS_i64_and; -static const instruction INS_I_or = INS_i64_or; -static const instruction INS_I_shl = INS_i64_shl; -static const instruction INS_I_eqz = INS_i64_eqz; -static const instruction INS_I_mul = INS_i64_mul; -static const instruction INS_I_sub = INS_i64_sub; -static const instruction INS_I_le_u = INS_i64_le_u; -static const instruction INS_I_ge_u = INS_i64_ge_u; -static const instruction INS_I_gt_u = INS_i64_gt_u; +static const instruction INS_I_load = INS_i64_load; +static const instruction INS_I_store = INS_i64_store; +static const instruction INS_I_const = INS_i64_const; +static const instruction INS_I_const_frameidentity = INS_i64_const_frameidentity; +static const instruction INS_I_add = INS_i64_add; +static const instruction INS_I_and = INS_i64_and; +static const instruction INS_I_or = INS_i64_or; +static const instruction INS_I_shl = INS_i64_shl; +static const instruction INS_I_eqz = INS_i64_eqz; +static const instruction INS_I_mul = INS_i64_mul; +static const instruction INS_I_sub = INS_i64_sub; +static const instruction INS_I_le_u = INS_i64_le_u; +static const instruction INS_I_gt_u = INS_i64_gt_u; #else // !TARGET_64BIT -static const instruction INS_I_load = INS_i32_load; -static const instruction INS_I_store = INS_i32_store; -static const instruction INS_I_const = INS_i32_const; -static const instruction INS_I_add = INS_i32_add; -static const instruction INS_I_and = INS_i32_and; -static const instruction INS_I_or = INS_i32_or; -static const instruction INS_I_shl = INS_i32_shl; -static const instruction INS_I_eqz = INS_i32_eqz; -static const instruction INS_I_mul = INS_i32_mul; -static const instruction INS_I_sub = INS_i32_sub; -static const instruction INS_I_le_u = INS_i32_le_u; -static const instruction INS_I_ge_u = INS_i32_ge_u; -static const instruction INS_I_gt_u = INS_i32_gt_u; +static const instruction INS_I_load = INS_i32_load; +static const instruction INS_I_store = INS_i32_store; +static const instruction INS_I_const = INS_i32_const; +static const instruction INS_I_const_frameidentity = INS_i32_const_frameidentity; +static const instruction INS_I_add = INS_i32_add; +static const instruction INS_I_and = INS_i32_and; +static const instruction INS_I_or = INS_i32_or; +static const instruction INS_I_shl = INS_i32_shl; +static const instruction INS_I_eqz = INS_i32_eqz; +static const instruction INS_I_mul = INS_i32_mul; +static const instruction INS_I_sub = INS_i32_sub; +static const instruction INS_I_le_u = INS_i32_le_u; +static const instruction INS_I_gt_u = INS_i32_gt_u; #endif // !TARGET_64BIT //------------------------------------------------------------------------ @@ -196,7 +196,7 @@ void CodeGen::genAllocLclFrame(unsigned frameSize, regNumber initReg, bool* pIni GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetFramePointerRegIndex()); if (m_compiler->IsNativeAot() || m_compiler->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_WASM_MANAGED_HELPER)) { - GetEmitter()->emitIns_I(INS_i32_const_frameidentity, EA_HANDLE_CNS_RELOC, + GetEmitter()->emitIns_I(INS_I_const_frameidentity, EA_HANDLE_CNS_RELOC, reinterpret_cast(m_compiler->info.compMethodHnd)); } else if (m_compiler->lvaWasmPortableEntryPointArg != BAD_VAR_NUM) @@ -220,7 +220,7 @@ void CodeGen::genAllocLclFrame(unsigned frameSize, regNumber initReg, bool* pIni if ((m_compiler->funCurrentFuncIdx() == ROOT_FUNC_IDX) && (m_compiler->lvaWasmResumeIP != BAD_VAR_NUM)) { GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetFramePointerRegIndex()); - GetEmitter()->emitIns_I(INS_I_const, EA_4BYTE, 0); + GetEmitter()->emitIns_I(INS_i32_const, EA_4BYTE, 0); GetEmitter()->emitIns_S(ins_Store(TYP_INT), EA_4BYTE, m_compiler->lvaWasmResumeIP, 0); } } @@ -1178,6 +1178,13 @@ void CodeGen::genCodeForTreeNode(GenTree* treeNode) case GT_RETURN: case GT_RETFILT: genReturn(treeNode); +#ifdef TARGET_64BIT + // The runtime uses the pointer-sized catch funclet ABI for filters as well. + if (treeNode->OperIs(GT_RETFILT) && treeNode->TypeIs(TYP_INT)) + { + GetEmitter()->emitIns(INS_i64_extend_u_i32); + } +#endif break; case GT_IL_OFFSET: @@ -1365,6 +1372,9 @@ void CodeGen::genTableBasedSwitch(GenTree* treeNode) genConsumeOperands(treeNode->AsOp()); + // LowerSwitch narrows native int indices, since br_table always takes an i32. + assert(genActualType(treeNode->AsOp()->gtOp1->TypeGet()) == TYP_INT); + BBswtDesc* const desc = block->GetSwitchTargets(); unsigned const caseCount = desc->GetCaseCount(); @@ -1467,9 +1477,11 @@ void CodeGen::genReturnSuspend(GenTreeUnOp* treeNode) switch (genActualType(retNativeType)) { case TYP_INT: + emit->emitIns_I(INS_i32_const, EA_4BYTE, 0); + break; case TYP_REF: case TYP_BYREF: - emit->emitIns_I(INS_i32_const, emitActualTypeSize(retNativeType), 0); + emit->emitIns_I(INS_I_const, EA_PTRSIZE, 0); break; case TYP_LONG: emit->emitIns_I(INS_i64_const, EA_8BYTE, 0); @@ -2242,7 +2254,7 @@ void CodeGen::genCodeForConstant(GenTree* treeNode) { if (icon->IsIconHandle(GTF_ICON_WASM_FRAME_IDENTITY)) { - GetEmitter()->emitIns_I(INS_i32_const_frameidentity, EA_HANDLE_CNS_RELOC, icon->IntegralValue()); + GetEmitter()->emitIns_I(INS_I_const_frameidentity, EA_HANDLE_CNS_RELOC, icon->IntegralValue()); WasmProduceReg(treeNode); return; } @@ -2334,16 +2346,17 @@ void CodeGen::genCodeForShift(GenTree* tree) GenTreeOp* treeNode = tree->AsOp(); genConsumeOperands(treeNode); - // The shift operand width in IR is always int or small int, so the operand's actual type should be TYP_INT. - // However, the WASM operations have the same widths for both the shift and shiftee so - // the shift width may need to be zero-extended if the shift result type is TYP_LONG. - if (treeNode->TypeIs(TYP_LONG)) + // Wasm requires the shift count and the value being shifted to have the same width. + const var_types shiftType = genActualType(treeNode->gtGetOp2()->TypeGet()); + assert((shiftType == TYP_INT) || (shiftType == TYP_LONG)); + if (treeNode->TypeIs(TYP_LONG) && (shiftType == TYP_INT)) { - assert(genActualType(treeNode->gtGetOp2()->TypeGet()) == TYP_INT); - // Zero-extend the shift amount to 64 bits for long shifts/rotates. - // Wasteful if the amount was a constant, perhaps we should contain it if so. GetEmitter()->emitIns(INS_i64_extend_u_i32); } + else if (treeNode->TypeIs(TYP_INT) && (shiftType == TYP_LONG)) + { + GetEmitter()->emitIns(INS_i32_wrap_i64); + } instruction ins; switch (PackOperAndType(treeNode->OperGet(), treeNode->TypeGet())) @@ -2651,7 +2664,9 @@ void CodeGen::genRangeCheck(GenTree* tree) else #endif { - GetEmitter()->emitIns(INS_I_ge_u); + const var_types indexType = genActualType(boundsCheck->GetIndex()->TypeGet()); + assert(indexType == genActualType(boundsCheck->GetArrayLength()->TypeGet())); + GetEmitter()->emitIns(indexType == TYP_LONG ? INS_i64_ge_u : INS_i32_ge_u); } genJumpToThrowHlpBlk(boundsCheck->gtThrowKind); @@ -3415,7 +3430,7 @@ void CodeGen::genCallInstruction(GenTreeCall* call) // must still include it. See #DeferredWasmCallRelocationProtocol. assert(!call->IsHelperCall() && !call->IsUnmanaged()); assert(call->gtArgs.FindWellKnownArg(WellKnownArg::WasmPortableEntryPoint) == nullptr); - typeStack.Push(CORINFO_WASM_TYPE_I32); + typeStack.Push(TARGET_POINTER_SIZE == 8 ? CORINFO_WASM_TYPE_I64 : CORINFO_WASM_TYPE_I32); } // Report managed call signatures to the R2R compiler for thunk generation. @@ -3724,19 +3739,26 @@ void CodeGen::genCompareInt(GenTreeOp* treeNode) if (!canUseValueDirectly) { - GetEmitter()->emitIns(genActualType(value->TypeGet()) == TYP_LONG ? INS_i64_eqz : INS_i32_eqz); + GetEmitter()->emitIns(genTypeSize(genActualType(value->TypeGet())) == 8 ? INS_i64_eqz : INS_i32_eqz); if (treeNode->OperIs(GT_NE)) { GetEmitter()->emitIns(INS_i32_eqz); } } + genWidenCompareResult(treeNode); WasmProduceReg(treeNode); return; } + var_types operandType = genActualType(op1->TypeGet()); + if (varTypeIsGC(operandType)) + { + operandType = TYP_I_IMPL; + } + instruction ins; - switch (PackOperAndType(treeNode->OperGet(), genActualType(op1->TypeGet()))) + switch (PackOperAndType(treeNode->OperGet(), operandType)) { case PackOperAndType(GT_EQ, TYP_INT): ins = INS_i32_eq; @@ -3779,9 +3801,27 @@ void CodeGen::genCompareInt(GenTreeOp* treeNode) } GetEmitter()->emitIns(ins); + genWidenCompareResult(treeNode); WasmProduceReg(treeNode); } +//------------------------------------------------------------------------ +// genWidenCompareResult: Zero-extend an i32 compare result when the node produces a long +// +// Arguments: +// treeNode - the compare tree +// +// Notes: +// On 64-bit targets lowering can turn a TYP_LONG GT_UDIV into a GT_GE that keeps its type. +// +void CodeGen::genWidenCompareResult(GenTreeOp* treeNode) +{ + if (genActualType(treeNode->TypeGet()) == TYP_LONG) + { + GetEmitter()->emitIns(INS_i64_extend_u_i32); + } +} + //------------------------------------------------------------------------ // genCompareFloat: Generate code for comparing floats // @@ -4011,7 +4051,7 @@ void CodeGen::genLclHeap(GenTree* tree) if (needsZeroing) { GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetStackPointerRegIndex()); - GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, 0); + GetEmitter()->emitIns_I(INS_i32_const, EA_4BYTE, 0); GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, WasmRegToIndex(sizeReg)); // TODO-WASM-CQ: possibly do small fills directly GetEmitter()->emitIns_I(INS_memory_fill, EA_4BYTE, LINEAR_MEMORY_INDEX); @@ -4189,7 +4229,7 @@ void CodeGen::genCodeForStoreBlk(GenTreeBlk* blkOp) } else { - emit->emitIns_I(INS_i32_const, EA_4BYTE, blkOp->Size()); + emit->emitIns_I(INS_I_const, EA_PTRSIZE, blkOp->Size()); emit->emitIns_I(isCopyBlk ? INS_memory_copy : INS_memory_fill, EA_4BYTE, LINEAR_MEMORY_INDEX); } genUpdateLife(blkOp); @@ -4352,7 +4392,7 @@ void CodeGen::genEHCatchRet(BasicBlock* block) // The runtime expects a return value from a catch funclet, // but nothing will depend on it. // - GetEmitter()->emitIns_I(INS_i32_const, EA_4BYTE, 0); + GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, 0); } void CodeGen::genStructReturn(GenTree* treeNode) diff --git a/src/coreclr/jit/emit.cpp b/src/coreclr/jit/emit.cpp index c2b30291286cc8..d2c3448fac01a0 100644 --- a/src/coreclr/jit/emit.cpp +++ b/src/coreclr/jit/emit.cpp @@ -8537,7 +8537,10 @@ void emitter::emitOutputDataSec(dataSecDsc* sec, AllocMemChunk* chunks) emitRecordRelocation(&aDstRW[i].Resume, emitAsyncResumeStubEntryPoint, CorInfoReloc::DIRECT); if (target != nullptr) { -#ifdef TARGET_WASMARCH +#if defined(TARGET_WASM64) + emitRecordRelocation(&aDstRW[i].DiagnosticIP, target, + CorInfoReloc::WASM_METHOD_RELATIVE_VIRTUAL_IP_I64); +#elif defined(TARGET_WASM) emitRecordRelocation(&aDstRW[i].DiagnosticIP, target, CorInfoReloc::WASM_METHOD_RELATIVE_VIRTUAL_IP_I32); #else diff --git a/src/coreclr/jit/emitwasm.cpp b/src/coreclr/jit/emitwasm.cpp index bd5035cbdaebc3..7d046e23049540 100644 --- a/src/coreclr/jit/emitwasm.cpp +++ b/src/coreclr/jit/emitwasm.cpp @@ -265,10 +265,11 @@ void emitter::emitAddressConstant(void* address) { emitImageBase(); } - emitIns_I(INS_i32_const_address, EA_SET_FLG(EA_PTRSIZE, EA_CNS_RELOC_FLG), (cnsval_ssize_t)address); + emitIns_I((TARGET_POINTER_SIZE == 8) ? INS_i64_const_address : INS_i32_const_address, + EA_SET_FLG(EA_PTRSIZE, EA_CNS_RELOC_FLG), (cnsval_ssize_t)address); if (!m_compiler->IsNativeAot()) { - emitIns(INS_i32_add); + emitIns((TARGET_POINTER_SIZE == 8) ? INS_i64_add : INS_i32_add); } } @@ -301,10 +302,10 @@ void emitter::emitFuncletAddressConstant(cnsval_ssize_t funcletId) emitIns_I(INS_global_get, EA_HANDLE_CNS_RELOC, (cnsval_ssize_t)(size_t)m_compiler->eeGetWasmWellKnownGlobals()->tableBase); } - emitIns_I(INS_i32_const_funcletptr, EA_PTRSIZE, (cnsval_ssize_t)funcletId); + emitIns_I((TARGET_POINTER_SIZE == 8) ? INS_i64_const_funcletptr : INS_i32_const_funcletptr, EA_PTRSIZE, funcletId); if (!m_compiler->IsNativeAot()) { - emitIns(INS_i32_add); + emitIns((TARGET_POINTER_SIZE == 8) ? INS_i64_add : INS_i32_add); } } @@ -328,14 +329,14 @@ void emitter::emitDataOffsetConstant(UNATIVE_OFFSET dataOffs) } instrDesc* id = emitNewInstrSC(EA_SET_FLG(EA_PTRSIZE, EA_CNS_RELOC_FLG), (cnsval_ssize_t)dataOffs); - id->idIns(INS_i32_const_dataoffs); + id->idIns((TARGET_POINTER_SIZE == 8) ? INS_i64_const_dataoffs : INS_i32_const_dataoffs); id->idInsFmt(IF_DATAOFFS); dispIns(id); appendToCurIG(id); if (!m_compiler->IsNativeAot()) { - emitIns(INS_i32_add); + emitIns((TARGET_POINTER_SIZE == 8) ? INS_i64_add : INS_i32_add); } } @@ -780,12 +781,9 @@ uint8_t emitter::GetWasmValueTypeCode(WasmValueType type) return typecode_mapping[static_cast(type)]; } -#ifdef TARGET_WASM -// NOTE: Keep in sync with Relocation.cs +// R2R relocations encode image-relative offsets and indices, not native pointers. +// Keep their reserved width in sync with Relocation.cs. static const unsigned PADDED_RELOC_SIZE = 5; -#else -#error WASM64 -#endif unsigned emitter::instrDesc::idCodeSize() const { @@ -1075,7 +1073,9 @@ size_t emitter::emitOutputInstr(insGroup* ig, instrDesc* id, BYTE** dp) // signature occupies one pending slot until the function-index callback consumes it, // so another deferred call must not interleave these callbacks. // See #DeferredWasmCallRewriting for direct-call selection and indirect expansion. - dst += emitOutputOpcode(dst, INS_i32_const); + // The identity occupies the pointer-sized PEP parameter; on wasm64 its padded SLEB + // is sign-extended by i64.const, as for the method's own frame identity. + dst += emitOutputOpcode(dst, TARGET_POINTER_SIZE == 8 ? INS_i64_const : INS_i32_const); emitRecordRelocation(dst, reinterpret_cast(emitGetInsSC(id)), CorInfoReloc::WASM_METHOD_FRAME_IDENTITY_SLEB); dst += emitOutputPaddedReloc(dst); diff --git a/src/coreclr/jit/fgwasm.cpp b/src/coreclr/jit/fgwasm.cpp index 4493bd81ef99ee..5609b5f49d2c25 100644 --- a/src/coreclr/jit/fgwasm.cpp +++ b/src/coreclr/jit/fgwasm.cpp @@ -4268,7 +4268,7 @@ PhaseStatus Compiler::fgWasmVirtualIP() GenTree* const spLocal = gtNewLclVarNode(lvaWasmSpArg, TYP_I_IMPL); GenTree* const virtualIPslotAddr = - gtNewOperNode(GT_ADD, TYP_I_IMPL, spLocal, gtNewIconNode(TARGET_POINTER_SIZE)); + gtNewOperNode(GT_ADD, TYP_I_IMPL, spLocal, gtNewIconNode(TARGET_POINTER_SIZE, TYP_I_IMPL)); GenTreeFlags indirFlags = GTF_IND_NONFAULTING | GTF_IND_TGT_NOT_HEAP; setVirtualIP = gtNewStoreIndNode(TYP_INT, virtualIPslotAddr, virtualIPValue, indirFlags); } diff --git a/src/coreclr/jit/importercalls.cpp b/src/coreclr/jit/importercalls.cpp index 3b7157677d1fd6..1cba04d97a01a4 100644 --- a/src/coreclr/jit/importercalls.cpp +++ b/src/coreclr/jit/importercalls.cpp @@ -10990,7 +10990,7 @@ bool Compiler::impTailCallRetTypeCompatible(bool allowWideni return true; } -#ifdef TARGET_64BIT +#if defined(TARGET_64BIT) && !defined(TARGET_WASMARCH) // Jit64 compat: if (callerRetType == TYP_VOID) { @@ -11020,7 +11020,7 @@ bool Compiler::impTailCallRetTypeCompatible(bool allowWideni { return (varTypeIsIntegral(calleeRetType) || isCalleeRetTypMBEnreg) && (callerRetTypeSize == calleeRetTypeSize); } -#endif // TARGET_64BIT +#endif // defined(TARGET_64BIT) && !defined(TARGET_WASMARCH) return false; } diff --git a/src/coreclr/jit/instrswasm.h b/src/coreclr/jit/instrswasm.h index 7d3acea8e43260..5e9224d94496fb 100644 --- a/src/coreclr/jit/instrswasm.h +++ b/src/coreclr/jit/instrswasm.h @@ -95,6 +95,10 @@ INST(i32_const_funcptr, "i32.const_funcptr", 0, IF_FUNCPTR, 0x41) INST(i32_const_funcletptr, "i32.const_funcletptr", 0, IF_FUNCLETPTR, 0x41) INST(i32_const_frameidentity, "i32.const_frameidentity", 0, IF_FRAMEIDENTITY, 0x41) INST(i32_const_dataoffs, "i32.const_dataoffs", 0, IF_DATAOFFS, 0x41) +INST(i64_const_address, "i64.const_address", 0, IF_MEMADDR, 0x42) +INST(i64_const_funcletptr, "i64.const_funcletptr", 0, IF_FUNCLETPTR, 0x42) +INST(i64_const_frameidentity, "i64.const_frameidentity", 0, IF_FRAMEIDENTITY, 0x42) +INST(i64_const_dataoffs, "i64.const_dataoffs", 0, IF_DATAOFFS, 0x42) // Constants, continued INST(i64_const, "i64.const", 0, IF_SLEB128, 0x42) INST(f32_const, "f32.const", 0, IF_F32, 0x43) diff --git a/src/coreclr/jit/jit.h b/src/coreclr/jit/jit.h index 32724964f0b706..e948ccaf4c6353 100644 --- a/src/coreclr/jit/jit.h +++ b/src/coreclr/jit/jit.h @@ -145,8 +145,8 @@ #if defined(TARGET_RISCV64) #error Cannot define both TARGET_X86 and TARGET_RISCV64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_X86 and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_X86 and TARGET_WASMARCH #endif #elif defined(TARGET_AMD64) #if defined(TARGET_X86) @@ -164,8 +164,8 @@ #if defined(TARGET_RISCV64) #error Cannot define both TARGET_AMD64 and TARGET_RISCV64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_AMD64 and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_AMD64 and TARGET_WASMARCH #endif #elif defined(TARGET_ARM) #if defined(TARGET_X86) @@ -183,8 +183,8 @@ #if defined(TARGET_RISCV64) #error Cannot define both TARGET_ARM and TARGET_RISCV64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_ARM and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_ARM and TARGET_WASMARCH #endif #elif defined(TARGET_ARM64) #if defined(TARGET_X86) @@ -202,8 +202,8 @@ #if defined(TARGET_RISCV64) #error Cannot define both TARGET_ARM64 and TARGET_RISCV64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_ARM64 and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_ARM64 and TARGET_WASMARCH #endif #elif defined(TARGET_LOONGARCH64) #if defined(TARGET_X86) @@ -221,8 +221,8 @@ #if defined(TARGET_RISCV64) #error Cannot define both TARGET_LOONGARCH64 and TARGET_RISCV64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_LOONGARCH64 and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_LOONGARCH64 and TARGET_WASMARCH #endif #elif defined(TARGET_RISCV64) #if defined(TARGET_X86) @@ -240,28 +240,31 @@ #if defined(TARGET_LOONGARCH64) #error Cannot define both TARGET_RISCV64 and TARGET_LOONGARCH64 #endif -#if defined(TARGET_WASM) -#error Cannot define both TARGET_RISCV64 and TARGET_WASM +#if defined(TARGET_WASMARCH) +#error Cannot define both TARGET_RISCV64 and TARGET_WASMARCH #endif -#elif defined(TARGET_WASM) +#elif defined(TARGET_WASMARCH) +#if defined(TARGET_WASM) == defined(TARGET_WASM64) +#error TARGET_WASMARCH requires exactly one of TARGET_WASM and TARGET_WASM64 +#endif #if defined(TARGET_X86) -#error Cannot define both TARGET_WASM and TARGET_X86 +#error Cannot define both TARGET_WASMARCH and TARGET_X86 #endif #if defined(TARGET_AMD64) -#error Cannot define both TARGET_WASM and TARGET_AMD64 +#error Cannot define both TARGET_WASMARCH and TARGET_AMD64 #endif #if defined(TARGET_ARM) -#error Cannot define both TARGET_WASM and TARGET_ARM +#error Cannot define both TARGET_WASMARCH and TARGET_ARM #endif #if defined(TARGET_ARM64) -#error Cannot define both TARGET_WASM and TARGET_ARM64 +#error Cannot define both TARGET_WASMARCH and TARGET_ARM64 #endif #if defined(TARGET_LOONGARCH64) -#error Cannot define both TARGET_WASM and TARGET_LOONGARCH64 +#error Cannot define both TARGET_WASMARCH and TARGET_LOONGARCH64 #endif #if defined(TARGET_RISCV64) -#error Cannot define both TARGET_WASM and TARGET_RISCV64 +#error Cannot define both TARGET_WASMARCH and TARGET_RISCV64 #endif #else @@ -277,7 +280,7 @@ #endif // TARGET_ARM #ifdef TARGET_WASM #error Cannot define both TARGET_WASM and TARGET_64BIT -#endif // TARGET_ARM +#endif // TARGET_WASM #endif // TARGET_64BIT #if defined(TARGET_X86) || defined(TARGET_AMD64) diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index 7a06d9948badfa..425dc69c00cb2b 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -927,6 +927,21 @@ GenTree* Lowering::LowerSwitch(GenTree* node) #ifdef TARGET_WASMARCH // Wasm's br_table maps exactly to GT_SWITCH // +#ifdef TARGET_64BIT + // IL can switch on a native int, but br_table always takes an i32 index. Narrow it with a + // saturating conversion so out-of-range (including negative) indices still reach the default + // case: the conversion to double is exact in the u32 range, and float-to-int casts saturate. + GenTree* index = node->AsOp()->gtOp1; + if (genActualType(index) == TYP_LONG) + { + GenTree* indexAsDouble = m_compiler->gtNewCastNode(TYP_DOUBLE, index, /* fromUnsigned */ true, TYP_DOUBLE); + GenTree* indexAsUInt = m_compiler->gtNewCastNode(TYP_INT, indexAsDouble, /* fromUnsigned */ false, TYP_UINT); + node->AsOp()->gtOp1 = indexAsUInt; + switchBBRange.InsertBefore(node, indexAsDouble, indexAsUInt); + LowerNode(indexAsDouble); + LowerNode(indexAsUInt); + } +#endif // TARGET_64BIT return node->gtNext; #endif // TARGET_WASMARCH diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index be49489e6de29f..b42cd077b94abf 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -14682,8 +14682,8 @@ GenTree* Compiler::fgInitThisClass() { GenTree* methHndTree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); methHndTree->gtFlags |= GTF_VAR_CONTEXT; - return gtNewHelperCallNode(CORINFO_HELP_INITINSTCLASS, HelperInitClassRetType, gtNewIconNode(0), - methHndTree); + return gtNewHelperCallNode(CORINFO_HELP_INITINSTCLASS, HelperInitClassRetType, + gtNewIconNode(0, TYP_I_IMPL), methHndTree); } default: diff --git a/src/coreclr/jit/target.h b/src/coreclr/jit/target.h index 56bc18a2de5576..f324cb2f365935 100644 --- a/src/coreclr/jit/target.h +++ b/src/coreclr/jit/target.h @@ -58,6 +58,8 @@ inline bool compFeatureArgSplit() #define TARGET_READABLE_NAME "RISCV64" #elif defined(TARGET_WASM) #define TARGET_READABLE_NAME "WASM32" +#elif defined(TARGET_WASM64) +#define TARGET_READABLE_NAME "WASM64" #else #error Unsupported or unset target architecture #endif diff --git a/src/coreclr/jit/targetwasm.h b/src/coreclr/jit/targetwasm.h index d3116029160fac..6dc4292195bcbe 100644 --- a/src/coreclr/jit/targetwasm.h +++ b/src/coreclr/jit/targetwasm.h @@ -10,7 +10,7 @@ #ifdef TARGET_WASM #define CORINFO_ARCH_TARGET CORINFO_ARCH_WASM32 #else -#error NYI: WASM64 +#define CORINFO_ARCH_TARGET CORINFO_ARCH_WASM64 #endif #define WASM_THREAD_SUPPORT 0 // Codegen does not support WasmThreads yet diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/AssemblyStubNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/AssemblyStubNode.cs index 1dd8fe73fdecd4..d3590a94b4c247 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/AssemblyStubNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/AssemblyStubNode.cs @@ -84,6 +84,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly) return riscv64Emitter.Builder.ToObjectData(); case TargetArchitecture.Wasm32: + case TargetArchitecture.Wasm64: Wasm.WasmEmitter wasmEmitter = new Wasm.WasmEmitter(factory, relocsOnly); EmitCode(factory, ref wasmEmitter, relocsOnly); return wasmEmitter.Encode(this); diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs index 4443f473348b24..bc28b7e1590418 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs @@ -293,6 +293,8 @@ public void EmitReloc(ISymbolNode symbol, RelocType relocType, int delta = 0) } EmitByte(checked((byte)value)); break; + case RelocType.WASM_TABLE_INDEX_I64: + case RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64: case RelocType.IMAGE_REL_BASED_DIR64: EmitLong(delta); break; diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs index 95e201b73d1418..7bc910cee89d9c 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs @@ -66,6 +66,7 @@ public enum RelocType WASM_METHOD_RELATIVE_VIRTUAL_IP_I32 = 0x20C, // Wasm: a method virtual IP relative to the image virtual IP base, stored as a 4-byte uint32. WASM_ASYNC_RESUME_INFO_DELTA_ULEB = 0x20D, // Wasm: an image-relative delta to an async resume info fixup chunk, encoded as ULEB128. WASM_METHOD_FRAME_IDENTITY_SLEB = 0x20E, // Wasm: the current method's runtime-specific shadow-frame identity, encoded as a 5-byte varint32. + WASM_METHOD_RELATIVE_VIRTUAL_IP_I64 = 0x20F, // Wasm: a method virtual IP relative to the image virtual IP base, stored as an 8-byte uint64. // // Relocation operators related to TLS access @@ -695,6 +696,7 @@ public static unsafe void WriteValue(RelocType relocType, void* location, long v *(uint*)location = checked((uint)value); return; case RelocType.WASM_TABLE_INDEX_I64: + case RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64: *(ulong*)location = checked((ulong)value); return; @@ -775,6 +777,7 @@ public static int GetSize(RelocType relocType) RelocType.WASM_TABLE_INDEX_REL_I32 => 4, RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32 => 4, RelocType.WASM_TABLE_INDEX_I64 => 8, + RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64 => 8, _ => throw new NotSupportedException(), }; @@ -840,6 +843,7 @@ public static unsafe long ReadValue(RelocType relocType, void* location) return *(int*)location; case RelocType.IMAGE_REL_BASED_DIR64: case RelocType.WASM_TABLE_INDEX_I64: + case RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64: return *(long*)location; case RelocType.IMAGE_REL_BASED_THUMB_MOV32: case RelocType.IMAGE_REL_BASED_THUMB_MOV32_PCREL: diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmEmitter.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmEmitter.cs index 85f1a8801265c5..bb656c7892ab91 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmEmitter.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmEmitter.cs @@ -13,6 +13,7 @@ public struct WasmEmitter(NodeFactory factory, bool relocsOnly) public WasmFunctionBody FunctionBody = null!; public bool Is64Bit => factory.Target.PointerSize == 8; + internal WasmTargetPtr Ptr => new WasmTargetPtr(factory.Target.PointerSize); public bool RelocsOnly => relocsOnly; public ObjectNode.ObjectData Encode(ISymbolDefinitionNode symbolDefinitionNode) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmFunctionBodyDeduplicator.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmFunctionBodyDeduplicator.cs index 5a51873ffc8056..60809ab24ff8d0 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmFunctionBodyDeduplicator.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmFunctionBodyDeduplicator.cs @@ -122,6 +122,7 @@ RelocType.WASM_TYPE_INDEX_LEB or RelocType.WASM_GLOBAL_INDEX_LEB or RelocType.WASM_CLR_RESTORE_CONTEXT_EXCEPTION_TAG_LEB or RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32 or + RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64 or RelocType.WASM_ASYNC_RESUME_INFO_DELTA_ULEB or RelocType.IMAGE_REL_SECREL or RelocType.IMAGE_REL_TLSGD or diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs index 7bd5d813646895..fecf62c0b68d04 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysis.Wasm; +using Internal.JitInterface; // This namespace implements encodings for certain Wasm expressions (instructions) // which are used in the object writer. @@ -132,14 +133,19 @@ public enum WasmExprKind I32Const = 0x41, I64Const = 0x42, I32Eqz = 0x45, + I64Eqz = 0x50, I32Ge_s = 0x4E, I32Add = 0x6A, I32Sub = 0x6B, + I64Add = 0x7C, + I64Sub = 0x7D, + I32WrapI64 = 0xA7, I32Load = 0x28, I64Load = 0x29, F32Load = 0x2A, F64Load = 0x2B, I32Load16_u = 0x2F, + I64Load16_u = 0x33, I32Store = 0x36, I64Store = 0x37, F32Store = 0x38, @@ -168,6 +174,8 @@ public static bool IsBinaryExpr(this WasmExprKind kind) { case WasmExprKind.I32Add: case WasmExprKind.I32Sub: + case WasmExprKind.I64Add: + case WasmExprKind.I64Sub: case WasmExprKind.I32Ge_s: return true; @@ -852,6 +860,7 @@ public static WasmExpr ConstRVA(ISymbolNode symbolNode) public static WasmExpr Sub => new WasmBinaryExpr(WasmExprKind.I32Sub); public static WasmExpr Eqz => new WasmUnaryExpr(WasmExprKind.I32Eqz); public static WasmExpr Ge_s => new WasmBinaryExpr(WasmExprKind.I32Ge_s); + public static WasmExpr WrapI64 => new WasmUnaryExpr(WasmExprKind.I32WrapI64); public static WasmExpr Load(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I32Load, 4, new WasmEncodableULong(offset)); public static WasmExpr Load16_u(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I32Load16_u, 2, new WasmEncodableULong(offset)); public static WasmExpr LoadWithRVAOffset(ISymbolNode symbolNode) => new WasmMemoryArgInstruction(WasmExprKind.I32Load, 4, new WasmEncodableSymbol(symbolNode, RelocType.WASM_MEMORY_ADDR_REL_LEB)); @@ -864,10 +873,44 @@ public static WasmExpr Const(long value) { return new WasmConstExpr(WasmExprKind.I64Const, value); } + public static WasmExpr Add => new WasmBinaryExpr(WasmExprKind.I64Add); + public static WasmExpr Sub => new WasmBinaryExpr(WasmExprKind.I64Sub); + public static WasmExpr Eqz => new WasmUnaryExpr(WasmExprKind.I64Eqz); public static WasmExpr Load(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I64Load, 8, new WasmEncodableULong(offset)); + public static WasmExpr Load16_u(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I64Load16_u, 2, new WasmEncodableULong(offset)); + public static WasmExpr LoadWithRVAOffset(ISymbolNode symbolNode) => new WasmMemoryArgInstruction(WasmExprKind.I64Load, 8, new WasmEncodableSymbol(symbolNode, RelocType.WASM_MEMORY_ADDR_REL_LEB)); public static WasmExpr Store(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I64Store, 8, new WasmEncodableULong(offset)); } + /// + /// Pointer-width instructions for the target: i32 on Wasm32 and i64 on Wasm64. + /// + internal readonly struct WasmTargetPtr + { + public WasmTargetPtr(int pointerSize) + { + Debug.Assert(pointerSize is 4 or 8); + Is64Bit = pointerSize == 8; + } + + public bool Is64Bit { get; } + public int Size => Is64Bit ? 8 : 4; + public WasmValueType Type => Is64Bit ? WasmValueType.I64 : WasmValueType.I32; + public CorInfoWasmType CorInfoType => Is64Bit ? CorInfoWasmType.CORINFO_WASM_TYPE_I64 : CorInfoWasmType.CORINFO_WASM_TYPE_I32; + public WasmExprKind ConstKind => Is64Bit ? WasmExprKind.I64Const : WasmExprKind.I32Const; + + public WasmExpr Const(long value) => Is64Bit ? I64.Const(value) : I32.Const(value); + public WasmExpr Add => Is64Bit ? I64.Add : I32.Add; + public WasmExpr Sub => Is64Bit ? I64.Sub : I32.Sub; + public WasmExpr Eqz => Is64Bit ? I64.Eqz : I32.Eqz; + public WasmExpr Load(ulong offset) => Is64Bit ? I64.Load(offset) : I32.Load(offset); + public WasmExpr LoadWithRVAOffset(ISymbolNode symbolNode) => Is64Bit ? I64.LoadWithRVAOffset(symbolNode) : I32.LoadWithRVAOffset(symbolNode); + public WasmExpr Store(ulong offset) => Is64Bit ? I64.Store(offset) : I32.Store(offset); + + /// Loads a 16-bit unsigned value, zero-extended to pointer width. + public WasmExpr Load16_u(ulong offset) => Is64Bit ? I64.Load16_u(offset) : I32.Load16_u(offset); + } + internal static class F32 { public static WasmExpr Load(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.F32Load, 4, new WasmEncodableULong(offset)); diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs index 496d4139749bd2..5d61e112682bee 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs @@ -123,15 +123,18 @@ public override int Encode(Span buffer) public class WasmTableImportType : WasmImportType { - public WasmTableImportType() : base (WasmExternalKind.Table) + private readonly bool _is64Bit; + + public WasmTableImportType(bool is64Bit = false) : base(WasmExternalKind.Table) { + _is64Bit = is64Bit; } public override int Encode(Span buffer) { int pos = 0; buffer[pos++] = (byte)0x70; // element type: funcref - buffer[pos++] = (byte)0; // table limits: flags (0 = min-only, 1 = min+max) + buffer[pos++] = (byte)(_is64Bit ? WasmLimitType.HasMin64 : WasmLimitType.HasMin); pos += DwarfHelper.WriteULEB128(buffer.Slice(pos), 1); // Requires 1 table entry return pos; } @@ -144,7 +147,8 @@ public override int Encode(Span buffer) public enum WasmLimitType : byte { HasMin = 0x00, - HasMinAndMax = 0x01 + HasMinAndMax = 0x01, + HasMin64 = 0x04 } public class WasmMemoryImportType : WasmImportType diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs index 3e546d0af88b73..b052ef2d2254a2 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs @@ -422,7 +422,7 @@ private unsafe int WriteRelocationEntries(SectionDataEmitter section, int conten fixed (byte* pData = relocScratchBuffer) { long addend = reloc.Addend + Relocation.ReadValue(reloc.Type, pData); - if (reloc.Type is RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32) + if (reloc.Type is RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32 or RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64) { Relocation.WriteValue(reloc.Type, pData, checked(_methodStartVirtualIPs[reloc.SymbolName] + addend)); sectionStream.Position = reloc.Offset; diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WebCilObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WebCilObjectWriter.cs index 4ad39ee6d14e60..0f901e8cf12064 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WebCilObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WebCilObjectWriter.cs @@ -99,8 +99,11 @@ WasmInstructionGroup GetImageFunctionPointerBaseOffset(int offset) ]); } - static WasmFunctionBody GetWebcilSize = new WasmFunctionBody( - new WasmFuncType(new([WasmValueType.I32]), new([])), // (func (destPtr i32) (result)) + private bool Is64Bit => _nodeFactory.Target.PointerSize == 8; + private WasmValueType PointerType => Is64Bit ? WasmValueType.I64 : WasmValueType.I32; + + private WasmFunctionBody GetWebcilSize => new WasmFunctionBody( + new WasmFuncType(new([PointerType]), new([])), [ Local.Get(0), // (local.get $destPtr) I32.Const(0), @@ -118,19 +121,23 @@ WasmInstructionGroup GetImageFunctionPointerBaseOffset(int offset) /// silently shifting every R2R function index by tableBase. Hosts must call this after /// instantiation. /// - static WasmFunctionBody PatchWebcilHeader = new WasmFunctionBody( - new WasmFuncType(new([WasmValueType.I32, WasmValueType.I32]), new([])), // (func ($d i32) ($n i32)) - [ + private WasmFunctionBody CreatePatchWebcilHeader() + { + List instructions = [ Local.Get(1), I32.Const(32), I32.Ge_s, Block.If(WasmBlockType.Empty), Local.Get(0), // (local.get $d) - Global.Get(WebCilObjectWriter.TableBaseGlobalIndex), // (global.get $tableBase) - I32.Store((ulong)WebcilEncoder.TableBaseOffset), // i32.store offset=TableBaseOffset - Block.End - ] - ); + Global.Get(TableBaseGlobalIndex), + ]; + // The WebCIL header stores a 32-bit table base even when the table uses i64 operands. + if (Is64Bit) + instructions.Add(I32.WrapI64); + instructions.Add(I32.Store((ulong)WebcilEncoder.TableBaseOffset)); + instructions.Add(Block.End); + return new WasmFunctionBody(new WasmFuncType(new([PointerType, WasmValueType.I32]), new([])), instructions.ToArray()); + } private long ResolveSymbolRVA(WebcilSection[] sections, SymbolDefinition definition) { @@ -284,7 +291,7 @@ private protected override void EmitSectionsAndLayout() const int stubCount = 2; int totalMethodCount = MethodCount + stubCount; InsertWasmStub(new Utf8String("getWebcilSize"), GetWebcilSize); - InsertWasmStub(new Utf8String("patchWebcilHeader"), PatchWebcilHeader); + InsertWasmStub(new Utf8String("patchWebcilHeader"), CreatePatchWebcilHeader()); Debug.Assert(MethodCount == totalMethodCount); @@ -892,6 +899,7 @@ private unsafe int ResolveReloc(int sectionIndex, MemoryStream sourceStream, lon switch (reloc.Type) { case RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32: + case RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64: Relocation.WriteValue(reloc.Type, pData, reloc.Addend + addend); break; case RelocType.WASM_METHOD_FRAME_IDENTITY_SLEB: @@ -1121,11 +1129,11 @@ private WasmImport[] CreateDefaultGlobalImports() return [ - new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.StackPointerName, import: new WasmGlobalImportType(WasmValueType.I32, WasmMutabilityType.Mut), index: StackPointerGlobalIndex), - new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.ImageBaseName, import: new WasmGlobalImportType(WasmValueType.I32, WasmMutabilityType.Const), index: ImageBaseGlobalIndex), - new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.TableBaseName, import: new WasmGlobalImportType(WasmValueType.I32, WasmMutabilityType.Const), index: TableBaseGlobalIndex), - new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.AsyncContinuationName, import: new WasmGlobalImportType(WasmValueType.I32, WasmMutabilityType.Mut), index: AsyncContinuationGlobalIndex), - new WasmImport("webcil", IndirectFunctionTableName, import: new WasmTableImportType(), index: 0), + new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.StackPointerName, import: new WasmGlobalImportType(PointerType, WasmMutabilityType.Mut), index: StackPointerGlobalIndex), + new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.ImageBaseName, import: new WasmGlobalImportType(PointerType, WasmMutabilityType.Const), index: ImageBaseGlobalIndex), + new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.TableBaseName, import: new WasmGlobalImportType(PointerType, WasmMutabilityType.Const), index: TableBaseGlobalIndex), + new WasmImport("webcil", WasmWellKnownGlobalSymbolNode.AsyncContinuationName, import: new WasmGlobalImportType(PointerType, WasmMutabilityType.Mut), index: AsyncContinuationGlobalIndex), + new WasmImport("webcil", IndirectFunctionTableName, import: new WasmTableImportType(Is64Bit), index: 0), new WasmImport("webcil", RtlRestoreContextTagName.ToString(), import: new WasmTagImportType(rtlRestoreContextTagTypeIndex), index: RtlRestoreContextTagIndex), ]; } @@ -1143,7 +1151,7 @@ private void WriteMemoryImport(ulong contentSize) uint dataPages = checked((uint)((contentSize + (1 << 16) - 1) >> 16)); uint numPages = Math.Max(dataPages, 1); // Ensure at least one page is allocated for the minimum - WasmImport memoryImport = new WasmImport("webcil", "memory", import: new WasmMemoryImportType(WasmLimitType.HasMin, numPages)); // memory limits: flags (0 = only minimum) + WasmImport memoryImport = new WasmImport("webcil", "memory", import: new WasmMemoryImportType(Is64Bit ? WasmLimitType.HasMin64 : WasmLimitType.HasMin, numPages)); WriteImport(memoryImport); } diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index 272c30be01c6fe..43eeaa4f9e5cc5 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -1492,7 +1492,7 @@ private void reportTailCallDecision(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_M #if READYTORUN // R2R/interpreter transitions do not preserve tail calls, and explicit tail calls that cannot be // fast are demoted to regular calls. Leave methods with explicit tail calls to the interpreter. - if (fIsTailPrefix && MethodBeingCompiled.Context.Target.Architecture == TargetArchitecture.Wasm32) + if (fIsTailPrefix && MethodBeingCompiled.Context.Target.IsWasm) { throw new RequiresRuntimeJitException(nameof(reportTailCallDecision)); } @@ -4975,6 +4975,8 @@ private uint getExpectedTargetArchitecture() return (uint)CorInfoArch.CORINFO_ARCH_RISCV64; case TargetArchitecture.Wasm32: return (uint)CorInfoArch.CORINFO_ARCH_WASM32; + case TargetArchitecture.Wasm64: + return (uint)CorInfoArch.CORINFO_ARCH_WASM64; default: throw new NotImplementedException("Expected target architecture is not supported"); } @@ -5125,7 +5127,7 @@ private uint getJitFlags(ref CORJIT_FLAGS flags, uint sizeInBytes) } #if READYTORUN - if (this.MethodBeingCompiled.Context.Target.Architecture == TargetArchitecture.Wasm32) + if (this.MethodBeingCompiled.Context.Target.IsWasm) { flags.Set(CorJitFlag.CORJIT_FLAG_PORTABLE_ENTRY_POINTS); if (_methodCodeNode.IsJitHelper) diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs index 17e20d028f7850..26d1f420c9d249 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs @@ -531,6 +531,7 @@ public enum CorInfoReloc WASM_METHOD_RELATIVE_VIRTUAL_IP_I32, // Wasm: the current method's virtual IP relative to the image virtual IP base, stored as a 4-byte uint32. WASM_METHOD_FRAME_IDENTITY_SLEB, // Wasm: the current method's runtime-specific shadow-frame identity, encoded as a 5-byte varint32. WASM_DEFERRED_CALL, // Wasm: metadata for a deferred direct call; the target is its exact signature handle and the location is its first immediate byte. Does not write bytes. + WASM_METHOD_RELATIVE_VIRTUAL_IP_I64, // Wasm: the current method's virtual IP relative to the image virtual IP base, stored as an 8-byte uint64. } public enum CorInfoGCType @@ -895,6 +896,7 @@ public enum CorInfoArch CORINFO_ARCH_LOONGARCH64, CORINFO_ARCH_RISCV64, CORINFO_ARCH_WASM32, + CORINFO_ARCH_WASM64, } public enum CORINFO_OS diff --git a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs index 7d1c182ce32119..8435f108472352 100644 --- a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs +++ b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs @@ -147,6 +147,7 @@ private static string GetTargetSpec(TargetDetails target) TargetArchitecture.ARM => "arm", TargetArchitecture.ARM64 => "arm64", TargetArchitecture.Wasm32 => "wasm", + TargetArchitecture.Wasm64 => "wasm64", TargetArchitecture.LoongArch64 => "loongarch64", TargetArchitecture.RiscV64 => "riscv64", _ => throw new NotImplementedException(target.Architecture.ToString()) diff --git a/src/coreclr/tools/Common/TypeSystem/IL/AsyncMethodIL.cs b/src/coreclr/tools/Common/TypeSystem/IL/AsyncMethodIL.cs new file mode 100644 index 00000000000000..e5cc30e8d52492 --- /dev/null +++ b/src/coreclr/tools/Common/TypeSystem/IL/AsyncMethodIL.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using ILCompiler; + +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +namespace Internal.IL +{ + /// + /// IL of an async variant method: the IL of the method it wraps, owned by the variant. + /// + public class AsyncMethodIL : MethodIL + { + private readonly AsyncMethodVariant _variant; + private readonly MethodIL _wrappedIL; + + private AsyncMethodIL(AsyncMethodVariant variant, MethodIL wrappedIL) + => (_variant, _wrappedIL) = (variant, wrappedIL); + + /// + /// Wraps as the IL of . Ecma IL stays Ecma IL, with + /// tokens relative to the wrapped IL's module, which is not necessarily the variant's owning module. + /// + public static AsyncMethodIL Create(AsyncMethodVariant variant, MethodIL wrappedIL) + => wrappedIL is IEcmaMethodIL ecmaIL + ? new EcmaAsyncMethodIL(variant, wrappedIL, ecmaIL.Module) + : new AsyncMethodIL(variant, wrappedIL); + + // This is the reason we need this class - the method that owns the IL is the variant. + public override MethodDesc OwningMethod => _variant; + + // Everything else dispatches to the wrapped IL + public override MethodDebugInformation GetDebugInfo() => _wrappedIL.GetDebugInfo(); + public override ILExceptionRegion[] GetExceptionRegions() => _wrappedIL.GetExceptionRegions(); + public override byte[] GetILBytes() => _wrappedIL.GetILBytes(); + public override LocalVariableDefinition[] GetLocals() => _wrappedIL.GetLocals(); + public override object GetObject(int token, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw) => _wrappedIL.GetObject(token, notFoundBehavior); + public override bool IsInitLocals => _wrappedIL.IsInitLocals; + public override int MaxStack => _wrappedIL.MaxStack; + + private sealed class EcmaAsyncMethodIL : AsyncMethodIL, IEcmaMethodIL + { + public EcmaAsyncMethodIL(AsyncMethodVariant variant, MethodIL wrappedIL, IEcmaModule module) + : base(variant, wrappedIL) + { + Module = module; + } + + public IEcmaModule Module { get; } + } + } +} diff --git a/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs b/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs index fcd5925c258985..367108e79ab9fa 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs @@ -369,9 +369,7 @@ public override MethodIL GetMethodIL(MethodDesc method) if (wrappedIL == null) return null; - return wrappedIL is EcmaMethodIL ecmaIL - ? new EcmaAsyncMethodIL(asyncVariantImpl, ecmaIL) - : new AsyncMethodIL(asyncVariantImpl, wrappedIL); + return AsyncMethodIL.Create(asyncVariantImpl, wrappedIL); } else { @@ -379,37 +377,5 @@ public override MethodIL GetMethodIL(MethodDesc method) return null; } } - - private class AsyncMethodIL : MethodIL - { - private readonly AsyncMethodVariant _variant; - private readonly MethodIL _wrappedIL; - - public AsyncMethodIL(AsyncMethodVariant variant, MethodIL wrappedIL) - => (_variant, _wrappedIL) = (variant, wrappedIL); - - // This is the reason we need this class - the method that owns the IL is the variant. - public override MethodDesc OwningMethod => _variant; - - // Everything else dispatches to the wrapped IL - public override MethodDebugInformation GetDebugInfo() => _wrappedIL.GetDebugInfo(); - public override ILExceptionRegion[] GetExceptionRegions() => _wrappedIL.GetExceptionRegions(); - public override byte[] GetILBytes() => _wrappedIL.GetILBytes(); - public override LocalVariableDefinition[] GetLocals() => _wrappedIL.GetLocals(); - public override object GetObject(int token, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw) => _wrappedIL.GetObject(token, notFoundBehavior); - public override bool IsInitLocals => _wrappedIL.IsInitLocals; - public override int MaxStack => _wrappedIL.MaxStack; - } - - private sealed class EcmaAsyncMethodIL : AsyncMethodIL, IEcmaMethodIL - { - public EcmaAsyncMethodIL(AsyncMethodVariant variant, EcmaMethodIL wrappedIL) - : base(variant, wrappedIL) - { - Module = wrappedIL.Module; - } - - public IEcmaModule Module { get; } - } } } diff --git a/src/coreclr/tools/aot/AotCompilerCommon.props b/src/coreclr/tools/aot/AotCompilerCommon.props index 3b32ec28c10801..af78072ebd1268 100644 --- a/src/coreclr/tools/aot/AotCompilerCommon.props +++ b/src/coreclr/tools/aot/AotCompilerCommon.props @@ -16,7 +16,7 @@ <_TargetArchitectureForJitLibraryName>$(TargetArchitecture) <_TargetArchitectureForJitLibraryName Condition="'$(_TargetArchitectureForJitLibraryName)' == 'armel'">arm <_TargetArchitectureForJitLibraryName Condition="'$(_TargetArchitectureForJitLibraryName)' == 'wasm'">wasm - <_TargetOSForJitLibraryName Condition="'$(TargetArchitecture)' == 'arm' or '$(TargetArchitecture)' == 'armel' or '$(TargetArchitecture)' == 'arm64' or '$(TargetArchitecture)' == 'wasm'">universal + <_TargetOSForJitLibraryName Condition="'$(TargetArchitecture)' == 'arm' or '$(TargetArchitecture)' == 'armel' or '$(TargetArchitecture)' == 'arm64' or '$(TargetsWasmArch)' == 'true'">universal <_TargetOSForJitLibraryName Condition="'$(_TargetOSForJitLibraryName)' == '' and '$(TargetOS)' == 'windows'">win <_TargetOSForJitLibraryName Condition="'$(_TargetOSForJitLibraryName)' == ''">unix $(_LibPrefix)clrjit_$(_TargetOSForJitLibraryName)_$(_TargetArchitectureForJitLibraryName)_$(TargetArchitectureForSharedLibraries)$(_LibSuffix) @@ -39,7 +39,7 @@ CopyToPublishDirectory="PreserveNewest" ExcludeFromSingleFile="$(PublishSingleFile)" Link="$(SingleJitLibraryName)" - Condition="'$(CrossHostArch)' != '' and '$(CopyAllJitLibrariesToAotCompilerOutput)' != 'true' and '$(TargetsWasm64)' != 'true'" + Condition="'$(CrossHostArch)' != '' and '$(CopyAllJitLibrariesToAotCompilerOutput)' != 'true'" /> diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index b6f8ae9962294e..fe1a56a84c3dfe 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -51,6 +51,7 @@ + IL\Stubs\DelegateThunks.Sorting.cs diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallProcessor.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallProcessor.cs index cab1a1f5ee86b9..2908fad51d7424 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallProcessor.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallProcessor.cs @@ -142,7 +142,7 @@ internal ISymbolNode GetCall(MethodWithToken method, ISymbolNode fallback, WasmT internal bool CanUseDirectCall(MethodDesc method, out DeferredWasmMethodFinalizationInfo finalizationInfo) { finalizationInfo = default; - return NodeFactory.Target.Architecture == TargetArchitecture.Wasm32 && + return NodeFactory.Target.IsWasm && _finalizedMethods.TryGetValue(method, out finalizationInfo) && (finalizationInfo.IsEager || _finalizingEagerMethods || (!method.IsNoInlining && !method.IsNoOptimization && diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallRewriter.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallRewriter.cs index 6b742131b1dd4a..3f604ac5f5b6c4 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallRewriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DeferredWasmCallRewriter.cs @@ -35,7 +35,7 @@ namespace ILCompiler; // rebase surviving relocations, update frame ranges and body-size prefixes, // and map raw debug offsets before their final encoding. // -// scratchLocals assigns one appended i32 PEP temporary per body, including +// scratchLocals assigns one appended pointer-sized PEP temporary per body, including // funclets. activationImports preserves the first import-time activation // token for each target, which need not match a surviving call site's token. // _fixups and _fixupsInitialized lazily seed and reuse a per-method set for @@ -137,7 +137,7 @@ private void RewriteCore( if (relocation.Target is DeferredWasmCallNode call) { Debug.Assert(relocation.RelocType == RelocType.WASM_FUNCTION_INDEX_LEB); - AssertDeferredCall(original.Data, relocation.Offset); + AssertDeferredCall(original.Data, relocation.Offset, new WasmTargetPtr(compilation.NodeFactory.Target.PointerSize)); bool direct = compilation.DeferredWasmCalls.CanUseDirectCall(call.Method, out DeferredWasmMethodFinalizationInfo info); Debug.Assert(direct); SelectCall(method, call, useDirectCall: true, info.IsEager, activationImports); @@ -155,6 +155,7 @@ private void RewriteWithIndirectCalls( Dictionary activationImports) { NodeFactory factory = compilation.NodeFactory; + WasmTargetPtr ptr = new WasmTargetPtr(factory.Target.PointerSize); Relocation[] originalRelocations = original.Relocs ?? []; FrameInfo[] frames = method.FrameInfos; var edits = new List(); @@ -165,7 +166,7 @@ private void RewriteWithIndirectCalls( if (relocation.Target is DeferredWasmCallNode call) { Debug.Assert(relocation.RelocType == RelocType.WASM_FUNCTION_INDEX_LEB); - AssertDeferredCall(original.Data, relocation.Offset); + AssertDeferredCall(original.Data, relocation.Offset, ptr); bool direct = compilation.DeferredWasmCalls.CanUseDirectCall(call.Method, out DeferredWasmMethodFinalizationInfo info); SelectCall(method, call, direct, info.IsEager, activationImports); if (direct) @@ -182,7 +183,7 @@ private void RewriteWithIndirectCalls( Debug.Assert(instructionOffset > frames[frameIndex].StartOffset); if (!scratchLocals.TryGetValue(frameIndex, out int scratchLocal)) { - scratchLocal = AddScratchLocal(method, original.Data, frameIndex, edits); + scratchLocal = AddScratchLocal(method, original.Data, frameIndex, edits, ptr); scratchLocals.Add(frameIndex, scratchLocal); } @@ -190,7 +191,8 @@ private void RewriteWithIndirectCalls( bool tailCall = original.Data[relocation.Offset - 1] == (byte)WasmExprKind.ReturnCall; edits.Add(EncodeEdit(instructionOffset, DeferredCallLength, new WasmLEBConstantReloc(WasmExprKind.GlobalGet, imageBase, RelocType.WASM_GLOBAL_INDEX_LEB), - I32.LoadWithRVAOffset(call.Fallback), Local.Tee(scratchLocal), Local.Get(scratchLocal), I32.Load(0), + ptr.LoadWithRVAOffset(call.Fallback), + Local.Tee(scratchLocal), Local.Get(scratchLocal), ptr.Load(0), new WasmIndirectCallInstruction( tailCall ? WasmExprKind.ReturnCallIndirect : WasmExprKind.CallIndirect, call.Signature, 0))); @@ -294,11 +296,12 @@ int MapOffset(int offset) } } - // Append a non-GC i32 local so fallback calls can reuse the loaded PEP without + // Append a non-GC pointer-sized local so fallback calls can reuse the loaded PEP without // renumbering JIT locals. Return its index after accounting for the main // method's or funclet's parameters. - private static int AddScratchLocal(MethodWithGCInfo method, byte[] code, int frameIndex, List edits) + private static int AddScratchLocal(MethodWithGCInfo method, byte[] code, int frameIndex, List edits, WasmTargetPtr ptr) { + byte pointerType = (byte)ptr.Type; int start = method.FrameInfos[frameIndex].StartOffset + BodySizePrefixLength; int position = start; int groupCount = ReadUnsigned(code, ref position); @@ -315,7 +318,7 @@ private static int AddScratchLocal(MethodWithGCInfo method, byte[] code, int fra lastGroupType = code[position++]; } - bool extendLastGroup = groupCount != 0 && lastGroupType == (byte)WasmValueType.I32; + bool extendLastGroup = groupCount != 0 && lastGroupType == pointerType; int newGroupCount = groupCount + (extendLastGroup ? 0 : 1); int prefixSize = checked((int)DwarfHelper.SizeOfULEB128((ulong)newGroupCount)); int copiedLength = (extendLastGroup ? lastGroupStart : position) - groupsStart; @@ -325,7 +328,7 @@ private static int AddScratchLocal(MethodWithGCInfo method, byte[] code, int fra DwarfHelper.WriteULEB128(declarations, (ulong)newGroupCount); code.AsSpan(groupsStart, copiedLength).CopyTo(declarations.AsSpan(prefixSize)); DwarfHelper.WriteULEB128(declarations.AsSpan(prefixSize + copiedLength), (ulong)appendedCount); - declarations[^1] = (byte)WasmValueType.I32; + declarations[^1] = pointerType; edits.Add(new Edit(start, position - start, declarations, [])); int parameterCount = frameIndex == 0 @@ -345,10 +348,10 @@ private static int ReadUnsigned(byte[] code, ref int position) // Check the instruction-boundary assumptions needed to replace the identity // constant and call as one self-contained bundle. [Conditional("DEBUG")] - private static void AssertDeferredCall(byte[] code, int callOffset) + private static void AssertDeferredCall(byte[] code, int callOffset, WasmTargetPtr ptr) { Debug.Assert(callOffset >= RelocInstructionLength + 1); - Debug.Assert(code[callOffset - RelocInstructionLength - 1] == (byte)WasmExprKind.I32Const); + Debug.Assert(code[callOffset - RelocInstructionLength - 1] == (byte)ptr.ConstKind); Debug.Assert(code[callOffset - 1] is (byte)WasmExprKind.Call or (byte)WasmExprKind.ReturnCall); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs index 00ef66205e7102..cc395ac2fbc9ad 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs @@ -40,7 +40,7 @@ public DelayLoadHelperImport( _helper = helper; _useVirtualCall = useVirtualCall; _useJumpableStub = useJumpableStub; - if (factory.Target.Architecture == TargetArchitecture.Wasm32) + if (factory.Target.IsWasm) { _delayLoadHelper = factory.WasmImportThunkPortableEntrypoint(this); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ExceptionInfoLookupTableNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ExceptionInfoLookupTableNode.cs index 8b11f1410e8844..971b4d8eca6887 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ExceptionInfoLookupTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ExceptionInfoLookupTableNode.cs @@ -118,7 +118,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // Add the symbol representing this object node exceptionInfoLookupBuilder.AddSymbol(this); - bool isWasm = factory.Target.Architecture == TargetArchitecture.Wasm32; + bool isWasm = factory.Target.IsWasm; // First, emit the actual EH records in sequence and store map from methods to the EH record symbols for (int index = 0; index < _methodNodes.Count; index++) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InjectStringThunksSignature.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InjectStringThunksSignature.cs index e5076a652ba18e..6a45a478b5a1e6 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InjectStringThunksSignature.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InjectStringThunksSignature.cs @@ -43,7 +43,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // Emit a 4-byte relocation to the stub code. // On WASM, this is a table index; on other platforms, an RVA. - RelocType relocType = factory.Target.Architecture == TargetArchitecture.Wasm32 + RelocType relocType = factory.Target.IsWasm ? RelocType.WASM_TABLE_INDEX_REL_I32 : RelocType.IMAGE_REL_BASED_ADDR32NB; builder.EmitReloc(stub, relocType, delta: factory.Target.CodeDelta); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/MethodGCInfoNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/MethodGCInfoNode.cs index 850ec40f1a7c14..8d175b6f14a390 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/MethodGCInfoNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/MethodGCInfoNode.cs @@ -41,12 +41,12 @@ protected override void OnMarked(NodeFactory factory) private static bool TargetUsesPersonalityRoutines(TargetArchitecture targetArch) { - return targetArch != TargetArchitecture.X86 && targetArch != TargetArchitecture.Wasm32; + return targetArch is not (TargetArchitecture.X86 or TargetArchitecture.Wasm32 or TargetArchitecture.Wasm64); } private static bool TargetAlignsGCInfoComponents(TargetArchitecture targetArch) { - return targetArch != TargetArchitecture.Wasm32; + return targetArch is not (TargetArchitecture.Wasm32 or TargetArchitecture.Wasm64); } public int[] CalculateFuncletOffsets(NodeFactory factory) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ResumptionStubEntryPointSignature.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ResumptionStubEntryPointSignature.cs index 2a2885de5736b4..aa3bc698541b1d 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ResumptionStubEntryPointSignature.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ResumptionStubEntryPointSignature.cs @@ -21,7 +21,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) builder.AddSymbol(this); builder.EmitByte((byte)ReadyToRunFixupKind.ResumptionStubEntryPoint); // On wasm the stub is a function-table index (WASM_TABLE_INDEX_REL_I32); elsewhere an imageBase RVA. - RelocType relocType = factory.Target.Architecture == TargetArchitecture.Wasm32 + RelocType relocType = factory.Target.IsWasm ? RelocType.WASM_TABLE_INDEX_REL_I32 : RelocType.IMAGE_REL_BASED_ADDR32NB; builder.EmitReloc(_resumptionStub, relocType); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs index f6967aad85279c..a6c745e114d242 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs @@ -65,7 +65,7 @@ private void LayoutRuntimeFunctions() public uint GetWasmVirtualIP(MethodWithGCInfo lookupMethod, int lookupFrameIndex) { - bool isWasm = _nodeFactory.Target.Architecture == TargetArchitecture.Wasm32; + bool isWasm = _nodeFactory.Target.IsWasm; if (!isWasm) { @@ -132,7 +132,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) uint runtimeFunctionIndex = 0; List mapping = new List(); - bool isWasm = _nodeFactory.Target.Architecture == TargetArchitecture.Wasm32; + bool isWasm = _nodeFactory.Target.IsWasm; for (int cold = 0; cold < 2; cold++) { @@ -252,6 +252,6 @@ public int TableSizeExcludingSentinel public override int ClassCode => (int)ObjectNodeOrder.RuntimeFunctionsTableNode; internal int SentinelSizeAdjustment => - _nodeFactory.Target.Architecture == TargetArchitecture.Wasm32 ? -8 : -4; + _nodeFactory.Target.IsWasm ? -8 : -4; } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/StoreMultiCallableAddrOfCodeSignature.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/StoreMultiCallableAddrOfCodeSignature.cs index 3f80c3bb958a85..89d19d3fba32b0 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/StoreMultiCallableAddrOfCodeSignature.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/StoreMultiCallableAddrOfCodeSignature.cs @@ -53,7 +53,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // On wasm the target code is a function-table index (WASM_TABLE_INDEX_REL_I32); elsewhere // an imageBase RVA. Keep this in sync with ResumptionStubEntryPointSignature. - RelocType codeRelocType = factory.Target.Architecture == TargetArchitecture.Wasm32 + RelocType codeRelocType = factory.Target.IsWasm ? RelocType.WASM_TABLE_INDEX_REL_I32 : RelocType.IMAGE_REL_BASED_ADDR32NB; builder.EmitReloc(_target, codeRelocType); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmClosedStaticRetBufThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmClosedStaticRetBufThunkNode.cs index ae57897d0e6098..4ed6a8d630b48a 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmClosedStaticRetBufThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmClosedStaticRetBufThunkNode.cs @@ -65,7 +65,6 @@ protected override void ComputeNonRelocationBasedDependencies(DependencySink sin protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructionEncoder, bool relocsOnly) { - Debug.Assert(!instructionEncoder.Is64Bit); Debug.Assert(_signature.SignatureString[0] == 'S'); Debug.Assert(!_signature.SignatureString.Contains('a')); @@ -76,11 +75,13 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructio int targetEntryPointLocalIndex = parameters.Length; List expressions = new List(parameters.Length + 8); + WasmTargetPtr ptr = instructionEncoder.Ptr; + // The target PEP is stored immediately before this stub's PEP. expressions.Add(Local.Get(portableEntryPointIndex)); - expressions.Add(I32.Const(factory.Target.PointerSize)); - expressions.Add(I32.Sub); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Const(ptr.Size)); + expressions.Add(ptr.Sub); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Set(targetEntryPointLocalIndex)); expressions.Add(Local.Get(0)); // shadow stack pointer @@ -94,12 +95,12 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructio expressions.Add(Local.Get(targetEntryPointLocalIndex)); expressions.Add(Local.Get(targetEntryPointLocalIndex)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); expressions.Add(ControlFlow.CallIndirect(_typeNode, 0)); instructionEncoder.FunctionBody = new WasmFunctionBody( _signature.FuncType, - new[] { WasmValueType.I32 }, + new[] { ptr.Type }, expressions.ToArray()); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs index bb923739979129..05b740a1ac9202 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs @@ -97,18 +97,17 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer return comparer.Compare(_helperCell, otherNode._helperCell); } - static CorInfoWasmType[] _helperTypeParams = new CorInfoWasmType[] { CorInfoWasmType.CORINFO_WASM_TYPE_I32, CorInfoWasmType.CORINFO_WASM_TYPE_I32, CorInfoWasmType.CORINFO_WASM_TYPE_I32, CorInfoWasmType.CORINFO_WASM_TYPE_I32, CorInfoWasmType.CORINFO_WASM_TYPE_I32 }; - protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instructionEncoder, bool relocsOnly) { Debug.Assert(_thunkKind == ImportThunkKind.DelayLoadHelper); - Debug.Assert(!instructionEncoder.Is64Bit); // We currently only support 32-bit, and the thunk logic is currently tied to that assumption + WasmTargetPtr ptr = instructionEncoder.Ptr; + CorInfoWasmType ptrType = ptr.CorInfoType; // WASM-TODO! This is NOT an efficient way to implement this thunk. Currently it writes all the arguments to the stack, not just the ones which need to be saved for GC purposes. // At some point we'll want to only write the arguments which need GC tracking, and skip the save/restore for other arguments. This might require changes to code // which is currently architecture neutral on the VM side, so we should wait to do this until we have a better picture of how the VM and compiler sides will interact for this thunk. - ISymbolNode helperTypeIndex = factory.WasmTypeNode(_helperTypeParams); + ISymbolNode helperTypeIndex = factory.WasmTypeNode([ptrType, ptrType, ptrType, ptrType, CorInfoWasmType.CORINFO_WASM_TYPE_I32]); WasmThunkArgLayout layout = new WasmThunkArgLayout(_wasmSignature, _context); @@ -121,25 +120,23 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr List expressions = new List(); // local.get 0 expressions.Add(Local.Get(0)); - // i32.const {sizeOfStoredLocals} - expressions.Add(I32.Const(sizeOfStoredLocals)); - // i32.sub - expressions.Add(I32.Sub); + expressions.Add(ptr.Const(sizeOfStoredLocals)); + expressions.Add(ptr.Sub); // local.set 0 expressions.Add(Local.Set(0)); // Initialize m_ReturnAddress to 0 at offset 0 of the transition block - // The 0 is a marker that the actual return address is to be computed from the m_StackPointer at offset 4. + // The 0 indicates that the return address is computed from m_StackPointer. expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(0)); - expressions.Add(I32.Store(0)); + expressions.Add(ptr.Const(0)); + expressions.Add(ptr.Store(0)); - // Store the original caller's frame pointer (SP before allocation) at offset 4 + // Store the original caller's frame pointer (SP before allocation). expressions.Add(Local.Get(0)); expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(sizeOfStoredLocals)); - expressions.Add(I32.Add); - expressions.Add(I32.Store(4)); + expressions.Add(ptr.Const(sizeOfStoredLocals)); + expressions.Add(ptr.Add); + expressions.Add(ptr.Store((ulong)ptr.Size)); // Stash the arguments in the transition block foreach (WasmThunkArg arg in layout.Args) @@ -156,10 +153,10 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // memory.fill: (dst, val, len) -> () expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(arg.Offset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(arg.Offset)); + expressions.Add(ptr.Add); expressions.Add(I32.Const(0)); - expressions.Add(I32.Const(fillSize)); + expressions.Add(ptr.Const(fillSize)); expressions.Add(Memory.Fill()); continue; } @@ -188,8 +185,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Load the helper function address and dispatch // global.get {module base} expressions.Add(Global.Get(WebCilObjectWriter.ImageBaseGlobalIndex)); // Module base used to load the helper function address - expressions.Add(I32.LoadWithRVAOffset(_helperCell)); // Load the helper call function pointer from the helper cell, using a load with an RVA offset so that the helper cell can be left as a zero in the R2R image and fixed up at runtime. This avoids the need to emit a runtime relocation for the helper cell. - // call_indirect (i32, i32, i32, i32) -> (i32) + expressions.Add(ptr.LoadWithRVAOffset(_helperCell)); expressions.Add(ControlFlow.CallIndirect(helperTypeIndex, 0)); // local.set (PortableEntrypointThunk) / At this point we can overwrite with the incoming portable entrypoint local, since the old value will no longer be used @@ -198,10 +194,8 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // ;Setup sp arg for the final call, with the call address now coming from the portable entrypoint // local.get 0 expressions.Add(Local.Get(0)); - // i32.const {sizeofstoredlocals} - expressions.Add(I32.Const(sizeOfStoredLocals)); - // i32.add - expressions.Add(I32.Add); + expressions.Add(ptr.Const(sizeOfStoredLocals)); + expressions.Add(ptr.Add); // Reload the arguments for the final call foreach (WasmThunkArg arg in layout.Args) @@ -227,8 +221,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // ; Load the actual target to jump to // local.get (PortableEntrypointThunk) expressions.Add(Local.Get(portableEntrypointLocalIndex)); - // i32.load 0 - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); // return_call_indirect (actual type index) ; We can use return_call_index here, or call_index. Semantically they are identical expressions.Add(ControlFlow.CallIndirect(_typeNode, 0)); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs index 911eb13d444db2..8302988c1faadc 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs @@ -34,8 +34,11 @@ public class WasmInterpreterToR2RThunkNode : StringDiscoverableAssemblyStubNode, public override string LookupString => "M" + _wasmSignature.SignatureString; - private static WasmSignature sigForInterpToR2RThunks = new WasmSignature(new WasmFuncType(new WasmResultType(new WasmValueType[]{WasmValueType.I32, WasmValueType.I32, WasmValueType.I32}), new WasmResultType(Array.Empty())), "viii"); - MethodSignature INodeWithTypeSignature.Signature => WasmLowering.RaiseSignature(sigForInterpToR2RThunks, _context); + private static readonly WasmSignature s_thunkSignature32 = new WasmSignature(new WasmFuncType(new([WasmValueType.I32, WasmValueType.I32, WasmValueType.I32]), new([])), "viii"); + private static readonly WasmSignature s_thunkSignature64 = new WasmSignature(new WasmFuncType(new([WasmValueType.I64, WasmValueType.I64, WasmValueType.I64]), new([])), "vlll"); + + private readonly WasmSignature _thunkSignature; + MethodSignature INodeWithTypeSignature.Signature => WasmLowering.RaiseSignature(_thunkSignature, _context); bool INodeWithTypeSignature.IsUnmanagedCallersOnly => false; bool INodeWithTypeSignature.IsAsyncCall => false; bool INodeWithTypeSignature.HasGenericContextArg => false; @@ -45,6 +48,7 @@ public WasmInterpreterToR2RThunkNode(NodeFactory factory, WasmSignature wasmSign _context = factory.TypeSystemContext; _wasmSignature = wasmSignature; _targetTypeNode = factory.WasmTypeNode(wasmSignature); + _thunkSignature = factory.Target.PointerSize == 8 ? s_thunkSignature64 : s_thunkSignature32; } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) @@ -73,12 +77,12 @@ protected override void ComputeNonRelocationBasedDependencies(DependencySink sin { base.ComputeNonRelocationBasedDependencies(sink, factory); sink.Add(_targetTypeNode, "Wasm interpreter-to-R2R thunk requires target type node"); - sink.Add(factory.WasmTypeNode(sigForInterpToR2RThunks), "Wasm interpreter-to-R2R thunk requires type for the function entry point"); + sink.Add(factory.WasmTypeNode(_thunkSignature), "Wasm interpreter-to-R2R thunk requires type for the function entry point"); } protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instructionEncoder, bool relocsOnly) { - Debug.Assert(!instructionEncoder.Is64Bit); + WasmTargetPtr ptr = instructionEncoder.Ptr; ISymbolNode targetTypeIndex = _targetTypeNode; @@ -91,15 +95,10 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr WasmFuncType targetFuncType = _targetTypeNode.Type; bool hasWasmReturn = targetFuncType.Returns.Types.Length > 0; - // Wasm locals for this thunk: - // local 0: portableEntryPoint (I32) - // local 1: pArgs (I32) - // local 2: pRet (I32) - // local 3: savedSp (I32) - save/restore SP global const int LocalPortableEntrypoint = 0; const int LocalPArgs = 1; const int LocalPRet = 2; - int localSavedSp = 3; + const int LocalSavedSp = 3; const int FrameSize = 16; // 16-byte aligned allocation for framePointer @@ -107,18 +106,18 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Save the current stack pointer global expressions.Add(Global.Get(WebCilObjectWriter.StackPointerGlobalIndex)); - expressions.Add(Local.Set(localSavedSp)); + expressions.Add(Local.Set(LocalSavedSp)); // Allocate frame space: sp -= FrameSize - expressions.Add(Local.Get(localSavedSp)); - expressions.Add(I32.Const(FrameSize)); - expressions.Add(I32.Sub); + expressions.Add(Local.Get(LocalSavedSp)); + expressions.Add(ptr.Const(FrameSize)); + expressions.Add(ptr.Sub); expressions.Add(Global.Set(WebCilObjectWriter.StackPointerGlobalIndex)); // Write TERMINATE_R2R_STACK_WALK (1) into the framePointer at new SP expressions.Add(Global.Get(WebCilObjectWriter.StackPointerGlobalIndex)); - expressions.Add(I32.Const(TerminateR2RStackWalk)); - expressions.Add(I32.Store(0)); + expressions.Add(ptr.Const(TerminateR2RStackWalk)); + expressions.Add(ptr.Store(0)); // If there is a wasm return value, push pRet underneath all the call args // so that after call_indirect the stack is [pRet, return_value] for the store. @@ -141,14 +140,14 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr } else if (arg.Kind == WasmThunkArgKind.AsyncContinuation) { - expressions.Add(I32.Const(0)); + expressions.Add(ptr.Const(0)); } else if (arg.IsIndirectStruct) { // Byreference struct — pass a pointer into the incoming pArgs buffer expressions.Add(Local.Get(LocalPArgs)); - expressions.Add(I32.Const(interpOffset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(interpOffset)); + expressions.Add(ptr.Add); } else { @@ -166,7 +165,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // call_indirect with the target R2R function's type signature expressions.Add(Local.Get(LocalPortableEntrypoint)); - expressions.Add(I32.Load(0)); // load the actual function index from the portable entrypoint + expressions.Add(ptr.Load(0)); // load the actual function index from the portable entrypoint expressions.Add(ControlFlow.CallIndirect(targetTypeIndex, 0)); // Handle wasm return value — pRet is already on the stack under the return value @@ -183,12 +182,12 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // pRet, and there is nothing more to do. // Restore the stack pointer global - expressions.Add(Local.Get(localSavedSp)); + expressions.Add(Local.Get(LocalSavedSp)); expressions.Add(Global.Set(WebCilObjectWriter.StackPointerGlobalIndex)); instructionEncoder.FunctionBody = new WasmFunctionBody( - sigForInterpToR2RThunks.FuncType, - new[] { WasmValueType.I32 }, + _thunkSignature.FuncType, + new[] { ptr.Type }, expressions.ToArray()); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs index 6af1ca4f4e2f07..efdc966be6a85d 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs @@ -28,16 +28,6 @@ public class WasmR2RToInterpreterThunkNode : StringDiscoverableAssemblyStubNode, private readonly WasmTypeNode _typeNode; private readonly Import _helperCell; - // Helper signature: (I32, I32, I32, I32) -> () - private static readonly CorInfoWasmType[] s_helperTypeParams = new CorInfoWasmType[] - { - CorInfoWasmType.CORINFO_WASM_TYPE_VOID, - CorInfoWasmType.CORINFO_WASM_TYPE_I32, - CorInfoWasmType.CORINFO_WASM_TYPE_I32, - CorInfoWasmType.CORINFO_WASM_TYPE_I32, - CorInfoWasmType.CORINFO_WASM_TYPE_I32, - }; - public override bool StaticDependenciesAreComputed => true; public override bool IsShareable => false; public override ObjectNodeSection GetSection(NodeFactory factory) => ObjectNodeSection.TextSection; @@ -89,18 +79,16 @@ protected override void ComputeNonRelocationBasedDependencies(DependencySink sin protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instructionEncoder, bool relocsOnly) { - Debug.Assert(!instructionEncoder.Is64Bit); - - ISymbolNode helperTypeIndex = factory.WasmTypeNode(s_helperTypeParams); + WasmTargetPtr ptr = instructionEncoder.Ptr; + CorInfoWasmType ptrType = ptr.CorInfoType; + ISymbolNode helperTypeIndex = factory.WasmTypeNode([CorInfoWasmType.CORINFO_WASM_TYPE_VOID, ptrType, ptrType, ptrType, ptrType]); WasmThunkArgLayout layout = new WasmThunkArgLayout(_wasmSignature, _context); int sizeOfArgumentArray = layout.SizeOfFrameArgumentArray; int sizeOfTransitionBlock = layout.TransitionBlock.SizeOfTransitionBlock; - // The arguments area must be 16-byte aligned. The TransitionBlock (8 bytes on Wasm32) - // sits before the arguments, so it is 8-byte aligned but not 16-byte aligned. - // Layout from base: [TransitionBlock (8)] [args...] + // Pad before the transition block to align the argument area to 16 bytes. int argumentsOffset = AlignmentHelper.AlignUp(sizeOfTransitionBlock, 16); int transitionBlockOffset = argumentsOffset - sizeOfTransitionBlock; int sizeOfStoredLocals = argumentsOffset + AlignmentHelper.AlignUp(sizeOfArgumentArray, 16); @@ -117,24 +105,22 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr List expressions = new List(); - // Allocate stack space: local.get 0; i32.const totalAlloc; i32.sub; local.set 0 + // Allocate stack space. expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(totalAlloc)); - expressions.Add(I32.Sub); + expressions.Add(ptr.Const(totalAlloc)); + expressions.Add(ptr.Sub); expressions.Add(Local.Set(0)); - // Initialize TransitionBlock: - // First 4 bytes (m_ReturnAddress) = 0 + // Initialize the transition block with a zero return address and the original SP. expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(0)); - expressions.Add(I32.Store((ulong)transitionBlockOffset)); + expressions.Add(ptr.Const(0)); + expressions.Add(ptr.Store((ulong)transitionBlockOffset)); - // Second 4 bytes (m_StackPointer) = original SP (local 0 + totalAlloc) expressions.Add(Local.Get(0)); expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(totalAlloc)); - expressions.Add(I32.Add); - expressions.Add(I32.Store((ulong)(transitionBlockOffset + 4))); + expressions.Add(ptr.Const(totalAlloc)); + expressions.Add(ptr.Add); + expressions.Add(ptr.Store((ulong)(transitionBlockOffset + ptr.Size))); // Store all arguments into the transition block area int? retBufParamIndex = null; @@ -162,12 +148,12 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // memory.copy: (dst, src, len) -> () // dst: base + currentOffset expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(currentOffset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(currentOffset)); + expressions.Add(ptr.Add); // src: the byref pointer passed as the wasm local expressions.Add(Local.Get(arg.WasmParamIndex)); // len: struct size - expressions.Add(I32.Const(structSize)); + expressions.Add(ptr.Const(structSize)); expressions.Add(Memory.Copy()); // Pad remaining bytes to alignment boundary with zeros @@ -177,10 +163,10 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr { // memory.fill: (dst, val, len) -> () expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(currentOffset + structSize)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(currentOffset + structSize)); + expressions.Add(ptr.Add); expressions.Add(I32.Const(0)); - expressions.Add(I32.Const(padding)); + expressions.Add(ptr.Const(padding)); expressions.Add(Memory.Fill()); } } @@ -207,10 +193,10 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr else { expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(localRetBufOffset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(localRetBufOffset)); + expressions.Add(ptr.Add); expressions.Add(I32.Const(0)); - expressions.Add(I32.Const(retBufSize)); + expressions.Add(ptr.Const(retBufSize)); expressions.Add(Memory.Fill()); } @@ -220,11 +206,11 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // arg2: pointer to the collected arguments and transition block (base + transitionBlockOffset) expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(transitionBlockOffset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(transitionBlockOffset)); + expressions.Add(ptr.Add); // arg3: size of arguments (excluding transition block) - expressions.Add(I32.Const(sizeOfArgumentArray)); + expressions.Add(ptr.Const(sizeOfArgumentArray)); // arg4: return buffer pointer if (retBufParamIndex is int retBufLocalIndex) @@ -236,8 +222,8 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr { // Pass pointer to local 8-byte return buffer expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(localRetBufOffset)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(localRetBufOffset)); + expressions.Add(ptr.Add); } // Extra local to save/restore the stack pointer global across the helper call @@ -252,7 +238,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Load the helper function address and call expressions.Add(Global.Get(WebCilObjectWriter.ImageBaseGlobalIndex)); - expressions.Add(I32.LoadWithRVAOffset(_helperCell)); + expressions.Add(ptr.LoadWithRVAOffset(_helperCell)); expressions.Add(ControlFlow.CallIndirect(helperTypeIndex, 0)); // The interpreter publishes its async continuation to the global itself @@ -270,7 +256,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr expressions.Add(Memory.Load(returnWasmType, (ulong)localRetBufOffset)); } - instructionEncoder.FunctionBody = new WasmFunctionBody(_typeNode.Type, new[] { WasmValueType.I32 }, expressions.ToArray()); + instructionEncoder.FunctionBody = new WasmFunctionBody(_typeNode.Type, new[] { ptr.Type }, expressions.ToArray()); } protected override void EmitCode(NodeFactory factory, ref X64.X64Emitter instructionEncoder, bool relocsOnly) { throw new NotSupportedException(); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs index b74fb61fbe5a94..d0cc7ad474599b 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs @@ -97,7 +97,7 @@ protected override void ComputeNonRelocationBasedDependencies(DependencySink sin protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructionEncoder, bool relocsOnly) { - Debug.Assert(!instructionEncoder.Is64Bit); + WasmTargetPtr ptr = instructionEncoder.Ptr; ReadOnlySpan parameters = _signature.FuncType.Params.Types; int portableEntryPointIndex = parameters.Length - 1; @@ -107,9 +107,9 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructio // The target PEP is stored immediately before this stub's PEP. expressions.Add(Local.Get(portableEntryPointIndex)); - expressions.Add(I32.Const(factory.Target.PointerSize)); - expressions.Add(I32.Sub); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Const(ptr.Size)); + expressions.Add(ptr.Sub); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Set(targetEntryPointLocalIndex)); AppendTargetCall( @@ -118,11 +118,11 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructio targetEntryPointLocalIndex, genericContext: _kind != UnboxingStubKind.Normal, hasReturnBuffer: _hasReturnBuffer, - pointerSize: factory.Target.PointerSize); + ptr); instructionEncoder.FunctionBody = new WasmFunctionBody( _signature.FuncType, - new[] { WasmValueType.I32 }, + new[] { ptr.Type }, expressions.ToArray()); } @@ -132,14 +132,14 @@ private void AppendTargetCall( int targetEntryPointLocalIndex, bool genericContext, bool hasReturnBuffer, - int pointerSize) + WasmTargetPtr ptr) { expressions.Add(Local.Get(0)); // Skip the MethodTable pointer at the start of the boxed object. expressions.Add(Local.Get(1)); - expressions.Add(I32.Const(pointerSize)); - expressions.Add(I32.Add); + expressions.Add(ptr.Const(ptr.Size)); + expressions.Add(ptr.Add); int firstExplicitArgumentIndex = 2; if (hasReturnBuffer) @@ -151,15 +151,15 @@ private void AppendTargetCall( if (genericContext && _kind == UnboxingStubKind.MethodTable) { expressions.Add(Local.Get(1)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); } else if (genericContext && _kind == UnboxingStubKind.MethodDesc) { // The target MethodDesc is stored two pointer-sized fields before this stub's PEP. expressions.Add(Local.Get(portableEntryPointIndex)); - expressions.Add(I32.Const(2 * pointerSize)); - expressions.Add(I32.Sub); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Const(2 * ptr.Size)); + expressions.Add(ptr.Sub); + expressions.Add(ptr.Load(0)); } for (int argumentIndex = firstExplicitArgumentIndex; argumentIndex < portableEntryPointIndex; argumentIndex++) @@ -169,7 +169,7 @@ private void AppendTargetCall( expressions.Add(Local.Get(targetEntryPointLocalIndex)); expressions.Add(Local.Get(targetEntryPointLocalIndex)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); expressions.Add(ControlFlow.CallIndirect(_targetType, 0)); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmVirtualDispatchThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmVirtualDispatchThunkNode.cs index a30faead66b764..2e026e834927a9 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmVirtualDispatchThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmVirtualDispatchThunkNode.cs @@ -73,8 +73,7 @@ protected override void ComputeNonRelocationBasedDependencies(DependencySink sin protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instructionEncoder, bool relocsOnly) { - Debug.Assert(!instructionEncoder.Is64Bit); - + WasmTargetPtr ptr = instructionEncoder.Ptr; MethodSignature methodSignature = WasmLowering.RaiseSignature(_wasmSignature, _context); Debug.Assert(!methodSignature.IsStatic); @@ -82,37 +81,37 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr int targetPortableEntrypointLocalIndex = _typeNode.Type.Params.Types.Length; int targetCodeLocalIndex = targetPortableEntrypointLocalIndex + 1; const int ThisLocalIndex = 1; - const ulong PackedDispatchOffsetsField = 4; - const ulong InitialEntryField = 8; + ulong packedDispatchOffsetsField = (ulong)ptr.Size; + ulong initialEntryField = 2 * packedDispatchOffsetsField; List expressions = new List(); // targetPEP = *(*(*(this) + pep->offsetOfIndirection) + pep->offsetAfterIndirection) expressions.Add(Local.Get(ThisLocalIndex)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Get(portableEntrypointLocalIndex)); - expressions.Add(I32.Load16_u(PackedDispatchOffsetsField)); - expressions.Add(I32.Add); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load16_u(packedDispatchOffsetsField)); + expressions.Add(ptr.Add); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Get(portableEntrypointLocalIndex)); - expressions.Add(I32.Load16_u(PackedDispatchOffsetsField + sizeof(ushort))); - expressions.Add(I32.Add); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load16_u(packedDispatchOffsetsField + sizeof(ushort))); + expressions.Add(ptr.Add); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Set(targetPortableEntrypointLocalIndex)); expressions.Add(Local.Get(targetPortableEntrypointLocalIndex)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Set(targetCodeLocalIndex)); // Redispatch through the original entrypoint if this receiver's target is not yet callable from R2R. expressions.Add(Local.Get(targetCodeLocalIndex)); - expressions.Add(I32.Eqz); + expressions.Add(ptr.Eqz); expressions.Add(Block.If(WasmBlockType.Empty)); expressions.Add(Local.Get(portableEntrypointLocalIndex)); - expressions.Add(I32.Load(InitialEntryField)); + expressions.Add(ptr.Load(initialEntryField)); expressions.Add(Local.Set(targetPortableEntrypointLocalIndex)); expressions.Add(Local.Get(targetPortableEntrypointLocalIndex)); - expressions.Add(I32.Load(0)); + expressions.Add(ptr.Load(0)); expressions.Add(Local.Set(targetCodeLocalIndex)); expressions.Add(Block.End); @@ -126,7 +125,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr instructionEncoder.FunctionBody = new WasmFunctionBody( _typeNode.Type, - new[] { WasmValueType.I32, WasmValueType.I32 }, + new[] { ptr.Type, ptr.Type }, expressions.ToArray()); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs index 3f294d76a9a6e0..f7c295d49038a3 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -157,7 +157,7 @@ private bool CanPrecompileUnboxingStub(MethodDesc targetMethod) // The IL implementation of the generic unboxing thunk does not support a MethodDesc // generic context. Wasm uses a generated assembly stub for this case instead. - if (targetMethod.RequiresInstMethodDescArg() && Target.Architecture != TargetArchitecture.Wasm32) + if (targetMethod.RequiresInstMethodDescArg() && !Target.IsWasm) return false; // TODO See comment in UnboxingThunk.EmitIL @@ -185,7 +185,7 @@ public DependencyNodeCore UnboxingStub(MethodDesc targetMethod) { Debug.Assert(NeedsUnboxingStub(targetMethod)); - if (Target.Architecture == TargetArchitecture.Wasm32) + if (Target.IsWasm) { return _wasmUnboxingStubTargets.GetOrAdd(targetMethod); } @@ -1265,7 +1265,7 @@ public void AttachToDependencyGraph(DependencyAnalyzerBase graph, I // as a dependency of any StringDiscoverableAssemblyStubNode that gets marked. InjectStringThunksImport = new Import(EagerImports, new InjectStringThunksSignature()); - if ((Target.Architecture != TargetArchitecture.X86) && (Target.Architecture != TargetArchitecture.Wasm32)) + if (Target.Architecture != TargetArchitecture.X86 && !Target.IsWasm) { Import personalityRoutineImport = new Import(EagerImports, new ReadyToRunHelperSignature( ReadyToRunHelper.PersonalityRoutine)); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs index 437db7fa2260ca..5c37c6c6d983be 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs @@ -391,7 +391,7 @@ public override ICompilation ToCompilation() bool deferredWasmCalls = false; if (_enableDeferredWasmCalls && - _context.Target.Architecture == TargetArchitecture.Wasm32 && _optimizationMode != OptimizationMode.None) + _context.Target.IsWasm && _optimizationMode != OptimizationMode.None) { foreach (EcmaModule compilationModule in inputModules) { diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCompilerContext.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCompilerContext.cs index 38966c50524e40..08e013d30c96f8 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCompilerContext.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCompilerContext.cs @@ -312,7 +312,7 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType type, ByteCountUnaligned = layoutFromSimilarIntrinsicVector.ByteCountUnaligned, ByteCountAlignment = layoutFromMetadata.ByteCountAlignment, // On wasm Vector is passed as a v128 and must share its 16-byte alignment. - FieldAlignment = type.Context.Target.Architecture == TargetArchitecture.Wasm32 + FieldAlignment = type.Context.Target.IsWasm ? layoutFromSimilarIntrinsicVector.FieldAlignment : layoutFromMetadata.FieldAlignment, FieldSize = layoutFromSimilarIntrinsicVector.FieldSize, diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs index 145f0cc1a898ba..3c31962cc5dd10 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs @@ -259,7 +259,7 @@ public override MethodIL GetMethodIL(MethodDesc method) if (asyncTargetMethodIL == null) return null; - return new AsyncMethodIL(amv, asyncTargetMethodIL); + return AsyncMethodIL.Create(amv, asyncTargetMethodIL); } else if (method is MethodForInstantiatedType || method is InstantiatedMethod) { @@ -395,28 +395,5 @@ public override object GetObject(int token, NotFoundBehavior notFoundBehavior = return _mutableModule.GetObject(System.Reflection.Metadata.Ecma335.MetadataTokens.EntityHandle(token), notFoundBehavior); } } - - public sealed class AsyncMethodIL : MethodIL, IEcmaMethodIL - { - private readonly AsyncMethodVariant _variant; - private readonly MethodIL _methodIL; - - public AsyncMethodIL(AsyncMethodVariant variant, MethodIL methodIL) - => (_variant, _methodIL) = (variant, methodIL); - - // This is the reason we need this class - the method that owns the IL is the variant. - public override MethodDesc OwningMethod => _variant; - - // Everything else dispatches to the wrapped IL - public override MethodDebugInformation GetDebugInfo() => _methodIL.GetDebugInfo(); - public override ILExceptionRegion[] GetExceptionRegions() => _methodIL.GetExceptionRegions(); - public override byte[] GetILBytes() => _methodIL.GetILBytes(); - public override LocalVariableDefinition[] GetLocals() => _methodIL.GetLocals(); - public override object GetObject(int token, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw) => _methodIL.GetObject(token, notFoundBehavior); - public override bool IsInitLocals => _methodIL.IsInitLocals; - public override int MaxStack => _methodIL.MaxStack; - - public IEcmaModule Module => ((EcmaType)(_variant.OwningType)).Module; - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj index 3ebc0a71be1cba..0323fd1062aefe 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj @@ -49,6 +49,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 7d6bd89fd29136..2ea8ad47419e50 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -3568,7 +3568,7 @@ partial void TryGetWasmMethodVirtualIPRelocation( return; } - if (fRelocType != CorInfoReloc.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32) + if (fRelocType is not (CorInfoReloc.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32 or CorInfoReloc.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64)) return; Debug.Assert(locationBlock is BlockType.ROData or BlockType.RWData); @@ -3579,7 +3579,9 @@ partial void TryGetWasmMethodVirtualIPRelocation( Debug.Assert(dataBlobNode is not null); relocTarget = _compilation.NodeFactory.WasmMethodRelativeVirtualIP(_methodCodeNode); - relocType = RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32; + relocType = fRelocType == CorInfoReloc.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64 + ? RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I64 + : RelocType.WASM_METHOD_RELATIVE_VIRTUAL_IP_I32; _wasmMethodVirtualIPFixups ??= new(); _wasmMethodVirtualIPFixups.Add((dataBlobNode, relocOffset)); @@ -3917,7 +3919,7 @@ inlineeModule is not null && // of the build finishes, it will then compute the IL bodies for those methods, then run the compilation again. if (needsTokenTranslation && !(methodIL is IMethodTokensAreUseableInCompilation) - && (methodIL is EcmaMethodIL || methodIL is ReadyToRunILProvider.AsyncMethodIL)) + && methodIL is IEcmaMethodIL) { // We may have already acquired the right type of MethodIL here, or be working with a method that is an IL Intrinsic. // Add the typicalMethod (which may be an AsyncMethodVariant) so that @@ -4159,12 +4161,13 @@ private void recordWasmManagedCallSig(CORINFO_SIG_INFO* callSig) // The adapter accepts the managed instance shape // (sp, this, retbuf, ..., pep). Require an indirect aggregate return, // no async-continuation argument, and pointer-typed this/retbuf positions. + WasmValueType pointerType = _compilation.NodeFactory.Target.PointerSize == 8 ? WasmValueType.I64 : WasmValueType.I32; if (!sig.IsStatic && wasmSig.SignatureString[0] == 'S' && !wasmSig.SignatureString.Contains('a') && parameters.Length >= 4 && - parameters[1] == WasmValueType.I32 && - parameters[2] == WasmValueType.I32) + parameters[1] == pointerType && + parameters[2] == pointerType) { AddWasmClosedStaticRetBufThunkDependencies(wasmSig); } diff --git a/src/coreclr/tools/aot/crossgen2/Program.cs b/src/coreclr/tools/aot/crossgen2/Program.cs index af73badccf9791..cb828db9569d22 100644 --- a/src/coreclr/tools/aot/crossgen2/Program.cs +++ b/src/coreclr/tools/aot/crossgen2/Program.cs @@ -88,7 +88,8 @@ public int Run() { throw new CommandLineException(SR.GeneratePortableCallHelpersRequiresWasmTarget); } - if (targetArchitecture == TargetArchitecture.Wasm64 && _generatePortableCallHelpers is null) + if (targetArchitecture == TargetArchitecture.Wasm64 && _generatePortableCallHelpers is null && + (targetOS != TargetOS.Browser || Get(_command.OutputFormat) != ReadyToRunContainerFormat.Wasm)) { throw new CommandLineException(SR.Wasm64ReadyToRunUnsupported); } diff --git a/src/coreclr/tools/aot/crossgen2/Properties/Resources.resx b/src/coreclr/tools/aot/crossgen2/Properties/Resources.resx index 2e214a21b8884d..59876a00f070e2 100644 --- a/src/coreclr/tools/aot/crossgen2/Properties/Resources.resx +++ b/src/coreclr/tools/aot/crossgen2/Properties/Resources.resx @@ -304,7 +304,7 @@ --generate-portable-callhelpers requires --targetarch wasm with --targetos browser or wasi, or --targetarch wasm64 with --targetos browser - ReadyToRun compilation is not supported for wasm64. Use --generate-portable-callhelpers to generate interpreter call helpers. + ReadyToRun compilation for wasm64 is limited to browser Wasm output. Specify --targetos browser --obj-format wasm, or use --generate-portable-callhelpers to generate interpreter call helpers. Target OS is not supported diff --git a/src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp b/src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp index b4630296e7b81f..62a73f7e7b8acd 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp @@ -732,7 +732,7 @@ void CompileResult::applyRelocs(RelocContext* rc, unsigned char* block1, ULONG b // so byte-by-byte comparison naturally succeeds at reloc sites without any // patching here. The near-differ validates reloc-target equivalence via // `compareOffsetsWasm` when the surrounding immediate bytes happen to differ. - if (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_WASM32) + if (IsSpmiTargetWasm()) return; size_t section_begin = (size_t)block1; diff --git a/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp index a42d8245b012ba..c7c956ac0802f6 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp @@ -252,6 +252,8 @@ static SPMI_TARGET_ARCHITECTURE SpmiTargetArchitecture = SPMI_TARGET_ARCHITECTUR static SPMI_TARGET_ARCHITECTURE SpmiTargetArchitecture = SPMI_TARGET_ARCHITECTURE_RISCV64; #elif defined(TARGET_WASM) static SPMI_TARGET_ARCHITECTURE SpmiTargetArchitecture = SPMI_TARGET_ARCHITECTURE_WASM32; +#elif defined(TARGET_WASM64) +static SPMI_TARGET_ARCHITECTURE SpmiTargetArchitecture = SPMI_TARGET_ARCHITECTURE_WASM64; #else #error Unsupported architecture #endif diff --git a/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h index 232eaa8a04861b..d684bd3097ae87 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h @@ -65,6 +65,7 @@ enum SPMI_TARGET_ARCHITECTURE SPMI_TARGET_ARCHITECTURE_LOONGARCH64, SPMI_TARGET_ARCHITECTURE_RISCV64, SPMI_TARGET_ARCHITECTURE_WASM32, + SPMI_TARGET_ARCHITECTURE_WASM64, }; SPMI_TARGET_ARCHITECTURE GetSpmiTargetArchitecture(); @@ -82,7 +83,14 @@ inline bool IsSpmiTarget64Bit() return (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_AMD64) || (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_ARM64) || (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_LOONGARCH64) || - (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_RISCV64); + (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_RISCV64) || + (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_WASM64); +} + +inline bool IsSpmiTargetWasm() +{ + return (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_WASM32) || + (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_WASM64); } inline size_t SpmiTargetPointerSize() diff --git a/src/coreclr/tools/superpmi/superpmi/commandline.cpp b/src/coreclr/tools/superpmi/superpmi/commandline.cpp index cf27a6b186e51e..86614b097c6fd2 100644 --- a/src/coreclr/tools/superpmi/superpmi/commandline.cpp +++ b/src/coreclr/tools/superpmi/superpmi/commandline.cpp @@ -128,7 +128,7 @@ void CommandLine::DumpHelp(const char* program) printf("\n"); printf(" -target \n"); printf(" Specifies the target architecture if doing cross-compilation.\n"); - printf(" Allowed values: x64, x86, arm, arm64, loongarch64, riscv64, wasm\n"); + printf(" Allowed values: x64, x86, arm, arm64, loongarch64, riscv64, wasm, wasm64\n"); printf(" Used by the assembly differences calculator; to determine a default JIT dll name;\n"); printf(" and to avoid treating mismatched cross-compilation replay as failure.\n"); printf("\n"); @@ -691,7 +691,8 @@ bool CommandLine::Parse(int argc, char* argv[], /* OUT */ Options* o) (0 != _stricmp(o->targetArchitecture, "loongarch64")) && (0 != _stricmp(o->targetArchitecture, "riscv64")) && (0 != _stricmp(o->targetArchitecture, "wasm")) && - (0 != _stricmp(o->targetArchitecture, "wasm32"))) + (0 != _stricmp(o->targetArchitecture, "wasm32")) && + (0 != _stricmp(o->targetArchitecture, "wasm64"))) { LogError("Illegal target architecture specified with -target."); DumpHelp(argv[0]); diff --git a/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp b/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp index fa24e9ca646d48..1f26290ccd0559 100644 --- a/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp +++ b/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp @@ -316,6 +316,10 @@ ReplayResults JitInstance::CompileMethod(MethodContext* MethodToCompile, int mcI matchesTargetArch = (targetArch == SPMI_TARGET_ARCHITECTURE_WASM32); break; + case CORINFO_ARCH_WASM64: + matchesTargetArch = (targetArch == SPMI_TARGET_ARCHITECTURE_WASM64); + break; + default: LogError("Unknown target architecture"); break; diff --git a/src/coreclr/tools/superpmi/superpmi/neardiffer.cpp b/src/coreclr/tools/superpmi/superpmi/neardiffer.cpp index 9bb7f913393056..4d9a155438c36b 100644 --- a/src/coreclr/tools/superpmi/superpmi/neardiffer.cpp +++ b/src/coreclr/tools/superpmi/superpmi/neardiffer.cpp @@ -552,12 +552,12 @@ bool NearDiffer::compareOffsets( return true; } - // For wasm32, recorded relocations are the source of truth: handles materialize - // as i32.const immediates with padded ULEB128/SLEB128 placeholders that the JIT + // For Wasm, recorded relocations are the source of truth: handles materialize + // as i32.const/i64.const immediates with padded ULEB128/SLEB128 placeholders that the JIT // separately records in a reloc table. Defer the "are these two distinct // immediates semantically equivalent" decision to a wasm-specific path that // consults the reloc tables instead of replaying generic IP-relative heuristics. - if (GetSpmiTargetArchitecture() == SPMI_TARGET_ARCHITECTURE_WASM32) + if (IsSpmiTargetWasm()) { return compareOffsetsWasm(payload, blockOffset, instrLen, offset1, offset2); } diff --git a/src/coreclr/tools/superpmi/superpmi/superpmi.cpp b/src/coreclr/tools/superpmi/superpmi/superpmi.cpp index 7eecc7d2ec4e16..859a61cb44c739 100644 --- a/src/coreclr/tools/superpmi/superpmi/superpmi.cpp +++ b/src/coreclr/tools/superpmi/superpmi/superpmi.cpp @@ -66,6 +66,10 @@ void SetSuperPmiTargetArchitecture(const char* targetArchitecture) { SetSpmiTargetArchitecture(SPMI_TARGET_ARCHITECTURE_WASM32); } + else if (0 == _stricmp(targetArchitecture, "wasm64")) + { + SetSpmiTargetArchitecture(SPMI_TARGET_ARCHITECTURE_WASM64); + } else { LogError("Illegal target architecture '%s'", targetArchitecture); diff --git a/src/coreclr/vm/codeman.cpp b/src/coreclr/vm/codeman.cpp index 89164f0335416d..eba08a551624b4 100644 --- a/src/coreclr/vm/codeman.cpp +++ b/src/coreclr/vm/codeman.cpp @@ -6196,7 +6196,7 @@ void ExecutionManager::Unload(LoaderAllocator *pLoaderAllocator) #endif // FEATURE_INTERPRETER } -#ifdef HOST_64BIT +#if defined(HOST_64BIT) && !defined(TARGET_WASMARCH) // This method is used by the JIT and the runtime for PreStubs. It will return // the address of a short jump thunk that will jump to the 'target' address. // It is only needed when the target architecture has a perferred call instruction @@ -6442,11 +6442,7 @@ PCODE ExecutionManager::getNextJumpStub(MethodDesc* pMD, PCODE target, _ASSERTE(((UINT_PTR)jumpStub & 7) == 0); #endif -#ifdef TARGET_WASM64 - UNREACHABLE_MSG("Wasm64 does not use native jump stubs"); -#else emitBackToBackJump(jumpStub, jumpStubRW, (void*) target); -#endif PerfMap::LogStubs(__FUNCTION__, "emitBackToBackJump", (PCODE)jumpStub, BACK_TO_BACK_JUMP_ALLOCATE_SIZE, PerfMapStubType::IndividualWithinBlock); @@ -6511,7 +6507,7 @@ PCODE ExecutionManager::getNextJumpStub(MethodDesc* pMD, PCODE target, return (PCODE)jumpStub; } -#endif // HOST_64BIT +#endif // HOST_64BIT && !TARGET_WASMARCH #endif // !DACCESS_COMPILE static void GetFuncletStartOffsetsHelper(PCODE pCodeStart, SIZE_T size, SIZE_T ofsAdj, diff --git a/src/coreclr/vm/codeman.h b/src/coreclr/vm/codeman.h index b44206138e7a3b..bc10b714832cd7 100644 --- a/src/coreclr/vm/codeman.h +++ b/src/coreclr/vm/codeman.h @@ -2632,14 +2632,14 @@ class ExecutionManager static void EnumMemoryRegions(CLRDataEnumMemoryFlags flags); #endif -#if !defined(DACCESS_COMPILE) && defined(HOST_64BIT) +#if !defined(DACCESS_COMPILE) && defined(HOST_64BIT) && !defined(TARGET_WASMARCH) // Returns NULL if no jump stub can be allocated within the requested range. static PCODE jumpStub(MethodDesc* pMD, PCODE target, BYTE * loAddr, BYTE * hiAddr, LoaderAllocator *pLoaderAllocator = NULL); -#endif // !defined(DACCESS_COMPILE) && defined(HOST_64BIT) +#endif // !defined(DACCESS_COMPILE) && defined(HOST_64BIT) && !defined(TARGET_WASMARCH) private: static RangeSection * FindCodeRangeWithLock(PCODE currentPC); @@ -2708,12 +2708,12 @@ class ExecutionManager } #endif // defined(_DEBUG) -#if !defined(DACCESS_COMPILE) && defined(HOST_64BIT) +#if !defined(DACCESS_COMPILE) && defined(HOST_64BIT) && !defined(TARGET_WASMARCH) static PCODE getNextJumpStub(MethodDesc* pMD, PCODE target, BYTE * loAddr, BYTE * hiAddr, LoaderAllocator *pLoaderAllocator); -#endif // !defined(DACCESS_COMPILE) && defined(HOST_64BIT) +#endif // !defined(DACCESS_COMPILE) && defined(HOST_64BIT) && !defined(TARGET_WASMARCH) private: // *************************************************************************** diff --git a/src/coreclr/vm/corelib.h b/src/coreclr/vm/corelib.h index 35ae863cbf5d84..4a67e1f8075b84 100644 --- a/src/coreclr/vm/corelib.h +++ b/src/coreclr/vm/corelib.h @@ -258,9 +258,9 @@ DEFINE_METHOD(MATH, CONVERT_TO_UINT32_CHECKED, ConvertToUInt32 DEFINE_METHOD(MATH, CONVERT_TO_INT64_CHECKED, ConvertToInt64Checked, NoSig) DEFINE_METHOD(MATH, CONVERT_TO_UINT64_CHECKED, ConvertToUInt64Checked, NoSig) -#ifdef TARGET_32BIT DEFINE_METHOD(MATH, MULTIPLY_CHECKED_INT64, MultiplyChecked, SM_Long_Long_RetLong) DEFINE_METHOD(MATH, MULTIPLY_CHECKED_UINT64, MultiplyChecked, SM_ULong_ULong_RetULong) +#ifdef TARGET_32BIT DEFINE_METHOD(MATH, DIV_INT32, DivInt32, NoSig) DEFINE_METHOD(MATH, DIV_UINT32, DivUInt32, NoSig) DEFINE_METHOD(MATH, DIV_INT64, DivInt64, NoSig) diff --git a/src/coreclr/vm/jitinterface.cpp b/src/coreclr/vm/jitinterface.cpp index b244090e8d0aa7..2cb3bf75c43f5c 100644 --- a/src/coreclr/vm/jitinterface.cpp +++ b/src/coreclr/vm/jitinterface.cpp @@ -15469,6 +15469,8 @@ uint32_t CEEInfo::getExpectedTargetArchitecture() return CORINFO_ARCH_RISCV64; #elif defined(TARGET_WASM) return CORINFO_ARCH_WASM32; +#elif defined(TARGET_WASM64) + return CORINFO_ARCH_WASM64; #else PORTABILITY_ASSERT("NYI: CEEInfo::getExpectedTargetArchitecture"); return -1; diff --git a/src/installer/pkg/sfx/Microsoft.NETCore.App/Microsoft.NETCore.App.Runtime.CoreCLR.sfxproj b/src/installer/pkg/sfx/Microsoft.NETCore.App/Microsoft.NETCore.App.Runtime.CoreCLR.sfxproj index 141b6ae7df2f3d..9216d198c7023e 100644 --- a/src/installer/pkg/sfx/Microsoft.NETCore.App/Microsoft.NETCore.App.Runtime.CoreCLR.sfxproj +++ b/src/installer/pkg/sfx/Microsoft.NETCore.App/Microsoft.NETCore.App.Runtime.CoreCLR.sfxproj @@ -34,7 +34,7 @@ true false - false + false false true true diff --git a/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.ReadyToRun.InBuild.targets b/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.ReadyToRun.InBuild.targets index b200e8a3e7c2ea..e34b3d36391f26 100644 --- a/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.ReadyToRun.InBuild.targets +++ b/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.ReadyToRun.InBuild.targets @@ -31,6 +31,7 @@ Copyright (c) .NET Foundation. All rights reserved. <_WasmR2RTargetOS Condition="'$(TargetOS)' != ''">$(TargetOS) <_WasmR2RTargetOS Condition="'$(_WasmR2RTargetOS)' == ''">browser <_WasmR2RTargetArch Condition="'$(TargetArchitecture)' != ''">$(TargetArchitecture) + <_WasmR2RTargetArch Condition="'$(RuntimeIdentifier)' == 'browser-wasm64'">wasm64 <_WasmR2RTargetArch Condition="'$(_WasmR2RTargetArch)' == ''">wasm diff --git a/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.targets b/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.targets index e30ef1ac3207c6..a50ec462498ba4 100644 --- a/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.targets +++ b/src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.CoreCLR.targets @@ -11,17 +11,6 @@ Copyright (c) .NET Foundation. All rights reserved. --> - - - false - - - - - - @@ -323,7 +312,7 @@ Copyright (c) .NET Foundation. All rights reserved. <_ReadyToRunCompilerInputs Include="$(_WasmReadyToRunStateFile);@(_ReadyToRunCompileList);@(_ReadyToRunAssembliesToReference);@(_ReadyToRunCompositeBuildReferences);@(_ReadyToRunCompositeUnrootedBuildInput)" /> - <_ReadyToRunCompilerInputs Include="$(_WasmResolvedCrossgen2Dir)crossgen2*;$(_WasmResolvedCrossgen2Dir)clrjit_universal_wasm_*" + <_ReadyToRunCompilerInputs Include="$(_WasmResolvedCrossgen2Dir)crossgen2*;$(_WasmResolvedCrossgen2Dir)*clrjit_universal_$(_WasmR2RTargetArch)_*" Condition="'$(_WasmResolvedCrossgen2Dir)' != ''" /> diff --git a/src/tests/Common/CLRTest.CrossGen.targets b/src/tests/Common/CLRTest.CrossGen.targets index 357b5e81ecccb1..a96471e565abff 100644 --- a/src/tests/Common/CLRTest.CrossGen.targets +++ b/src/tests/Common/CLRTest.CrossGen.targets @@ -175,7 +175,7 @@ if [ ! -z ${RunCrossGen2+x} ]%3B then fi if [ ! -z ${CrossGen2SynthesizePgo+x} ]%3B then echo --synthesize-random-mibc >> "$__ResponseFile" - if [ "$(TargetArchitecture)" != "wasm" ]; then + if [ "$(TargetArchitecture)" != "wasm" ] && [ "$(TargetArchitecture)" != "wasm64" ]; then echo --embed-pgo-data >> "$__ResponseFile" fi fi @@ -458,7 +458,7 @@ if defined RunCrossGen2 ( ) if defined CrossGen2SynthesizePgo ( echo --synthesize-random-mibc>>!__ResponseFile! - if not "$(TargetArchitecture)"=="wasm" ( + if not "$(CrossGen2OutputFormat)"=="wasm" ( echo --embed-pgo-data>>!__ResponseFile! ) ) diff --git a/src/tests/Directory.Build.targets b/src/tests/Directory.Build.targets index 74fea177534cf6..fbbdd1c33361a0 100644 --- a/src/tests/Directory.Build.targets +++ b/src/tests/Directory.Build.targets @@ -90,11 +90,6 @@ true - - - true - - false diff --git a/src/tests/readytorun/async-inline-thunks/async-inline-thunks.csproj b/src/tests/readytorun/async-inline-thunks/async-inline-thunks.csproj index c472c2df9b2452..2dc0d939934aa8 100644 --- a/src/tests/readytorun/async-inline-thunks/async-inline-thunks.csproj +++ b/src/tests/readytorun/async-inline-thunks/async-inline-thunks.csproj @@ -7,7 +7,7 @@ $(Features);runtime-async=on true - true + true diff --git a/src/tests/readytorun/determinism/crossgen2determinism.csproj b/src/tests/readytorun/determinism/crossgen2determinism.csproj index ce045528f12a69..c99c230d80a7b1 100644 --- a/src/tests/readytorun/determinism/crossgen2determinism.csproj +++ b/src/tests/readytorun/determinism/crossgen2determinism.csproj @@ -2,7 +2,7 @@ true - true + true true diff --git a/src/tests/readytorun/ilbody-implflags-versioning/ilbody-implflags-versioning.csproj b/src/tests/readytorun/ilbody-implflags-versioning/ilbody-implflags-versioning.csproj index ccd9dc8283bf08..ce5c0b20bce8e3 100644 --- a/src/tests/readytorun/ilbody-implflags-versioning/ilbody-implflags-versioning.csproj +++ b/src/tests/readytorun/ilbody-implflags-versioning/ilbody-implflags-versioning.csproj @@ -7,7 +7,7 @@ $(Features);runtime-async=on true - true + true diff --git a/src/tests/readytorun/tests/coldsignaturedispatch.csproj b/src/tests/readytorun/tests/coldsignaturedispatch.csproj index 292ccc1c802062..f84d3b30df0f45 100644 --- a/src/tests/readytorun/tests/coldsignaturedispatch.csproj +++ b/src/tests/readytorun/tests/coldsignaturedispatch.csproj @@ -4,7 +4,7 @@ 1 true - true + true --verify-type-and-field-layout:false diff --git a/src/tests/readytorun/tests/mainv1.csproj b/src/tests/readytorun/tests/mainv1.csproj index 2aa1311fc76e24..54ae8b9684764c 100644 --- a/src/tests/readytorun/tests/mainv1.csproj +++ b/src/tests/readytorun/tests/mainv1.csproj @@ -7,7 +7,7 @@ true true - true + true diff --git a/src/tests/readytorun/tests/mainv2.csproj b/src/tests/readytorun/tests/mainv2.csproj index cbff9e03efb8c9..dc08c633d08e1b 100644 --- a/src/tests/readytorun/tests/mainv2.csproj +++ b/src/tests/readytorun/tests/mainv2.csproj @@ -7,7 +7,7 @@ true true - true + true diff --git a/src/tests/readytorun/tests/mainv3.csproj b/src/tests/readytorun/tests/mainv3.csproj index 487aecda28da3a..066ceaa89ee075 100644 --- a/src/tests/readytorun/tests/mainv3.csproj +++ b/src/tests/readytorun/tests/mainv3.csproj @@ -11,7 +11,7 @@ $(DefineConstants);NO_CROSS_MODULE_INLINING;TEST_DECLARING_TYPE_HANDLE true - true + true diff --git a/src/tests/readytorun/tests/methodtokenmissingsignature.csproj b/src/tests/readytorun/tests/methodtokenmissingsignature.csproj index 534c23c9e4c8e7..eac6d2cbf273de 100644 --- a/src/tests/readytorun/tests/methodtokenmissingsignature.csproj +++ b/src/tests/readytorun/tests/methodtokenmissingsignature.csproj @@ -3,7 +3,7 @@ true 1 - true + true