Skip to content

Commit 9637e4e

Browse files
hoodmanemahesh-attarde
authored andcommitted
[WebAssembly,clang] Add __builtin_wasm_test_function_pointer_signature (llvm#150201)
Tests if the runtime type of the function pointer matches the static type. If this returns false, calling the function pointer will trap. Uses `@llvm.wasm.ref.test.func` added in llvm#147486. Also adds a "gc" wasm feature to gate the use of the ref.test instruction.
1 parent 38ef127 commit 9637e4e

File tree

17 files changed

+219
-23
lines changed

17 files changed

+219
-23
lines changed

clang/include/clang/Basic/BuiltinsWebAssembly.def

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,12 @@ TARGET_BUILTIN(__builtin_wasm_ref_is_null_extern, "ii", "nct", "reference-types"
199199
// return type.
200200
TARGET_BUILTIN(__builtin_wasm_ref_null_func, "i", "nct", "reference-types")
201201

202+
// Check if the runtime type of a function pointer matches its static type. Used
203+
// to avoid "function signature mismatch" traps. Takes a function pointer, uses
204+
// table.get to look up the pointer in __indirect_function_table and then
205+
// ref.test to test the type.
206+
TARGET_BUILTIN(__builtin_wasm_test_function_pointer_signature, "i.", "nct", "gc")
207+
202208
// Table builtins
203209
TARGET_BUILTIN(__builtin_wasm_table_set, "viii", "t", "reference-types")
204210
TARGET_BUILTIN(__builtin_wasm_table_get, "iii", "t", "reference-types")

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7575,6 +7575,8 @@ def err_typecheck_illegal_increment_decrement : Error<
75757575
"cannot %select{decrement|increment}1 value of type %0">;
75767576
def err_typecheck_expect_int : Error<
75777577
"used type %0 where integer is required">;
7578+
def err_typecheck_expect_function_pointer
7579+
: Error<"used type %0 where function pointer is required">;
75787580
def err_typecheck_expect_hlsl_resource : Error<
75797581
"used type %0 where __hlsl_resource_t is required">;
75807582
def err_typecheck_arithmetic_incomplete_or_sizeless_type : Error<
@@ -13202,6 +13204,10 @@ def err_wasm_builtin_arg_must_match_table_element_type : Error <
1320213204
"%ordinal0 argument must match the element type of the WebAssembly table in the %ordinal1 argument">;
1320313205
def err_wasm_builtin_arg_must_be_integer_type : Error <
1320413206
"%ordinal0 argument must be an integer">;
13207+
def err_wasm_builtin_test_fp_sig_cannot_include_reference_type
13208+
: Error<"not supported for "
13209+
"function pointers with a reference type %select{return "
13210+
"value|parameter}0">;
1320513211

1320613212
// OpenACC diagnostics.
1320713213
def warn_acc_routine_unimplemented

clang/include/clang/Sema/SemaWasm.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class SemaWasm : public SemaBase {
3737
bool BuiltinWasmTableGrow(CallExpr *TheCall);
3838
bool BuiltinWasmTableFill(CallExpr *TheCall);
3939
bool BuiltinWasmTableCopy(CallExpr *TheCall);
40+
bool BuiltinWasmTestFunctionPointerSignature(CallExpr *TheCall);
4041

4142
WebAssemblyImportNameAttr *
4243
mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL);

clang/lib/Basic/Targets/WebAssembly.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ bool WebAssemblyTargetInfo::hasFeature(StringRef Feature) const {
6464
.Case("mutable-globals", HasMutableGlobals)
6565
.Case("nontrapping-fptoint", HasNontrappingFPToInt)
6666
.Case("reference-types", HasReferenceTypes)
67+
.Case("gc", HasGC)
6768
.Case("relaxed-simd", SIMDLevel >= RelaxedSIMD)
6869
.Case("sign-ext", HasSignExt)
6970
.Case("simd128", SIMDLevel >= SIMD128)
@@ -106,6 +107,8 @@ void WebAssemblyTargetInfo::getTargetDefines(const LangOptions &Opts,
106107
Builder.defineMacro("__wasm_nontrapping_fptoint__");
107108
if (HasReferenceTypes)
108109
Builder.defineMacro("__wasm_reference_types__");
110+
if (HasGC)
111+
Builder.defineMacro("__wasm_gc__");
109112
if (SIMDLevel >= RelaxedSIMD)
110113
Builder.defineMacro("__wasm_relaxed_simd__");
111114
if (HasSignExt)
@@ -307,6 +310,14 @@ bool WebAssemblyTargetInfo::handleTargetFeatures(
307310
HasReferenceTypes = false;
308311
continue;
309312
}
313+
if (Feature == "+gc") {
314+
HasGC = true;
315+
continue;
316+
}
317+
if (Feature == "-gc") {
318+
HasGC = false;
319+
continue;
320+
}
310321
if (Feature == "+relaxed-simd") {
311322
SIMDLevel = std::max(SIMDLevel, RelaxedSIMD);
312323
continue;
@@ -353,6 +364,11 @@ bool WebAssemblyTargetInfo::handleTargetFeatures(
353364
return false;
354365
}
355366

367+
// gc implies reference-types
368+
if (HasGC) {
369+
HasReferenceTypes = true;
370+
}
371+
356372
// bulk-memory-opt is a subset of bulk-memory.
357373
if (HasBulkMemory) {
358374
HasBulkMemoryOpt = true;

clang/lib/Basic/Targets/WebAssembly.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class LLVM_LIBRARY_VISIBILITY WebAssemblyTargetInfo : public TargetInfo {
6969
bool HasMutableGlobals = false;
7070
bool HasNontrappingFPToInt = false;
7171
bool HasReferenceTypes = false;
72+
bool HasGC = false;
7273
bool HasSignExt = false;
7374
bool HasTailCall = false;
7475
bool HasWideArithmetic = false;

clang/lib/CodeGen/TargetBuiltins/WebAssembly.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212

1313
#include "CGBuiltin.h"
1414
#include "clang/Basic/TargetBuiltins.h"
15+
#include "llvm/ADT/APInt.h"
16+
#include "llvm/IR/Constants.h"
1517
#include "llvm/IR/IntrinsicsWebAssembly.h"
18+
#include "llvm/Support/ErrorHandling.h"
1619

1720
using namespace clang;
1821
using namespace CodeGen;
@@ -218,6 +221,64 @@ Value *CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
218221
Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_ref_null_func);
219222
return Builder.CreateCall(Callee);
220223
}
224+
case WebAssembly::BI__builtin_wasm_test_function_pointer_signature: {
225+
Value *FuncRef = EmitScalarExpr(E->getArg(0));
226+
227+
// Get the function type from the argument's static type
228+
QualType ArgType = E->getArg(0)->getType();
229+
const PointerType *PtrTy = ArgType->getAs<PointerType>();
230+
assert(PtrTy && "Sema should have ensured this is a function pointer");
231+
232+
const FunctionType *FuncTy = PtrTy->getPointeeType()->getAs<FunctionType>();
233+
assert(FuncTy && "Sema should have ensured this is a function pointer");
234+
235+
// In the llvm IR, we won't have access any more to the type of the function
236+
// pointer so we need to insert this type information somehow. The
237+
// @llvm.wasm.ref.test.func takes varargs arguments whose values are unused
238+
// to indicate the type of the function to test for. See the test here:
239+
// llvm/test/CodeGen/WebAssembly/ref-test-func.ll
240+
//
241+
// The format is: first we include the return types (since this is a C
242+
// function pointer, there will be 0 or one of these) then a token type to
243+
// indicate the boundary between return types and param types, then the
244+
// param types.
245+
246+
llvm::FunctionType *LLVMFuncTy =
247+
cast<llvm::FunctionType>(ConvertType(QualType(FuncTy, 0)));
248+
249+
unsigned NParams = LLVMFuncTy->getNumParams();
250+
std::vector<Value *> Args;
251+
Args.reserve(NParams + 3);
252+
// The only real argument is the FuncRef
253+
Args.push_back(FuncRef);
254+
255+
// Add the type information
256+
auto addType = [this, &Args](llvm::Type *T) {
257+
if (T->isVoidTy()) {
258+
// Do nothing
259+
} else if (T->isFloatingPointTy()) {
260+
Args.push_back(ConstantFP::get(T, 0));
261+
} else if (T->isIntegerTy()) {
262+
Args.push_back(ConstantInt::get(T, 0));
263+
} else if (T->isPointerTy()) {
264+
Args.push_back(ConstantPointerNull::get(llvm::PointerType::get(
265+
getLLVMContext(), T->getPointerAddressSpace())));
266+
} else {
267+
// TODO: Handle reference types. For now, we reject them in Sema.
268+
llvm_unreachable("Unhandled type");
269+
}
270+
};
271+
272+
addType(LLVMFuncTy->getReturnType());
273+
// The token type indicates the boundary between return types and param
274+
// types.
275+
Args.push_back(PoisonValue::get(llvm::Type::getTokenTy(getLLVMContext())));
276+
for (unsigned i = 0; i < NParams; i++) {
277+
addType(LLVMFuncTy->getParamType(i));
278+
}
279+
Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_ref_test_func);
280+
return Builder.CreateCall(Callee, Args);
281+
}
221282
case WebAssembly::BI__builtin_wasm_swizzle_i8x16: {
222283
Value *Src = EmitScalarExpr(E->getArg(0));
223284
Value *Indices = EmitScalarExpr(E->getArg(1));

clang/lib/Sema/SemaWasm.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,53 @@ bool SemaWasm::BuiltinWasmTableCopy(CallExpr *TheCall) {
227227
return false;
228228
}
229229

230+
bool SemaWasm::BuiltinWasmTestFunctionPointerSignature(CallExpr *TheCall) {
231+
if (SemaRef.checkArgCount(TheCall, 1))
232+
return true;
233+
234+
Expr *FuncPtrArg = TheCall->getArg(0);
235+
QualType ArgType = FuncPtrArg->getType();
236+
237+
// Check that the argument is a function pointer
238+
const PointerType *PtrTy = ArgType->getAs<PointerType>();
239+
if (!PtrTy) {
240+
return Diag(FuncPtrArg->getBeginLoc(),
241+
diag::err_typecheck_expect_function_pointer)
242+
<< ArgType << FuncPtrArg->getSourceRange();
243+
}
244+
245+
const FunctionProtoType *FuncTy =
246+
PtrTy->getPointeeType()->getAs<FunctionProtoType>();
247+
if (!FuncTy) {
248+
return Diag(FuncPtrArg->getBeginLoc(),
249+
diag::err_typecheck_expect_function_pointer)
250+
<< ArgType << FuncPtrArg->getSourceRange();
251+
}
252+
253+
// Check that the function pointer doesn't use reference types
254+
if (FuncTy->getReturnType().isWebAssemblyReferenceType()) {
255+
return Diag(
256+
FuncPtrArg->getBeginLoc(),
257+
diag::err_wasm_builtin_test_fp_sig_cannot_include_reference_type)
258+
<< 0 << FuncTy->getReturnType() << FuncPtrArg->getSourceRange();
259+
}
260+
auto NParams = FuncTy->getNumParams();
261+
for (unsigned I = 0; I < NParams; I++) {
262+
if (FuncTy->getParamType(I).isWebAssemblyReferenceType()) {
263+
return Diag(
264+
FuncPtrArg->getBeginLoc(),
265+
diag::
266+
err_wasm_builtin_test_fp_sig_cannot_include_reference_type)
267+
<< 1 << FuncPtrArg->getSourceRange();
268+
}
269+
}
270+
271+
// Set return type to int (the result of the test)
272+
TheCall->setType(getASTContext().IntTy);
273+
274+
return false;
275+
}
276+
230277
bool SemaWasm::CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
231278
unsigned BuiltinID,
232279
CallExpr *TheCall) {
@@ -249,6 +296,8 @@ bool SemaWasm::CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
249296
return BuiltinWasmTableFill(TheCall);
250297
case WebAssembly::BI__builtin_wasm_table_copy:
251298
return BuiltinWasmTableCopy(TheCall);
299+
case WebAssembly::BI__builtin_wasm_test_function_pointer_signature:
300+
return BuiltinWasmTestFunctionPointerSignature(TheCall);
252301
}
253302

254303
return false;

clang/test/CodeGen/builtins-wasm.c

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
// RUN: %clang_cc1 -triple wasm32-unknown-unknown -target-feature +reference-types -target-feature +simd128 -target-feature +relaxed-simd -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -target-feature +fp16 -flax-vector-conversions=none -O3 -emit-llvm -o - %s | FileCheck %s -check-prefixes WEBASSEMBLY,WEBASSEMBLY32
2-
// RUN: %clang_cc1 -triple wasm64-unknown-unknown -target-feature +reference-types -target-feature +simd128 -target-feature +relaxed-simd -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -target-feature +fp16 -flax-vector-conversions=none -O3 -emit-llvm -o - %s | FileCheck %s -check-prefixes WEBASSEMBLY,WEBASSEMBLY64
3-
// RUN: not %clang_cc1 -triple wasm64-unknown-unknown -target-feature +reference-types -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -flax-vector-conversions=none -O3 -emit-llvm -o - %s 2>&1 | FileCheck %s -check-prefixes MISSING-SIMD
1+
// RUN: %clang_cc1 -triple wasm32-unknown-unknown -target-feature +reference-types -target-feature +simd128 -target-feature +relaxed-simd -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -target-feature +gc -target-feature +fp16 -flax-vector-conversions=none -O3 -emit-llvm -o - %s | FileCheck %s -check-prefixes WEBASSEMBLY,WEBASSEMBLY32
2+
// RUN: %clang_cc1 -triple wasm64-unknown-unknown -target-feature +reference-types -target-feature +simd128 -target-feature +relaxed-simd -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -target-feature +gc -target-feature +fp16 -flax-vector-conversions=none -O3 -emit-llvm -o - %s | FileCheck %s -check-prefixes WEBASSEMBLY,WEBASSEMBLY64
3+
// RUN: not %clang_cc1 -triple wasm64-unknown-unknown -target-feature +reference-types -target-feature +nontrapping-fptoint -target-feature +exception-handling -target-feature +bulk-memory -target-feature +atomics -target-feature +gc -flax-vector-conversions=none -O3 -emit-llvm -o - %s 2>&1 | FileCheck %s -check-prefixes MISSING-SIMD
44

55
// SIMD convenience types
66
typedef signed char i8x16 __attribute((vector_size(16)));
@@ -751,3 +751,24 @@ void *tp (void) {
751751
return __builtin_thread_pointer ();
752752
// WEBASSEMBLY: call {{.*}} @llvm.thread.pointer.p0()
753753
}
754+
755+
typedef void (*Fvoid)(void);
756+
typedef float (*Ffloats)(float, double, int);
757+
typedef void (*Fpointers)(Fvoid, Ffloats, void*, int*, int***, char[5]);
758+
759+
void use(int);
760+
761+
void test_function_pointer_signature_void(Fvoid func) {
762+
// WEBASSEMBLY: %0 = tail call i32 (ptr, ...) @llvm.wasm.ref.test.func(ptr %func, token poison)
763+
use(__builtin_wasm_test_function_pointer_signature(func));
764+
}
765+
766+
void test_function_pointer_signature_floats(Ffloats func) {
767+
// WEBASSEMBLY: tail call i32 (ptr, ...) @llvm.wasm.ref.test.func(ptr %func, float 0.000000e+00, token poison, float 0.000000e+00, double 0.000000e+00, i32 0)
768+
use(__builtin_wasm_test_function_pointer_signature(func));
769+
}
770+
771+
void test_function_pointer_signature_pointers(Fpointers func) {
772+
// WEBASSEMBLY: %0 = tail call i32 (ptr, ...) @llvm.wasm.ref.test.func(ptr %func, token poison, ptr null, ptr null, ptr null, ptr null, ptr null, ptr null)
773+
use(__builtin_wasm_test_function_pointer_signature(func));
774+
}

clang/test/Sema/builtins-wasm.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,27 @@ void test_table_copy(int dst_idx, int src_idx, int nelem) {
5454
__builtin_wasm_table_copy(table, table, dst_idx, src_idx, table); // expected-error {{5th argument must be an integer}}
5555
__builtin_wasm_table_copy(table, table, dst_idx, src_idx, nelem);
5656
}
57+
58+
typedef void (*F1)(void);
59+
typedef int (*F2)(int);
60+
typedef int (*F3)(__externref_t);
61+
typedef __externref_t (*F4)(int);
62+
63+
void test_function_pointer_signature() {
64+
// Test argument count validation
65+
(void)__builtin_wasm_test_function_pointer_signature(); // expected-error {{too few arguments to function call, expected 1, have 0}}
66+
(void)__builtin_wasm_test_function_pointer_signature((F1)0, (F2)0); // expected-error {{too many arguments to function call, expected 1, have 2}}
67+
68+
// // Test argument type validation - should require function pointer
69+
(void)__builtin_wasm_test_function_pointer_signature((void*)0); // expected-error {{used type 'void *' where function pointer is required}}
70+
(void)__builtin_wasm_test_function_pointer_signature((int)0); // expected-error {{used type 'int' where function pointer is required}}
71+
(void)__builtin_wasm_test_function_pointer_signature((F3)0); // expected-error {{not supported for function pointers with a reference type parameter}}
72+
(void)__builtin_wasm_test_function_pointer_signature((F4)0); // expected-error {{not supported for function pointers with a reference type return value}}
73+
74+
// // Test valid usage
75+
int res = __builtin_wasm_test_function_pointer_signature((F1)0);
76+
res = __builtin_wasm_test_function_pointer_signature((F2)0);
77+
78+
// Test return type
79+
_Static_assert(EXPR_HAS_TYPE(__builtin_wasm_test_function_pointer_signature((F1)0), int), "");
80+
}

llvm/lib/Target/WebAssembly/WebAssembly.td

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ def FeatureReferenceTypes :
7171
SubtargetFeature<"reference-types", "HasReferenceTypes", "true",
7272
"Enable reference types">;
7373

74+
def FeatureGC : SubtargetFeature<"gc", "HasGC", "true", "Enable wasm gc">;
7475
def FeatureRelaxedSIMD :
7576
SubtargetFeature<"relaxed-simd", "SIMDLevel", "RelaxedSIMD",
7677
"Enable relaxed-simd instructions">;
@@ -136,13 +137,13 @@ def : ProcessorModel<"lime1", NoSchedModel,
136137

137138
// Latest and greatest experimental version of WebAssembly. Bugs included!
138139
def : ProcessorModel<"bleeding-edge", NoSchedModel,
139-
[FeatureAtomics, FeatureBulkMemory, FeatureBulkMemoryOpt,
140-
FeatureCallIndirectOverlong, FeatureExceptionHandling,
141-
FeatureExtendedConst, FeatureFP16, FeatureMultiMemory,
142-
FeatureMultivalue, FeatureMutableGlobals,
143-
FeatureNontrappingFPToInt, FeatureRelaxedSIMD,
144-
FeatureReferenceTypes, FeatureSIMD128, FeatureSignExt,
145-
FeatureTailCall]>;
140+
[FeatureAtomics, FeatureBulkMemory, FeatureBulkMemoryOpt,
141+
FeatureCallIndirectOverlong, FeatureExceptionHandling,
142+
FeatureExtendedConst, FeatureFP16, FeatureMultiMemory,
143+
FeatureMultivalue, FeatureMutableGlobals,
144+
FeatureNontrappingFPToInt, FeatureRelaxedSIMD,
145+
FeatureReferenceTypes, FeatureGC, FeatureSIMD128,
146+
FeatureSignExt, FeatureTailCall]>;
146147

147148
//===----------------------------------------------------------------------===//
148149
// Target Declaration

0 commit comments

Comments
 (0)