[clang] [llvm] [Clang][RISCV] generate Labels for the zicfilp func-sig label scheme (PR #240346)
Benedikt Steinberg via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 23 01:23:00 PST 2026
https://github.com/Keksesser3000 updated https://github.com/llvm/llvm-project/pull/240346
>From 4645bf1339bdc44adacdaf3e0465061db720c692 Mon Sep 17 00:00:00 2001
From: Benedikt Steinberg <benedikt.steinberg at aisec.fraunhofer.de>
Date: Wed, 21 Oct 2026 00:07:29 +0000
Subject: [PATCH 1/3] [Clang][RISCV] generate Labels for the zicfilp func-sig
label scheme
---
clang/lib/Basic/Targets/RISCV.cpp | 15 +-
clang/lib/CodeGen/CGBlocks.cpp | 19 +-
clang/lib/CodeGen/CGCoroutine.cpp | 5 +
clang/lib/CodeGen/CGDeclCXX.cpp | 28 +-
clang/lib/CodeGen/CGExpr.cpp | 9 +
clang/lib/CodeGen/CGExprCXX.cpp | 53 +-
clang/lib/CodeGen/CGOpenMPRuntime.cpp | 13 +-
clang/lib/CodeGen/CMakeLists.txt | 1 +
clang/lib/CodeGen/CodeGenModule.cpp | 78 +++
clang/lib/CodeGen/CodeGenModule.h | 17 +-
clang/lib/CodeGen/RISCVLpadLabelGen.cpp | 507 ++++++++++++++++++
clang/lib/CodeGen/RISCVLpadLabelGen.h | 73 +++
.../test/CodeGen/RISCV/riscv-cf-protection.c | 35 +-
.../RISCV/riscv-zicfilp-block-call.cpp | 89 +++
.../riscv-zicfilp-cpp-member-pointers.cpp | 26 +
.../RISCV/riscv-zicfilp-cpp-virtual-call.cpp | 11 +
.../RISCV/riscv-zicfilp-main-attr-noargs.c | 64 +++
.../CodeGen/RISCV/riscv-zicfilp-main-attr.c | 76 +++
.../CodeGen/RISCV/riscv-zicfilp-metadata.c | 262 +++++++++
.../CodeGen/RISCV/riscv-zicfilp-no-bypass.c | 9 +
...ilp-template-exceptionspec-unsupported.cpp | 20 +
...cv-zicfilp-template-wchart-unsupported.cpp | 66 +++
.../riscv-zicfilp-virtual-destructor.cpp | 17 +
.../Preprocessor/riscv-cf-protection-branch.c | 29 +
clang/unittests/CMakeLists.txt | 3 +
clang/unittests/CodeGen/CMakeLists.txt | 1 +
.../CodeGen/RISCVLpadLabelGenTest.cpp | 457 ++++++++++++++++
.../llvm/Transforms/Utils/RISCVZicfilpHash.h | 33 ++
llvm/lib/Transforms/Utils/CMakeLists.txt | 1 +
.../lib/Transforms/Utils/RISCVZicfilpHash.cpp | 55 ++
.../unittests/Transforms/Utils/CMakeLists.txt | 1 +
.../Transforms/Utils/RISCVZicfilpHashTest.cpp | 102 ++++
32 files changed, 2126 insertions(+), 49 deletions(-)
create mode 100644 clang/lib/CodeGen/RISCVLpadLabelGen.cpp
create mode 100644 clang/lib/CodeGen/RISCVLpadLabelGen.h
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-block-call.cpp
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-member-pointers.cpp
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-virtual-call.cpp
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr-noargs.c
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr.c
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-metadata.c
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-no-bypass.c
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-template-exceptionspec-unsupported.cpp
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-template-wchart-unsupported.cpp
create mode 100644 clang/test/CodeGen/RISCV/riscv-zicfilp-virtual-destructor.cpp
create mode 100644 clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
create mode 100644 llvm/include/llvm/Transforms/Utils/RISCVZicfilpHash.h
create mode 100644 llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
create mode 100644 llvm/unittests/Transforms/Utils/RISCVZicfilpHashTest.cpp
diff --git a/clang/lib/Basic/Targets/RISCV.cpp b/clang/lib/Basic/Targets/RISCV.cpp
index c282136cf5fcf2..34a7f852358935 100644
--- a/clang/lib/Basic/Targets/RISCV.cpp
+++ b/clang/lib/Basic/Targets/RISCV.cpp
@@ -257,7 +257,7 @@ void RISCVTargetInfo::getTargetDefines(const LangOptions &Opts,
Builder.defineMacro("__riscv_landing_pad_unlabeled");
break;
case CFBranchLabelSchemeKind::FuncSig:
- // TODO: Define macros after the func-sig scheme is implemented
+ Builder.defineMacro("__riscv_landing_pad_func_sig");
break;
case CFBranchLabelSchemeKind::Default:
llvm_unreachable("default cf-branch-label scheme should already be "
@@ -647,22 +647,11 @@ bool RISCVTargetInfo::validateCpuIs(StringRef CPUName) const {
bool RISCVTargetInfo::checkCFBranchLabelSchemeSupported(
const CFBranchLabelSchemeKind Scheme, DiagnosticsEngine &Diags) const {
- // TODO: Allow the default func-sig scheme to be selected after backend
- // implements it
switch (Scheme) {
case CFBranchLabelSchemeKind::Default:
- return true;
case CFBranchLabelSchemeKind::Unlabeled:
- return true;
case CFBranchLabelSchemeKind::FuncSig:
- Diags.Report(diag::err_opt_unsupported_with_suggest)
- << (Twine("-mcf-branch-label-scheme=") +
- getCFBranchLabelSchemeFlagVal(CFBranchLabelSchemeKind::FuncSig))
- .str()
- << (Twine("-mcf-branch-label-scheme=") +
- getCFBranchLabelSchemeFlagVal(CFBranchLabelSchemeKind::Unlabeled))
- .str();
- return false;
+ return true;
}
return TargetInfo::checkCFBranchLabelSchemeSupported(Scheme, Diags);
}
diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp
index 26c34925b7a651..33ad0a213e7e4b 100644
--- a/clang/lib/CodeGen/CGBlocks.cpp
+++ b/clang/lib/CodeGen/CGBlocks.cpp
@@ -19,6 +19,7 @@
#include "CodeGenModule.h"
#include "CodeGenPGO.h"
#include "ConstantEmitter.h"
+#include "RISCVLpadLabelGen.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
@@ -1236,8 +1237,15 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
CGCallee Callee(CGCalleeInfo(), Func, PointerAuth);
- // And call the block.
- return EmitCall(FnInfo, Callee, ReturnValue, Args, CallOrInvoke);
+ llvm::CallBase *LocalCallOrInvoke = nullptr;
+ RValue RV = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke);
+
+ // Add RISC-V landing pad label metadata for zicfilp extension
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, FnType, E->getExprLoc());
+
+ if (CallOrInvoke)
+ *CallOrInvoke = LocalCallOrInvoke;
+ return RV;
}
Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
@@ -1512,6 +1520,7 @@ llvm::Function *CodeGenFunction::GenerateBlockFunction(
llvm::Function *fn = llvm::Function::Create(
fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
+ CGM.setRISCVLpadFunctionAttr(fn, QualType(fnType, 0));
if (BuildGlobalBlock) {
auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
@@ -1957,6 +1966,7 @@ CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
CGM);
+ CGM.setRISCVLpadFunctionAttr(Fn, buildBlockCopyHelperSigTy(C));
StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
@@ -2148,6 +2158,9 @@ CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
CGM);
+ // Block dispose helpers share the void(void*) ABI shape with C++
+ // destructors and __cxa_atexit callbacks
+ CGM.setRISCVLpadFunctionAttr(Fn, buildDtorSigTy(C));
StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
markAsIgnoreThreadCheckingAtRuntime(Fn);
@@ -2413,6 +2426,7 @@ generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
"__Block_byref_object_copy_", &CGF.CGM.getModule());
CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
+ CGF.CGM.setRISCVLpadFunctionAttr(Fn, buildBlockCopyHelperSigTy(Context));
CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
// Create a scope with an artificial location for the body of this function.
@@ -2474,6 +2488,7 @@ generateByrefDisposeHelper(CodeGenFunction &CGF,
&CGF.CGM.getModule());
CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
+ CGF.CGM.setRISCVLpadFunctionAttr(Fn, buildDtorSigTy(Context));
CGF.StartFunction(GlobalDecl(), R, Fn, FI, args);
// Create a scope with an artificial location for the body of this function.
diff --git a/clang/lib/CodeGen/CGCoroutine.cpp b/clang/lib/CodeGen/CGCoroutine.cpp
index 2f162519139e0d..46f94f4a600a0b 100644
--- a/clang/lib/CodeGen/CGCoroutine.cpp
+++ b/clang/lib/CodeGen/CGCoroutine.cpp
@@ -439,6 +439,11 @@ CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,
LTy, llvm::GlobalValue::InternalLinkage, FuncName, &CGM.getModule());
CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
+ QualType VoidPtrTy = C.getPointerType(C.VoidTy);
+ QualType WrapperSigTy = C.getFunctionType(ReturnTy, {VoidPtrTy, VoidPtrTy},
+ FunctionProtoType::ExtProtoInfo());
+ CGM.setRISCVLpadFunctionAttr(Fn, WrapperSigTy);
+
Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index 2b6bd17e278b5d..0c08f613c7b4d6 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -16,6 +16,7 @@
#include "CGObjCRuntime.h"
#include "CGOpenMPRuntime.h"
#include "CodeGenFunction.h"
+#include "RISCVLpadLabelGen.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/Basic/LangOptions.h"
@@ -294,8 +295,13 @@ llvm::Function *CodeGenFunction::createTLSAtExitStub(
llvm::FunctionType *StubTy =
llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy}, true);
+ FunctionProtoType::ExtProtoInfo EPI;
+ EPI.Variadic = true;
+ QualType StubSigTy = CGM.getContext().getFunctionType(
+ CGM.getContext().IntTy, {CGM.getContext().IntTy}, EPI);
llvm::Function *DtorStub = CGM.CreateGlobalInitOrCleanUpFunction(
- StubTy, FnName.str(), FI, D.getLocation());
+ StubTy, FnName.str(), FI, D.getLocation(),
+ /*TLS=*/false, llvm::GlobalVariable::InternalLinkage, StubSigTy);
CodeGenFunction CGF(CGM);
@@ -438,9 +444,23 @@ void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
- SourceLocation Loc, bool TLS, llvm::GlobalVariable::LinkageTypes Linkage) {
+ SourceLocation Loc, bool TLS, llvm::GlobalVariable::LinkageTypes Linkage,
+ QualType RISCVLpadSigTy) {
llvm::Function *Fn = llvm::Function::Create(FTy, Linkage, Name, &getModule());
+ assert((!RISCVLpadSigTy.isNull() ||
+ (FTy->getReturnType()->isVoidTy() && FTy->params().empty() &&
+ !FTy->isVarArg())) &&
+ "CreateGlobalInitOrCleanUpFunction: omitted RISCVLpadSigTy "
+ "implies a plain void() signature, but FTy does not match it");
+
+ QualType SigTy =
+ RISCVLpadSigTy.isNull()
+ ? getContext().getFunctionType(getContext().VoidTy, {},
+ FunctionProtoType::ExtProtoInfo())
+ : RISCVLpadSigTy;
+ setRISCVLpadFunctionAttr(Fn, SigTy);
+
if (!getLangOpts().AppleKext && !TLS) {
// Set the section if needed.
if (const char *Section = getTarget().getStaticInitSectionSpecifier())
@@ -1183,7 +1203,9 @@ llvm::Function *CodeGenFunction::generateDestroyHelper(
CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
- FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
+ FTy, "__cxx_global_array_dtor", FI, VD->getLocation(),
+ /*TLS=*/false, llvm::GlobalVariable::InternalLinkage,
+ buildDtorSigTy(getContext()));
CurEHLocation = VD->getBeginLoc();
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae5f4e723f5129..50bb5bf24bdc06 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -7344,6 +7344,15 @@ RValue CodeGenFunction::EmitCall(QualType CalleeType,
if (CallOrInvoke)
*CallOrInvoke = LocalCallOrInvoke;
+ // Add RISC-V landing pad label metadata for zicfilp extension
+ // if Branch Label Scheme "func-sig" is not selected, the label is 0 instead.
+ // CFIUnchecked is applicable only for software-cfi, don't check it here.
+ if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, FD);
+ else
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, QualType(FnType, 0),
+ E ? E->getExprLoc() : SourceLocation());
+
return Call;
}
diff --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp
index 761c689c224186..1b0e0a2ae2ff0a 100644
--- a/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/clang/lib/CodeGen/CGExprCXX.cpp
@@ -94,9 +94,20 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize,
getCurrentFunctionDecl());
- return EmitCall(FnInfo, Callee, ReturnValue, Args, CallOrInvoke,
- CE && CE == MustTailCall,
- CE ? CE->getExprLoc() : SourceLocation());
+
+ llvm::CallBase *LocalCallOrInvoke = nullptr;
+ RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
+ CE && CE == MustTailCall,
+ CE ? CE->getExprLoc() : SourceLocation());
+
+ // Add RISC-V landing pad label metadata for zicfilp extension. A virtual
+ // call (CGCallee::forVirtual) lowers to an indirect call through the
+ // vtable.
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, MD);
+
+ if (CallOrInvoke)
+ *CallOrInvoke = LocalCallOrInvoke;
+ return Call;
}
RValue CodeGenFunction::EmitCXXDestructorCall(
@@ -120,10 +131,19 @@ RValue CodeGenFunction::EmitCXXDestructorCall(
CallArgList Args;
commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam,
ImplicitParamTy, CE, Args, nullptr);
- return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
- ReturnValueSlot(), Args, CallOrInvoke,
- CE && CE == MustTailCall,
- CE ? CE->getExprLoc() : SourceLocation{});
+
+ llvm::CallBase *LocalCallOrInvoke = nullptr;
+ RValue RV = EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor),
+ Callee, ReturnValueSlot(), Args, &LocalCallOrInvoke,
+ CE && CE == MustTailCall,
+ CE ? CE->getExprLoc() : SourceLocation{});
+
+ // Add RISC-V landing pad label metadata for zicfilp extension
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, DtorDecl);
+
+ if (CallOrInvoke)
+ *CallOrInvoke = LocalCallOrInvoke;
+ return RV;
}
RValue
@@ -496,11 +516,20 @@ CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
// And the rest of the call args
EmitCallArgs(Args, FPT, E->arguments());
- return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
- /*PrefixSize=*/0,
- getCurrentFunctionDecl()),
- Callee, ReturnValue, Args, CallOrInvoke, E == MustTailCall,
- E->getExprLoc());
+ llvm::CallBase *LocalCallOrInvoke = nullptr;
+ RValue Call = EmitCall(CGM.getTypes().arrangeCXXMethodCall(
+ Args, FPT, required,
+ /*PrefixSize=*/0, getCurrentFunctionDecl()),
+ Callee, ReturnValue, Args, &LocalCallOrInvoke,
+ E == MustTailCall, E->getExprLoc());
+
+ // Add RISC-V landing pad label metadata for zicfilp extension
+ CGM.setRISCVLpadCallSiteMetadata(LocalCallOrInvoke, MemFnExpr->getType(),
+ E->getExprLoc());
+
+ if (CallOrInvoke)
+ *CallOrInvoke = LocalCallOrInvoke;
+ return Call;
}
RValue CodeGenFunction::EmitCXXOperatorMemberCallExpr(
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index a88039aeb9cee6..18e99e7a2e09d2 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -17,6 +17,7 @@
#include "CGDebugInfo.h"
#include "CGRecordLayout.h"
#include "CodeGenFunction.h"
+#include "RISCVLpadLabelGen.h"
#include "TargetInfo.h"
#include "clang/AST/APValue.h"
#include "clang/AST/Attr.h"
@@ -1687,8 +1688,10 @@ llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
CGM.getContext().VoidPtrTy, Args);
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
std::string Name = getName({"__kmpc_global_ctor_", ""});
- llvm::Function *Fn =
- CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
+ llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
+ FTy, Name, FI, Loc, /*TLS=*/false,
+ llvm::GlobalVariable::InternalLinkage,
+ buildVoidPtrToVoidPtrSigTy(CGM.getContext()));
CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Args, Loc, Loc);
llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
@@ -1718,8 +1721,10 @@ llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
CGM.getContext().VoidTy, Args);
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
std::string Name = getName({"__kmpc_global_dtor_", ""});
- llvm::Function *Fn =
- CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
+ llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
+ FTy, Name, FI, Loc, /*TLS=*/false,
+ llvm::GlobalVariable::InternalLinkage,
+ buildDtorSigTy(CGM.getContext()));
auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Loc, Loc);
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 93790567dcf8bb..77631615b8ed0d 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -120,6 +120,7 @@ add_clang_library(clangCodeGen
ObjectFilePCHContainerWriter.cpp
PatternInit.cpp
QualTypeMapper.cpp
+ RISCVLpadLabelGen.cpp
SanitizerMetadata.cpp
SwiftCallingConv.cpp
TargetBuiltins/ARM.cpp
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 88129acfe2dabc..bfbcd83c2763a3 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -27,6 +27,7 @@
#include "ConstantEmitter.h"
#include "CoverageMappingGen.h"
#include "QualTypeMapper.h"
+#include "RISCVLpadLabelGen.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
@@ -3910,6 +3911,11 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
setKCFIType(FD, F);
+ // If RISC-V Landing Pads are enabled, add the function Type ID to the
+ // function as an attribute to pass it to the backend. if Branch Label Scheme
+ // "func-sig" is not selected, the label is 0 instead.
+ setRISCVLpadFunctionAttr(F, FD);
+
if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
@@ -3934,6 +3940,78 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
}
}
+void CodeGenModule::setRISCVLpadFunctionAttr(llvm::Function *Fn,
+ QualType FnTy) {
+ if (!(CodeGenOpts.CFProtectionBranch && getTriple().isRISCV()))
+ return;
+ uint32_t Label = 0;
+ if (getResolvedCFBranchLabelScheme() == CFBranchLabelSchemeKind::FuncSig)
+ Label = createRISCVLpadTypeId(
+ getContext(),
+ cast<ItaniumMangleContext>(getCXXABI().getMangleContext()), FnTy);
+ Fn->addFnAttr("cfi_type_hash", std::to_string(Label));
+}
+
+void CodeGenModule::setRISCVLpadFunctionAttr(llvm::Function *Fn,
+ const FunctionDecl *FD) {
+ if (!(CodeGenOpts.CFProtectionBranch && getTriple().isRISCV()))
+ return;
+ uint32_t Label = 0;
+ if (getResolvedCFBranchLabelScheme() == CFBranchLabelSchemeKind::FuncSig)
+ Label = createRISCVEntryLpadTypeId(
+ getContext(),
+ cast<ItaniumMangleContext>(getCXXABI().getMangleContext()), FD);
+ Fn->addFnAttr("cfi_type_hash", std::to_string(Label));
+}
+
+static bool needsRISCVLpadCallLabel(CodeGenModule &CGM,
+ llvm::CallBase *CallOrInvoke) {
+ // CFIUnchecked is applicable only for software-cfi, don't check it here.
+ return CallOrInvoke && CGM.getTriple().isRISCV() &&
+ CGM.getCodeGenOpts().CFProtectionBranch &&
+ !CallOrInvoke->getCalledFunction();
+}
+
+static void attachRISCVLpadCallLabel(CodeGenModule &CGM,
+ llvm::CallBase *CallOrInvoke,
+ uint32_t Label) {
+ CallOrInvoke->setMetadata(
+ "riscv_lpad_label",
+ llvm::MDNode::get(
+ CGM.getLLVMContext(),
+ llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+ llvm::Type::getInt32Ty(CGM.getLLVMContext()), Label))));
+}
+
+void CodeGenModule::setRISCVLpadCallSiteMetadata(llvm::CallBase *CallOrInvoke,
+ const FunctionDecl *FD) {
+ if (!needsRISCVLpadCallLabel(*this, CallOrInvoke))
+ return;
+
+ uint32_t Label = 0;
+ if (getResolvedCFBranchLabelScheme() == CFBranchLabelSchemeKind::FuncSig)
+ Label = createRISCVCallSiteLpadTypeId(
+ getContext(),
+ cast<ItaniumMangleContext>(getCXXABI().getMangleContext()), FD);
+
+ attachRISCVLpadCallLabel(*this, CallOrInvoke, Label);
+}
+
+void CodeGenModule::setRISCVLpadCallSiteMetadata(llvm::CallBase *CallOrInvoke,
+ QualType FnTy,
+ SourceLocation Loc) {
+ if (!needsRISCVLpadCallLabel(*this, CallOrInvoke))
+ return;
+
+ uint32_t Label = 0;
+ if (getResolvedCFBranchLabelScheme() == CFBranchLabelSchemeKind::FuncSig)
+ Label = createRISCVLpadTypeId(
+ getContext(),
+ cast<ItaniumMangleContext>(getCXXABI().getMangleContext()), FnTy, Loc);
+
+ attachRISCVLpadCallLabel(*this, CallOrInvoke, Label);
+}
+
void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
"Only globals with definition can force usage.");
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index e2bd6bc4701fda..ec8dd97810ea47 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1070,7 +1070,8 @@ class CodeGenModule : public CodeGenTypeCache {
llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
SourceLocation Loc = SourceLocation(), bool TLS = false,
llvm::GlobalVariable::LinkageTypes Linkage =
- llvm::GlobalVariable::InternalLinkage);
+ llvm::GlobalVariable::InternalLinkage,
+ QualType RISCVLpadSigTy = QualType());
/// Return the AST address space of the underlying global variable for D, as
/// determined by its declaration. Normally this is the same as the address
@@ -1994,6 +1995,20 @@ class CodeGenModule : public CodeGenTypeCache {
std::string getPFPFieldName(const FieldDecl *FD);
llvm::GlobalValue *getPFPDeactivationSymbol(const FieldDecl *FD);
+ CFBranchLabelSchemeKind getResolvedCFBranchLabelScheme() const {
+ auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
+ if (Scheme == CFBranchLabelSchemeKind::Default)
+ Scheme = Target.getDefaultCFBranchLabelScheme();
+ return Scheme;
+ }
+
+ void setRISCVLpadFunctionAttr(llvm::Function *Fn, const FunctionDecl *FD);
+ void setRISCVLpadFunctionAttr(llvm::Function *Fn, QualType FnTy);
+ void setRISCVLpadCallSiteMetadata(llvm::CallBase *CallOrInvoke,
+ const FunctionDecl *FD);
+ void setRISCVLpadCallSiteMetadata(llvm::CallBase *CallOrInvoke, QualType FnTy,
+ SourceLocation Loc);
+
private:
/// Translate an llvm::abi::ArgInfo (computed by the LLVMABI library) into
/// the clang ABIArgInfo consumed by the rest of CodeGen. Used by the
diff --git a/clang/lib/CodeGen/RISCVLpadLabelGen.cpp b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
new file mode 100644
index 00000000000000..7842171a877702
--- /dev/null
+++ b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
@@ -0,0 +1,507 @@
+//===--- RISCVLpadLabelGen.cpp - func-sig based lpad label gen ------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Implements lpad label generation helpers from RISCVLpadLabelGen.h
+//
+//===----------------------------------------------------------------------===//
+
+#include "RISCVLpadLabelGen.h"
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/Mangle.h"
+#include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TargetInfo.h"
+#include "llvm/Support/MD5.h"
+#include "llvm/Transforms/Utils/RISCVZicfilpHash.h"
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang;
+using namespace clang::CodeGen;
+
+namespace clang {
+namespace CodeGen {
+QualType getRISCVLpadCanonicalSignature(ASTContext &Ctx, QualType Ty,
+ SourceLocation Loc = SourceLocation());
+
+QualType substituteCovariantReturn(ASTContext &Ctx, QualType Ty);
+
+QualType getSyntheticVType(ASTContext &Ctx);
+
+QualType buildMainSigTy(ASTContext &Ctx);
+
+} // namespace CodeGen
+} // namespace clang
+
+namespace {
+
+enum class TemplateArgScanResult {
+ Safe,
+ ContainsWCharT,
+ ContainsExceptionSpec,
+ Unsupported,
+};
+
+/// FIXME: template arguments are not handled correctly (unsupported).
+/// supports: pointers, references, arrays, member-pointer pointees,
+/// function-proto/no-proto, ParenType, TypedefType, Block pointers
+class SignatureNormalizer : public TypeVisitor<SignatureNormalizer, QualType> {
+ ASTContext &Ctx;
+ QualType UnderlyingWCharTy;
+
+ static QualType computeUnderlyingWCharTy(ASTContext &Ctx) {
+ switch (Ctx.getTargetInfo().getWCharType()) {
+ case TargetInfo::SignedInt:
+ return Ctx.IntTy;
+ case TargetInfo::UnsignedInt:
+ return Ctx.UnsignedIntTy;
+ case TargetInfo::SignedLong:
+ return Ctx.LongTy;
+ case TargetInfo::UnsignedLong:
+ return Ctx.UnsignedLongTy;
+ case TargetInfo::SignedShort:
+ return Ctx.ShortTy;
+ case TargetInfo::UnsignedShort:
+ return Ctx.UnsignedShortTy;
+ default:
+ llvm_unreachable("unexpected wchar_t underlying type");
+ }
+ }
+
+public:
+ explicit SignatureNormalizer(ASTContext &Ctx)
+ : Ctx(Ctx), UnderlyingWCharTy(computeUnderlyingWCharTy(Ctx)) {}
+
+ QualType Visit(QualType T) {
+ Qualifiers Quals = T.getQualifiers();
+ QualType Result = TypeVisitor::Visit(T.getTypePtr());
+ return Ctx.getQualifiedType(Result, Quals);
+ }
+
+ QualType VisitType(const Type *T) { return QualType(T, 0); }
+
+ QualType VisitBuiltinType(const BuiltinType *T) {
+ if (T->getKind() == BuiltinType::WChar_S ||
+ T->getKind() == BuiltinType::WChar_U)
+ return UnderlyingWCharTy;
+ return QualType(T, 0);
+ }
+
+ QualType VisitPointerType(const PointerType *T) {
+ return Ctx.getPointerType(Visit(T->getPointeeType()));
+ }
+ QualType VisitLValueReferenceType(const LValueReferenceType *T) {
+ return Ctx.getLValueReferenceType(Visit(T->getPointeeType()));
+ }
+ QualType VisitRValueReferenceType(const RValueReferenceType *T) {
+ return Ctx.getRValueReferenceType(Visit(T->getPointeeType()));
+ }
+
+ // Pointer-to-array (e.g. "wchar_t (*)[4]") -- the only shape an array
+ // can take inside a mangled function signature, since arrays decay to
+ // pointers in parameter position and can't be returned directly.
+ QualType VisitConstantArrayType(const ConstantArrayType *T) {
+ return Ctx.getConstantArrayType(Visit(T->getElementType()), T->getSize(),
+ T->getSizeExpr(), T->getSizeModifier(),
+ T->getIndexTypeCVRQualifiers());
+ }
+ QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
+ return Ctx.getIncompleteArrayType(Visit(T->getElementType()),
+ T->getSizeModifier(),
+ T->getIndexTypeCVRQualifiers());
+ }
+
+ // Nested pointer-to-member (e.g. as a parameter type): per psABI, the
+ // class/covariant-return substitutions only apply at the top level, so
+ // we only recurse for wchar_t/exception-spec normalization here --
+ // the class and pointee are otherwise left as-is.
+ QualType VisitMemberPointerType(const MemberPointerType *T) {
+ QualType NewPointee = Visit(T->getPointeeType());
+ return Ctx.getMemberPointerType(NewPointee, std::nullopt,
+ T->getMostRecentCXXRecordDecl());
+ }
+
+ // Unprototyped (C-style) empty parameter list -> explicit (void).
+ QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
+ FunctionProtoType::ExtProtoInfo EPI;
+ EPI.ExtInfo = T->getExtInfo();
+ return Ctx.getFunctionType(Visit(T->getReturnType()), {}, EPI);
+ }
+
+ QualType VisitFunctionProtoType(const FunctionProtoType *T) {
+ SmallVector<QualType, 8> Params;
+ for (QualType P : T->getParamTypes())
+ Params.push_back(Visit(P));
+
+ FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
+ EPI.ExceptionSpec =
+ FunctionProtoType::ExceptionSpecInfo(); // strip, at every level
+
+ return Ctx.getFunctionType(Visit(T->getReturnType()), Params, EPI);
+ }
+
+ QualType VisitParenType(const ParenType *T) {
+ return Visit(T->getInnerType());
+ }
+
+ QualType VisitTypedefType(const TypedefType *T) {
+ return Visit(T->desugar());
+ }
+
+ QualType VisitBlockPointerType(const BlockPointerType *T) {
+ return Ctx.getBlockPointerType(Visit(T->getPointeeType()));
+ }
+
+ QualType VisitVariableArrayType(const VariableArrayType *T) {
+ return Ctx.getVariableArrayType(Visit(T->getElementType()),
+ T->getSizeExpr(), T->getSizeModifier(),
+ T->getIndexTypeCVRQualifiers());
+ }
+};
+
+} // end anonymous namespace
+
+QualType clang::CodeGen::buildMainSigTy(ASTContext &Ctx) {
+ QualType CharPtrPtr = Ctx.getPointerType(Ctx.getPointerType(Ctx.CharTy));
+ FunctionProtoType::ExtProtoInfo
+ EPI; // defaults are fine: no exceptions, normal CC
+ return Ctx.getFunctionType(Ctx.IntTy, {Ctx.IntTy, CharPtrPtr}, EPI);
+}
+
+QualType clang::CodeGen::buildBlockCopyHelperSigTy(ASTContext &Ctx) {
+ QualType VoidPtr = Ctx.getPointerType(Ctx.VoidTy);
+ FunctionProtoType::ExtProtoInfo EPI;
+ return Ctx.getFunctionType(Ctx.VoidTy, {VoidPtr, VoidPtr}, EPI);
+}
+
+QualType clang::CodeGen::buildDtorSigTy(ASTContext &Ctx) {
+ QualType VoidPtr = Ctx.getPointerType(Ctx.VoidTy);
+ FunctionProtoType::ExtProtoInfo EPI;
+ return Ctx.getFunctionType(Ctx.VoidTy, {VoidPtr}, EPI);
+}
+
+QualType clang::CodeGen::buildVoidPtrToVoidPtrSigTy(ASTContext &Ctx) {
+ QualType VoidPtr = Ctx.getPointerType(Ctx.VoidTy);
+ FunctionProtoType::ExtProtoInfo EPI;
+ return Ctx.getFunctionType(VoidPtr, {VoidPtr}, EPI);
+}
+
+uint32_t
+clang::CodeGen::computeRISCVLpadLabel(const llvm::MD5::MD5Result &Result) {
+ return llvm::RISCVCFI::reduceZicfilpFuncSigLabel(Result);
+}
+
+uint32_t clang::CodeGen::computeRISCVLpadLabel(llvm::StringRef Str) {
+ return llvm::RISCVCFI::getZicfilpFuncSigLabel(Str);
+}
+
+// apply signature normalization according to psABI draft
+// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/pull/434, then delegate
+// to Itanium Mangler.
+std::string
+clang::CodeGen::getRISCVLpadSignatureString(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ QualType Ty, SourceLocation Loc) {
+ Ty = getRISCVLpadCanonicalSignature(Ctx, Ty, Loc);
+
+ std::string MangledName;
+ llvm::raw_string_ostream Out(MangledName);
+ MC.mangleCXXRTTIName(Ty, Out);
+
+ assert(llvm::StringRef(MangledName).starts_with("_ZTS") &&
+ "unexpected RTTI name mangling format");
+ return MangledName.substr(4);
+}
+
+std::string clang::CodeGen::getRISCVLpadSignatureString(
+ ASTContext &Ctx, ItaniumMangleContext &MC, const FunctionDecl *FD) {
+ // special cases
+ if (FD->isMain())
+ return getRISCVLpadSignatureString(Ctx, MC, buildMainSigTy(Ctx));
+ if (isa<CXXDestructorDecl>(FD))
+ return getRISCVLpadSignatureString(Ctx, MC, buildDtorSigTy(Ctx));
+
+ if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
+ if (!MD->isStatic()) {
+ QualType MPTy = Ctx.getMemberPointerType(MD->getType(), std::nullopt,
+ MD->getParent());
+ return getRISCVLpadSignatureString(
+ Ctx, MC, MPTy, FD->getLocation()); // v-substitution happens
+ }
+ // later, during canonicalization
+ // Static member: falls through, treated as non-member below.
+ }
+
+ // Free function / static member function: use the FunctionProtoType
+ // directly (exception-spec stripping, wchar_t normalization, empty
+ // param list -> void, all applied before/inside the type overload).
+ return getRISCVLpadSignatureString(Ctx, MC, FD->getType(), FD->getLocation());
+}
+
+uint32_t clang::CodeGen::createRISCVEntryLpadTypeId(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ const FunctionDecl *FD) {
+ if (FD->getIdentifier() && FD->getName() == "_dl_runtime_resolve" &&
+ FD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
+ FD->isExternC() && FD->isExternallyVisible())
+ return 0;
+ return createRISCVCallSiteLpadTypeId(Ctx, MC, FD);
+}
+
+uint32_t clang::CodeGen::createRISCVCallSiteLpadTypeId(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ const FunctionDecl *FD) {
+ return computeRISCVLpadLabel(
+ llvm::StringRef(getRISCVLpadSignatureString(Ctx, MC, FD)));
+}
+
+uint32_t clang::CodeGen::createRISCVLpadTypeId(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ QualType Ty,
+ SourceLocation Loc) {
+ return computeRISCVLpadLabel(
+ llvm::StringRef(getRISCVLpadSignatureString(Ctx, MC, Ty, Loc)));
+}
+
+static bool isWCharT(QualType T) {
+ if (const auto *BT = T->getAs<BuiltinType>())
+ return BT->getKind() == BuiltinType::WChar_S ||
+ BT->getKind() == BuiltinType::WChar_U;
+ return false;
+}
+
+static TemplateArgScanResult
+combineTemplateArgScanResults(TemplateArgScanResult LHS,
+ TemplateArgScanResult RHS) {
+ // Precedence below is an arbitrary but deterministic tie-break for
+ // inputs triggering more than one condition; only one diagnostic can
+ // be reported per call.
+ if (LHS == TemplateArgScanResult::ContainsWCharT ||
+ RHS == TemplateArgScanResult::ContainsWCharT)
+ return TemplateArgScanResult::ContainsWCharT;
+ if (LHS == TemplateArgScanResult::ContainsExceptionSpec ||
+ RHS == TemplateArgScanResult::ContainsExceptionSpec)
+ return TemplateArgScanResult::ContainsExceptionSpec;
+ if (LHS == TemplateArgScanResult::Unsupported ||
+ RHS == TemplateArgScanResult::Unsupported)
+ return TemplateArgScanResult::Unsupported;
+ return TemplateArgScanResult::Safe;
+}
+
+static TemplateArgScanResult
+scanTemplateArgumentForWCharT(const TemplateArgument &Arg);
+
+// Looks through sugar via getAsCXXRecordDecl() rather than matching a
+// specific Type subclass, so this is robust regardless of which sugar
+// node (TemplateSpecializationType/ElaboratedType/RecordType) the AST
+// actually uses for a given specialization.
+static TemplateArgScanResult
+scanTypeForWCharTInTemplateArgs(QualType T, bool WithinTemplateArgs = false) {
+ if (WithinTemplateArgs && isWCharT(T))
+ return TemplateArgScanResult::ContainsWCharT;
+ if (const auto *RD = T->getAsCXXRecordDecl()) {
+ if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
+ TemplateArgScanResult Result = TemplateArgScanResult::Safe;
+
+ for (const TemplateArgument &Arg : Spec->getTemplateArgs().asArray()) {
+ Result = combineTemplateArgScanResults(
+ Result, scanTemplateArgumentForWCharT(Arg));
+ // ContainsWCharT outranks all other results; no need to keep going if
+ // found.
+ if (Result == TemplateArgScanResult::ContainsWCharT)
+ return Result;
+ }
+
+ if (Result != TemplateArgScanResult::Safe)
+ return Result;
+ }
+ }
+ // Mirrors a subset of SignatureNormalizer's own structural recursion --
+ // if SignatureNormalizer gains a new recursive case, update this too.
+ if (const auto *PT = T->getAs<PointerType>())
+ return scanTypeForWCharTInTemplateArgs(PT->getPointeeType(),
+ WithinTemplateArgs);
+ if (const auto *RT = T->getAs<ReferenceType>())
+ return scanTypeForWCharTInTemplateArgs(RT->getPointeeType(),
+ WithinTemplateArgs);
+ if (const auto *AT = T->getAsArrayTypeUnsafe())
+ return scanTypeForWCharTInTemplateArgs(AT->getElementType(),
+ WithinTemplateArgs);
+ if (const auto *FPT = T->getAs<FunctionProtoType>()) {
+ TemplateArgScanResult Result = TemplateArgScanResult::Safe;
+
+ if (WithinTemplateArgs && FPT->hasExceptionSpec()) {
+ Result = TemplateArgScanResult::ContainsExceptionSpec;
+ }
+
+ Result = combineTemplateArgScanResults(
+ Result, scanTypeForWCharTInTemplateArgs(FPT->getReturnType(),
+ WithinTemplateArgs));
+ for (QualType ParamTy : FPT->getParamTypes())
+ Result = combineTemplateArgScanResults(
+ Result, scanTypeForWCharTInTemplateArgs(ParamTy, WithinTemplateArgs));
+ return Result;
+ }
+
+ if (const auto *FNPT = T->getAs<FunctionNoProtoType>())
+ return scanTypeForWCharTInTemplateArgs(FNPT->getReturnType(),
+ WithinTemplateArgs);
+
+ if (const auto *MPT = T->getAs<MemberPointerType>())
+ return scanTypeForWCharTInTemplateArgs(MPT->getPointeeType(),
+ WithinTemplateArgs);
+
+ if (const auto *BPT = T->getAs<BlockPointerType>())
+ return scanTypeForWCharTInTemplateArgs(BPT->getPointeeType(),
+ WithinTemplateArgs);
+
+ if (const auto *PT = dyn_cast<ParenType>(T.getTypePtr()))
+ return scanTypeForWCharTInTemplateArgs(PT->getInnerType(),
+ WithinTemplateArgs);
+
+ if (const auto *TT = dyn_cast<TypedefType>(T.getTypePtr()))
+ return scanTypeForWCharTInTemplateArgs(TT->desugar(), WithinTemplateArgs);
+
+ return TemplateArgScanResult::Safe;
+}
+
+static TemplateArgScanResult
+scanTemplateArgumentForWCharT(const TemplateArgument &Arg) {
+ switch (Arg.getKind()) {
+ case TemplateArgument::Type:
+ return scanTypeForWCharTInTemplateArgs(Arg.getAsType(),
+ /*WithinTemplateArgument=*/true);
+
+ case TemplateArgument::Integral:
+ return scanTypeForWCharTInTemplateArgs(Arg.getIntegralType(),
+ /*WithinTemplateArgument=*/true);
+
+ case TemplateArgument::NullPtr:
+ return scanTypeForWCharTInTemplateArgs(Arg.getNullPtrType(),
+ /*WithinTemplateArgument=*/true);
+
+ case TemplateArgument::Pack: {
+ TemplateArgScanResult Result = TemplateArgScanResult::Safe;
+ for (const TemplateArgument &Element : Arg.pack_elements()) {
+ Result = combineTemplateArgScanResults(
+ Result, scanTemplateArgumentForWCharT(Element));
+ }
+ return Result;
+ }
+
+ case TemplateArgument::Null:
+ return TemplateArgScanResult::Safe;
+
+ case TemplateArgument::Expression:
+ case TemplateArgument::Declaration:
+ case TemplateArgument::Template:
+ case TemplateArgument::TemplateExpansion:
+ case TemplateArgument::StructuralValue:
+ return TemplateArgScanResult::Unsupported;
+ }
+ llvm_unreachable("unknown TemplateArgument kind");
+}
+
+QualType clang::CodeGen::getRISCVLpadCanonicalSignature(ASTContext &Ctx,
+ QualType Ty,
+ SourceLocation Loc) {
+ TemplateArgScanResult ScanResult =
+ scanTypeForWCharTInTemplateArgs(Ty,
+ /*WithinTemplateArgument=*/false);
+
+ unsigned UnsupportedTemplateArgDiagID = Ctx.getDiagnostics().getCustomDiagID(
+ DiagnosticsEngine::Error,
+ "RISC-V landing pad label generation does not yet support "
+ "this template argument form");
+
+ unsigned WCharTInTemplateArgDiagID = Ctx.getDiagnostics().getCustomDiagID(
+ DiagnosticsEngine::Error,
+ "RISC-V landing pad label generation does not yet support "
+ "template arguments containing wchar_t");
+
+ unsigned ExceptionSpecTInTemplateArgDiagID =
+ Ctx.getDiagnostics().getCustomDiagID(
+ DiagnosticsEngine::Error,
+ "RISC-V landing pad label generation does not yet support "
+ "template arguments containing exception spec");
+
+ switch (ScanResult) {
+ case TemplateArgScanResult::Safe:
+ break;
+
+ case TemplateArgScanResult::ContainsWCharT:
+ Ctx.getDiagnostics().Report(Loc, WCharTInTemplateArgDiagID);
+ break;
+
+ case TemplateArgScanResult::ContainsExceptionSpec:
+ Ctx.getDiagnostics().Report(Loc, ExceptionSpecTInTemplateArgDiagID);
+ break;
+
+ case TemplateArgScanResult::Unsupported:
+ Ctx.getDiagnostics().Report(Loc, UnsupportedTemplateArgDiagID);
+ break;
+ }
+
+ SignatureNormalizer Normalizer(Ctx);
+
+ if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
+ QualType VType = getSyntheticVType(Ctx);
+
+ QualType PointeeTy =
+ Normalizer.Visit(MPT->getPointeeType()); // generic, recursive
+ PointeeTy =
+ substituteCovariantReturn(Ctx, PointeeTy); // narrow, top-level only
+
+ return Ctx.getMemberPointerType(PointeeTy, std::nullopt,
+ VType->getAsCXXRecordDecl());
+ }
+
+ return Normalizer.Visit(Ty);
+}
+
+QualType clang::CodeGen::substituteCovariantReturn(ASTContext &Ctx,
+ QualType FnTy) {
+ const auto *FPT = FnTy->getAs<FunctionProtoType>();
+ if (!FPT)
+ return FnTy;
+
+ QualType Ret = FPT->getReturnType();
+ QualType NewRet = Ret;
+
+ if (const auto *PT = Ret->getAs<PointerType>()) {
+ if (PT->getPointeeType()->isRecordType())
+ NewRet = Ctx.getPointerType(Ctx.VoidTy);
+ } else if (const auto *RT = Ret->getAs<LValueReferenceType>()) {
+ if (RT->getPointeeType()->isRecordType())
+ NewRet = Ctx.getLValueReferenceType(Ctx.VoidTy);
+ } else if (const auto *RRT = Ret->getAs<RValueReferenceType>()) {
+ if (RRT->getPointeeType()->isRecordType())
+ NewRet = Ctx.getRValueReferenceType(Ctx.VoidTy);
+ }
+
+ if (NewRet == Ret)
+ return FnTy;
+ FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
+ return Ctx.getFunctionType(NewRet, FPT->getParamTypes(), EPI);
+}
+
+QualType clang::CodeGen::getSyntheticVType(ASTContext &Ctx) {
+ auto *RD = CXXRecordDecl::Create(
+ Ctx, TagTypeKind::Class, Ctx.getTranslationUnitDecl(), SourceLocation(),
+ SourceLocation(), &Ctx.Idents.get("v"));
+ RD->startDefinition();
+ RD->completeDefinition();
+ return Ctx.getTagType(ElaboratedTypeKeyword::None, std::nullopt, RD,
+ /*OwnsTag=*/false);
+}
\ No newline at end of file
diff --git a/clang/lib/CodeGen/RISCVLpadLabelGen.h b/clang/lib/CodeGen/RISCVLpadLabelGen.h
new file mode 100644
index 00000000000000..b0fa604df436a4
--- /dev/null
+++ b/clang/lib/CodeGen/RISCVLpadLabelGen.h
@@ -0,0 +1,73 @@
+//==---- RISCVLpadLabelGen.h - generates func-sig labels for landing pads --==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Computes RISC-V zicfilp landing-pad labels for the psABI "func-sig"
+/// scheme, deriving each label from a function's mangled signature.
+/// Shared by function definitions and indirect call sites so their
+/// labels agree.
+///
+//===----------------------------------------------------------------------===//
+#ifndef CLANG_LIB_CODEGEN_RISCV_LPADLABELGEN_H
+#define CLANG_LIB_CODEGEN_RISCV_LPADLABELGEN_H
+
+#include "clang/AST/Type.h"
+#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MD5.h"
+#include <cstdint>
+#include <string>
+
+namespace clang {
+class ASTContext;
+class ItaniumMangleContext;
+class FunctionDecl;
+
+namespace CodeGen {
+
+std::string getRISCVLpadSignatureString(ASTContext &Ctx,
+ ItaniumMangleContext &MC, QualType Ty,
+ SourceLocation Loc = SourceLocation());
+std::string getRISCVLpadSignatureString(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ const FunctionDecl *FD);
+
+uint32_t computeRISCVLpadLabel(const llvm::MD5::MD5Result &Result);
+
+uint32_t computeRISCVLpadLabel(llvm::StringRef Str);
+
+QualType buildBlockCopyHelperSigTy(ASTContext &Ctx);
+
+QualType buildDtorSigTy(ASTContext &Ctx);
+
+QualType buildVoidPtrToVoidPtrSigTy(ASTContext &Ctx);
+
+/// Generate a 20-bit type identifier for riscv landing pad labels.
+/// Entry point when a Decl is known, to compute the function entry label.
+uint32_t createRISCVEntryLpadTypeId(ASTContext &Ctx, ItaniumMangleContext &MC,
+ const FunctionDecl *FD);
+
+/// Generate a 20-bit type identifier for riscv landing pad labels.
+/// Entry point when a Decl is known, to compute the callsite label.
+uint32_t createRISCVCallSiteLpadTypeId(ASTContext &Ctx,
+ ItaniumMangleContext &MC,
+ const FunctionDecl *FD);
+
+/// Generate a 20-bit type identifier for riscv landing pad labels.
+/// Canonical/structural entry point. Used directly for indirect calls with
+/// no resolvable Decl, and internally by the FunctionDecl overload after
+/// Decl-only special cases are resolved. This is the single source of
+/// truth for the actual mangling + hashing.
+uint32_t createRISCVLpadTypeId(ASTContext &Ctx, ItaniumMangleContext &MC,
+ QualType Ty,
+ SourceLocation Loc = SourceLocation());
+
+} // namespace CodeGen
+} // namespace clang
+
+#endif
diff --git a/clang/test/CodeGen/RISCV/riscv-cf-protection.c b/clang/test/CodeGen/RISCV/riscv-cf-protection.c
index f957890cd9f6f4..c25804de420212 100644
--- a/clang/test/CodeGen/RISCV/riscv-cf-protection.c
+++ b/clang/test/CodeGen/RISCV/riscv-cf-protection.c
@@ -3,10 +3,10 @@
// RUN: -mcf-branch-label-scheme=unlabeled -S -emit-llvm %s -o - | FileCheck \
// RUN: --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
-// RUN: not %clang --target=riscv32 -menable-experimental-extensions \
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
// RUN: -march=rv32i_zicfilp1p0 -fcf-protection=branch \
-// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - 2>&1 | \
-// RUN: FileCheck --check-prefixes=FUNC-SIG-NOSUPPORT %s
+// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - | FileCheck \
+// RUN: --check-prefixes=BRANCH-PROT-FLAG,FUNC-SIG-FLAG %s
// RUN: %clang --target=riscv32 -menable-experimental-extensions \
// RUN: -march=rv32i_zicfilp1p0 -mcf-branch-label-scheme=unlabeled -S \
@@ -22,9 +22,9 @@
// RUN: -mcf-branch-label-scheme=unlabeled -S -emit-llvm %s -o - | FileCheck \
// RUN: --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
-// RUN: not %clang --target=riscv32 -fcf-protection=branch \
-// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - 2>&1 | \
-// RUN: FileCheck --check-prefixes=FUNC-SIG-NOSUPPORT %s
+// RUN: %clang --target=riscv32 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - | FileCheck \
+// RUN: --check-prefixes=BRANCH-PROT-FLAG,FUNC-SIG-FLAG %s
// RUN: %clang --target=riscv32 -mcf-branch-label-scheme=unlabeled -S \
// RUN: -emit-llvm %s -o - 2>&1 | FileCheck \
@@ -39,10 +39,10 @@
// RUN: -mcf-branch-label-scheme=unlabeled -S -emit-llvm %s -o - | FileCheck \
// RUN: --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
-// RUN: not %clang --target=riscv64 -menable-experimental-extensions \
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
// RUN: -march=rv64i_zicfilp1p0 -fcf-protection=branch \
-// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - 2>&1 | \
-// RUN: FileCheck --check-prefixes=FUNC-SIG-NOSUPPORT %s
+// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - | FileCheck \
+// RUN: --check-prefixes=BRANCH-PROT-FLAG,FUNC-SIG-FLAG %s
// RUN: %clang --target=riscv64 -menable-experimental-extensions \
// RUN: -march=rv64i_zicfilp1p0 -mcf-branch-label-scheme=unlabeled -S \
@@ -58,9 +58,9 @@
// RUN: -mcf-branch-label-scheme=unlabeled -S -emit-llvm %s -o - | FileCheck \
// RUN: --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
-// RUN: not %clang --target=riscv64 -fcf-protection=branch \
-// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - 2>&1 | \
-// RUN: FileCheck --check-prefixes=FUNC-SIG-NOSUPPORT %s
+// RUN: %clang --target=riscv64 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -S -emit-llvm %s -o - | FileCheck \
+// RUN: --check-prefixes=BRANCH-PROT-FLAG,FUNC-SIG-FLAG %s
// RUN: %clang --target=riscv64 -mcf-branch-label-scheme=unlabeled -S \
// RUN: -emit-llvm %s -o - 2>&1 | FileCheck \
@@ -70,15 +70,22 @@
// RUN: -emit-llvm %s -o - 2>&1 | FileCheck \
// RUN: --check-prefixes=NO-FLAG,FUNC-SIG-SCHEME-UNUSED %s
+// Default -mcf-branch-label-scheme is func-sig
+// RUN: %clang --target=riscv32 -fcf-protection=branch -S -emit-llvm %s \
+// RUN: -o - | FileCheck --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
+
+// Default -mcf-branch-label-scheme is func-sig
+// RUN: %clang --target=riscv64 -fcf-protection=branch -S -emit-llvm %s \
+// RUN: -o - | FileCheck --check-prefixes=BRANCH-PROT-FLAG,UNLABELED-FLAG %s
+
// UNLABELED-SCHEME-UNUSED: warning: argument unused during compilation:
// UNLABELED-SCHEME-UNUSED-SAME: '-mcf-branch-label-scheme=unlabeled'
// FUNC-SIG-SCHEME-UNUSED: warning: argument unused during compilation:
// FUNC-SIG-SCHEME-UNUSED-SAME: '-mcf-branch-label-scheme=func-sig'
-// FUNC-SIG-NOSUPPORT: error: option '-mcf-branch-label-scheme=func-sig' is
-// FUNC-SIG-NOSUPPORT-SAME: unsupported; consider using '-mcf-branch-label-scheme=unlabeled'
// BRANCH-PROT-FLAG-DAG: [[P_FLAG:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
// UNLABELED-FLAG-DAG: [[S_FLAG:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"unlabeled"}
+// FUNC-SIG-FLAG-DAG: [[S_FLAG:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
// BRANCH-PROT-FLAG-DAG: !llvm.module.flags = !{{[{].*}}[[P_FLAG]]{{.*, }}[[S_FLAG]]{{(,.+)?[}]}}
// NO-FLAG-NOT: !{i32 8, !"cf-protection-branch", i32 1}
// NO-FLAG-NOT: !{i32 8, !"cf-branch-label-scheme", !"unlabeled"}
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-block-call.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-block-call.cpp
new file mode 100644
index 00000000000000..3e5209fe19e637
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-block-call.cpp
@@ -0,0 +1,89 @@
+// Checks in this test were originally generated by
+// utils/update_cc_test_checks.py, but have been manually
+// edited. Do not autogenerate checks.
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fblocks -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV32
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fblocks -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV64
+
+// The two label values captured below are intentionally
+// captured/reused via FileCheck's [[NAME:PATTERN]]/[[NAME]]
+// syntax: the block invoke function's cfi_type_hash entry
+// label and the indirect block call's !riscv_lpad_label value
+// must be equal.
+
+typedef void (^BlockTy)(int);
+//.
+// RV32: @_NSConcreteGlobalBlock = external global ptr
+// RV32: @.str = private unnamed_addr constant [8 x i8] c"v8@?0i4\00", align 1
+// RV32: @__block_descriptor_tmp = internal constant { i32, i32, ptr, ptr } { i32 0, i32 20, ptr @.str, ptr null }, align 4
+// RV32: @__block_literal_global = internal constant { ptr, i32, i32, ptr, ptr } { ptr @_NSConcreteGlobalBlock, i32 1342177280, i32 0, ptr @___Z4testv_block_invoke, ptr @__block_descriptor_tmp }, align 4 #0
+//.
+// RV64: @_NSConcreteGlobalBlock = external global ptr
+// RV64: @.str = private unnamed_addr constant [9 x i8] c"v12@?0i8\00", align 1
+// RV64: @__block_descriptor_tmp = internal constant { i64, i64, ptr, ptr } { i64 0, i64 32, ptr @.str, ptr null }, align 8
+// RV64: @__block_literal_global = internal constant { ptr, i32, i32, ptr, ptr } { ptr @_NSConcreteGlobalBlock, i32 1342177280, i32 0, ptr @___Z4testv_block_invoke, ptr @__block_descriptor_tmp }, align 8 #0
+//.
+// RV32: Function Attrs: mustprogress noinline nounwind optnone
+// RV32-LABEL: define dso_local void @_Z4testv(
+// RV32-SAME: ) #[[ATTR1:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[B:%.*]] = alloca ptr, align 4
+// RV32-NEXT: store ptr @__block_literal_global, ptr [[B]], align 4
+// RV32-NEXT: [[TMP0:%.*]] = load ptr, ptr [[B]], align 4
+// RV32-NEXT: [[TMP1:%.*]] = getelementptr inbounds nuw [[STRUCT___BLOCK_LITERAL_GENERIC:%.*]], ptr [[TMP0]], i32 0, i32 3
+// RV32-NEXT: [[TMP2:%.*]] = load ptr, ptr [[TMP1]], align 4
+// RV32-NEXT: call void [[TMP2]](ptr noundef [[TMP0]], i32 noundef 1), !riscv_lpad_label [[META7:![0-9]+]]
+// RV32-NEXT: ret void
+//
+// RV64: Function Attrs: mustprogress noinline nounwind optnone
+// RV64-LABEL: define dso_local void @_Z4testv(
+// RV64-SAME: ) #[[ATTR1:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[B:%.*]] = alloca ptr, align 8
+// RV64-NEXT: store ptr @__block_literal_global, ptr [[B]], align 8
+// RV64-NEXT: [[TMP0:%.*]] = load ptr, ptr [[B]], align 8
+// RV64-NEXT: [[TMP1:%.*]] = getelementptr inbounds nuw [[STRUCT___BLOCK_LITERAL_GENERIC:%.*]], ptr [[TMP0]], i32 0, i32 3
+// RV64-NEXT: [[TMP2:%.*]] = load ptr, ptr [[TMP1]], align 8
+// RV64-NEXT: call void [[TMP2]](ptr noundef [[TMP0]], i32 noundef signext 1), !riscv_lpad_label [[META7:![0-9]+]]
+// RV64-NEXT: ret void
+//
+void test(void) {
+ BlockTy b = ^(int x) {
+ (void)x;
+ };
+ b(1);
+}
+//.
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define internal void @___Z4testv_block_invoke(
+// RV32-SAME: #[[ATTR2:[0-9]+]]
+// RV32: attributes #[[ATTR0:[0-9]+]] = { "objc_arc_inert" }
+// RV32: attributes #[[ATTR1]] = { mustprogress noinline nounwind optnone "cfi_type_hash"="308871" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32-DAG: attributes #[[ATTR2]] = { noinline nounwind optnone "cfi_type_hash"="[[RV32_LABEL:[0-9]+]]"{{.*}} }
+//.
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define internal void @___Z4testv_block_invoke(
+// RV64-SAME: #[[ATTR2:[0-9]+]]
+// RV64: attributes #[[ATTR0:[0-9]+]] = { "objc_arc_inert" }
+// RV64: attributes #[[ATTR1]] = { mustprogress noinline nounwind optnone "cfi_type_hash"="308871" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-DAG: attributes #[[ATTR2]] = { noinline nounwind optnone "cfi_type_hash"="[[RV64_LABEL:[0-9]+]]"{{.*}} }
+//.
+// RV32: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"ilp32"}
+// RV32: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV32: [[META2]] = !{!"rv32i2p1"}
+// RV32: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV32: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV32: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV32: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+// RV32-DAG: [[META7]] = !{i32 [[RV32_LABEL]]}
+//.
+// RV64: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64: [[META2]] = !{!"rv64i2p1"}
+// RV64: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+// RV64-DAG: [[META7]] = !{i32 [[RV64_LABEL]]}
+//.
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-member-pointers.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-member-pointers.cpp
new file mode 100644
index 00000000000000..26a74b209eeebb
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-member-pointers.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s
+
+class Base {
+public:
+ void nonvirtual_method(int);
+ virtual void virtual_method(int);
+};
+class Derived : public Base {
+public:
+ void virtual_method(int) override;
+};
+
+void call_nonvirtual(Base *b, void (Base::*pm)(int), int x) { (b->*pm)(x); }
+void call_virtual(Base *b, void (Base::*pm)(int), int x) { (b->*pm)(x); }
+
+void call_converted(Derived *d, int x) {
+ void (Base::*pm_base)(int) = &Base::virtual_method;
+ void (Derived::*pm_derived)(int) = pm_base; // valid Base::* -> Derived::* conversion
+ (d->*pm_derived)(x); // dispatches to Derived::virtual_method at runtime
+}
+
+void (Base::*global_pm)(int) = &Base::nonvirtual_method;
+void call_through_variable(Base *b, int x) { (b->*global_pm)(x); }
+
+// CHECK-COUNT-4: !riscv_lpad_label [[LABEL:![0-9]+]]
+// CHECK: [[LABEL]] = !{i32 {{[1-9][0-9]*}}}
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-virtual-call.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-virtual-call.cpp
new file mode 100644
index 00000000000000..18e215a4bdac0f
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-cpp-virtual-call.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s
+
+class Base {
+public:
+ virtual void f(int);
+};
+void call_virtual_dispatch(Base *b, int x) {
+ b->f(x);
+}
+// CHECK: !riscv_lpad_label [[LABEL:![0-9]+]]
+// CHECK: [[LABEL]] = !{i32 {{[1-9][0-9]*}}}
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr-noargs.c b/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr-noargs.c
new file mode 100644
index 00000000000000..1ccfcffb9549e5
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr-noargs.c
@@ -0,0 +1,64 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-attributes --check-globals all --version 6
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV32
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV64
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig -mcmodel=large %s -o - | FileCheck %s --check-prefix=RV64-LARGE
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local i32 @main(
+// RV32-SAME: ) #[[ATTR0:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV32-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV32-NEXT: ret i32 0
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local signext i32 @main(
+// RV64-SAME: ) #[[ATTR0:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV64-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV64-NEXT: ret i32 0
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local signext i32 @main(
+// RV64-LARGE-SAME: ) #[[ATTR0:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV64-LARGE-NEXT: ret i32 0
+//
+int main() {
+ return 0;
+}
+//.
+// RV32: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+//.
+// RV64: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV64-LARGE: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV32: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"ilp32"}
+// RV32: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV32: [[META2]] = !{!"rv32i2p1"}
+// RV32: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV32: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV32: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV32: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
+// RV64: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64: [[META2]] = !{!"rv64i2p1"}
+// RV64: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
+// RV64-LARGE: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64-LARGE: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64-LARGE: [[META2]] = !{!"rv64i2p1"}
+// RV64-LARGE: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64-LARGE: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64-LARGE: [[META5:![0-9]+]] = !{i32 1, !"Code Model", i32 4}
+// RV64-LARGE: [[META6:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64-LARGE: [[META7:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr.c b/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr.c
new file mode 100644
index 00000000000000..cf6611e3fe4d74
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-main-attr.c
@@ -0,0 +1,76 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-attributes --check-globals all --version 6
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV32
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV64
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig -mcmodel=large %s -o - | FileCheck %s --check-prefix=RV64-LARGE
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local i32 @main(
+// RV32-SAME: i32 noundef [[ARGC:%.*]], ptr noundef [[ARGV:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[ARGC_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[ARGV_ADDR:%.*]] = alloca ptr, align 4
+// RV32-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV32-NEXT: store i32 [[ARGC]], ptr [[ARGC_ADDR]], align 4
+// RV32-NEXT: store ptr [[ARGV]], ptr [[ARGV_ADDR]], align 4
+// RV32-NEXT: ret i32 0
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local signext i32 @main(
+// RV64-SAME: i32 noundef signext [[ARGC:%.*]], ptr noundef [[ARGV:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[ARGC_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[ARGV_ADDR:%.*]] = alloca ptr, align 8
+// RV64-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV64-NEXT: store i32 [[ARGC]], ptr [[ARGC_ADDR]], align 4
+// RV64-NEXT: store ptr [[ARGV]], ptr [[ARGV_ADDR]], align 8
+// RV64-NEXT: ret i32 0
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local signext i32 @main(
+// RV64-LARGE-SAME: i32 noundef signext [[ARGC:%.*]], ptr noundef [[ARGV:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[RETVAL:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[ARGC_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[ARGV_ADDR:%.*]] = alloca ptr, align 8
+// RV64-LARGE-NEXT: store i32 0, ptr [[RETVAL]], align 4
+// RV64-LARGE-NEXT: store i32 [[ARGC]], ptr [[ARGC_ADDR]], align 4
+// RV64-LARGE-NEXT: store ptr [[ARGV]], ptr [[ARGV_ADDR]], align 8
+// RV64-LARGE-NEXT: ret i32 0
+//
+int main(int argc, char **argv) {
+ return 0;
+}
+//.
+// RV32: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+//.
+// RV64: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV64-LARGE: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="853561" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV32: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"ilp32"}
+// RV32: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV32: [[META2]] = !{!"rv32i2p1"}
+// RV32: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV32: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV32: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV32: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
+// RV64: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64: [[META2]] = !{!"rv64i2p1"}
+// RV64: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
+// RV64-LARGE: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64-LARGE: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64-LARGE: [[META2]] = !{!"rv64i2p1"}
+// RV64-LARGE: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64-LARGE: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64-LARGE: [[META5:![0-9]+]] = !{i32 1, !"Code Model", i32 4}
+// RV64-LARGE: [[META6:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64-LARGE: [[META7:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+//.
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-metadata.c b/clang/test/CodeGen/RISCV/riscv-zicfilp-metadata.c
new file mode 100644
index 00000000000000..0c3f4d448a6815
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-metadata.c
@@ -0,0 +1,262 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-attributes --check-globals all --version 6
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV32
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s --check-prefix=RV64
+// RUN: %clang_cc1 -triple riscv64 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig -mcmodel=large %s -o - | FileCheck %s --check-prefix=RV64-LARGE
+// test Metadata generation for the zicfilp func-sig label scheme. These are the same test cases from the backend "calls-cf-branch-func-sig.ll" test.
+
+extern int external_function(int a);
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local i32 @test_call_external(
+// RV32-SAME: i32 noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: store i32 [[A]], ptr [[A_ADDR]], align 4
+// RV32-NEXT: [[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
+// RV32-NEXT: [[CALL:%.*]] = call i32 @external_function(i32 noundef [[TMP0]])
+// RV32-NEXT: ret i32 [[CALL]]
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local signext i32 @test_call_external(
+// RV64-SAME: i32 noundef signext [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: store i32 [[A]], ptr [[A_ADDR]], align 4
+// RV64-NEXT: [[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
+// RV64-NEXT: [[CALL:%.*]] = call signext i32 @external_function(i32 noundef signext [[TMP0]])
+// RV64-NEXT: ret i32 [[CALL]]
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local signext i32 @test_call_external(
+// RV64-LARGE-SAME: i32 noundef signext [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: store i32 [[A]], ptr [[A_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
+// RV64-LARGE-NEXT: [[CALL:%.*]] = call signext i32 @external_function(i32 noundef signext [[TMP0]])
+// RV64-LARGE-NEXT: ret i32 [[CALL]]
+//
+int test_call_external(int a) {
+ return external_function(a);
+}
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local i32 @test_call_indirect(
+// RV32-SAME: ptr noundef [[A:%.*]], i32 noundef [[B:%.*]]) #[[ATTR2:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 4
+// RV32-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 4
+// RV32-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV32-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 4
+// RV32-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV32-NEXT: [[CALL:%.*]] = call i32 [[TMP0]](i32 noundef [[TMP1]]), !riscv_lpad_label [[META7:![0-9]+]]
+// RV32-NEXT: ret i32 [[CALL]]
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local signext i32 @test_call_indirect(
+// RV64-SAME: ptr noundef [[A:%.*]], i32 noundef signext [[B:%.*]]) #[[ATTR2:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 8
+// RV64-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 8
+// RV64-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV64-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// RV64-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV64-NEXT: [[CALL:%.*]] = call signext i32 [[TMP0]](i32 noundef signext [[TMP1]]), !riscv_lpad_label [[META7:![0-9]+]]
+// RV64-NEXT: ret i32 [[CALL]]
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local signext i32 @test_call_indirect(
+// RV64-LARGE-SAME: ptr noundef [[A:%.*]], i32 noundef signext [[B:%.*]]) #[[ATTR2:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 8
+// RV64-LARGE-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 8
+// RV64-LARGE-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// RV64-LARGE-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV64-LARGE-NEXT: [[CALL:%.*]] = call signext i32 [[TMP0]](i32 noundef signext [[TMP1]]), !riscv_lpad_label [[META8:![0-9]+]]
+// RV64-LARGE-NEXT: ret i32 [[CALL]]
+//
+int test_call_indirect(int (*a)(int), int b) {
+ return a(b);
+}
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local i32 @test_call_indirect_no_t0(
+// RV32-SAME: ptr noundef [[A:%.*]], i32 noundef [[B:%.*]], i32 noundef [[C:%.*]], i32 noundef [[D:%.*]], i32 noundef [[E:%.*]], i32 noundef [[F:%.*]], i32 noundef [[G:%.*]], i32 noundef [[H:%.*]]) #[[ATTR3:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 4
+// RV32-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[C_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[D_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[E_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[F_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[G_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: [[H_ADDR:%.*]] = alloca i32, align 4
+// RV32-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 4
+// RV32-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV32-NEXT: store i32 [[C]], ptr [[C_ADDR]], align 4
+// RV32-NEXT: store i32 [[D]], ptr [[D_ADDR]], align 4
+// RV32-NEXT: store i32 [[E]], ptr [[E_ADDR]], align 4
+// RV32-NEXT: store i32 [[F]], ptr [[F_ADDR]], align 4
+// RV32-NEXT: store i32 [[G]], ptr [[G_ADDR]], align 4
+// RV32-NEXT: store i32 [[H]], ptr [[H_ADDR]], align 4
+// RV32-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 4
+// RV32-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV32-NEXT: [[TMP2:%.*]] = load i32, ptr [[C_ADDR]], align 4
+// RV32-NEXT: [[TMP3:%.*]] = load i32, ptr [[D_ADDR]], align 4
+// RV32-NEXT: [[TMP4:%.*]] = load i32, ptr [[E_ADDR]], align 4
+// RV32-NEXT: [[TMP5:%.*]] = load i32, ptr [[F_ADDR]], align 4
+// RV32-NEXT: [[TMP6:%.*]] = load i32, ptr [[G_ADDR]], align 4
+// RV32-NEXT: [[TMP7:%.*]] = load i32, ptr [[H_ADDR]], align 4
+// RV32-NEXT: [[CALL:%.*]] = call i32 [[TMP0]](i32 noundef [[TMP1]], i32 noundef [[TMP2]], i32 noundef [[TMP3]], i32 noundef [[TMP4]], i32 noundef [[TMP5]], i32 noundef [[TMP6]], i32 noundef [[TMP7]]), !riscv_lpad_label [[META8:![0-9]+]]
+// RV32-NEXT: ret i32 [[CALL]]
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local signext i32 @test_call_indirect_no_t0(
+// RV64-SAME: ptr noundef [[A:%.*]], i32 noundef signext [[B:%.*]], i32 noundef signext [[C:%.*]], i32 noundef signext [[D:%.*]], i32 noundef signext [[E:%.*]], i32 noundef signext [[F:%.*]], i32 noundef signext [[G:%.*]], i32 noundef signext [[H:%.*]]) #[[ATTR3:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 8
+// RV64-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[C_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[D_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[E_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[F_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[G_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: [[H_ADDR:%.*]] = alloca i32, align 4
+// RV64-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 8
+// RV64-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV64-NEXT: store i32 [[C]], ptr [[C_ADDR]], align 4
+// RV64-NEXT: store i32 [[D]], ptr [[D_ADDR]], align 4
+// RV64-NEXT: store i32 [[E]], ptr [[E_ADDR]], align 4
+// RV64-NEXT: store i32 [[F]], ptr [[F_ADDR]], align 4
+// RV64-NEXT: store i32 [[G]], ptr [[G_ADDR]], align 4
+// RV64-NEXT: store i32 [[H]], ptr [[H_ADDR]], align 4
+// RV64-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// RV64-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV64-NEXT: [[TMP2:%.*]] = load i32, ptr [[C_ADDR]], align 4
+// RV64-NEXT: [[TMP3:%.*]] = load i32, ptr [[D_ADDR]], align 4
+// RV64-NEXT: [[TMP4:%.*]] = load i32, ptr [[E_ADDR]], align 4
+// RV64-NEXT: [[TMP5:%.*]] = load i32, ptr [[F_ADDR]], align 4
+// RV64-NEXT: [[TMP6:%.*]] = load i32, ptr [[G_ADDR]], align 4
+// RV64-NEXT: [[TMP7:%.*]] = load i32, ptr [[H_ADDR]], align 4
+// RV64-NEXT: [[CALL:%.*]] = call signext i32 [[TMP0]](i32 noundef signext [[TMP1]], i32 noundef signext [[TMP2]], i32 noundef signext [[TMP3]], i32 noundef signext [[TMP4]], i32 noundef signext [[TMP5]], i32 noundef signext [[TMP6]], i32 noundef signext [[TMP7]]), !riscv_lpad_label [[META8:![0-9]+]]
+// RV64-NEXT: ret i32 [[CALL]]
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local signext i32 @test_call_indirect_no_t0(
+// RV64-LARGE-SAME: ptr noundef [[A:%.*]], i32 noundef signext [[B:%.*]], i32 noundef signext [[C:%.*]], i32 noundef signext [[D:%.*]], i32 noundef signext [[E:%.*]], i32 noundef signext [[F:%.*]], i32 noundef signext [[G:%.*]], i32 noundef signext [[H:%.*]]) #[[ATTR3:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[A_ADDR:%.*]] = alloca ptr, align 8
+// RV64-LARGE-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[C_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[D_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[E_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[F_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[G_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: [[H_ADDR:%.*]] = alloca i32, align 4
+// RV64-LARGE-NEXT: store ptr [[A]], ptr [[A_ADDR]], align 8
+// RV64-LARGE-NEXT: store i32 [[B]], ptr [[B_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[C]], ptr [[C_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[D]], ptr [[D_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[E]], ptr [[E_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[F]], ptr [[F_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[G]], ptr [[G_ADDR]], align 4
+// RV64-LARGE-NEXT: store i32 [[H]], ptr [[H_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// RV64-LARGE-NEXT: [[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP2:%.*]] = load i32, ptr [[C_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP3:%.*]] = load i32, ptr [[D_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP4:%.*]] = load i32, ptr [[E_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP5:%.*]] = load i32, ptr [[F_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP6:%.*]] = load i32, ptr [[G_ADDR]], align 4
+// RV64-LARGE-NEXT: [[TMP7:%.*]] = load i32, ptr [[H_ADDR]], align 4
+// RV64-LARGE-NEXT: [[CALL:%.*]] = call signext i32 [[TMP0]](i32 noundef signext [[TMP1]], i32 noundef signext [[TMP2]], i32 noundef signext [[TMP3]], i32 noundef signext [[TMP4]], i32 noundef signext [[TMP5]], i32 noundef signext [[TMP6]], i32 noundef signext [[TMP7]]), !riscv_lpad_label [[META9:![0-9]+]]
+// RV64-LARGE-NEXT: ret i32 [[CALL]]
+//
+int test_call_indirect_no_t0(int (*a)(int, int, int, int, int, int, int),
+ int b, int c, int d, int e, int f, int g, int h) {
+ return a(b, c, d, e, f, g, h);
+}
+
+extern int external_many_args(int, int, int, int, int, int, int, int, int, int);
+
+// RV32: Function Attrs: noinline nounwind optnone
+// RV32-LABEL: define dso_local void @fastcc_call_nonfastcc(
+// RV32-SAME: ) #[[ATTR4:[0-9]+]] {
+// RV32-NEXT: [[ENTRY:.*:]]
+// RV32-NEXT: [[CALL:%.*]] = call i32 @external_many_args(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 noundef 4, i32 noundef 5, i32 noundef 6, i32 noundef 7, i32 noundef 8, i32 noundef 9, i32 noundef 10)
+// RV32-NEXT: ret void
+//
+// RV64: Function Attrs: noinline nounwind optnone
+// RV64-LABEL: define dso_local void @fastcc_call_nonfastcc(
+// RV64-SAME: ) #[[ATTR4:[0-9]+]] {
+// RV64-NEXT: [[ENTRY:.*:]]
+// RV64-NEXT: [[CALL:%.*]] = call signext i32 @external_many_args(i32 noundef signext 1, i32 noundef signext 2, i32 noundef signext 3, i32 noundef signext 4, i32 noundef signext 5, i32 noundef signext 6, i32 noundef signext 7, i32 noundef signext 8, i32 noundef signext 9, i32 noundef signext 10)
+// RV64-NEXT: ret void
+//
+// RV64-LARGE: Function Attrs: noinline nounwind optnone
+// RV64-LARGE-LABEL: define dso_local void @fastcc_call_nonfastcc(
+// RV64-LARGE-SAME: ) #[[ATTR4:[0-9]+]] {
+// RV64-LARGE-NEXT: [[ENTRY:.*:]]
+// RV64-LARGE-NEXT: [[CALL:%.*]] = call signext i32 @external_many_args(i32 noundef signext 1, i32 noundef signext 2, i32 noundef signext 3, i32 noundef signext 4, i32 noundef signext 5, i32 noundef signext 6, i32 noundef signext 7, i32 noundef signext 8, i32 noundef signext 9, i32 noundef signext 10)
+// RV64-LARGE-NEXT: ret void
+//
+void fastcc_call_nonfastcc() {
+ external_many_args(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+}
+//.
+// RV32: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32: attributes #[[ATTR1:[0-9]+]] = { "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32: attributes #[[ATTR2]] = { noinline nounwind optnone "cfi_type_hash"="187979" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32: attributes #[[ATTR3]] = { noinline nounwind optnone "cfi_type_hash"="391802" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32: attributes #[[ATTR4]] = { noinline nounwind optnone "cfi_type_hash"="308871" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+// RV32: attributes #[[ATTR5:[0-9]+]] = { "cfi_type_hash"="768796" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+32bit,+i" }
+//.
+// RV64: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64: attributes #[[ATTR1:[0-9]+]] = { "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64: attributes #[[ATTR2]] = { noinline nounwind optnone "cfi_type_hash"="187979" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64: attributes #[[ATTR3]] = { noinline nounwind optnone "cfi_type_hash"="391802" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64: attributes #[[ATTR4]] = { noinline nounwind optnone "cfi_type_hash"="308871" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64: attributes #[[ATTR5:[0-9]+]] = { "cfi_type_hash"="768796" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV64-LARGE: attributes #[[ATTR0]] = { noinline nounwind optnone "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-LARGE: attributes #[[ATTR1:[0-9]+]] = { "cfi_type_hash"="566246" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-LARGE: attributes #[[ATTR2]] = { noinline nounwind optnone "cfi_type_hash"="187979" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-LARGE: attributes #[[ATTR3]] = { noinline nounwind optnone "cfi_type_hash"="391802" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-LARGE: attributes #[[ATTR4]] = { noinline nounwind optnone "cfi_type_hash"="308871" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+// RV64-LARGE: attributes #[[ATTR5:[0-9]+]] = { "cfi_type_hash"="768796" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+64bit,+i" }
+//.
+// RV32: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"ilp32"}
+// RV32: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV32: [[META2]] = !{!"rv32i2p1"}
+// RV32: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV32: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV32: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV32: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+// RV32: [[META7]] = !{i32 566246}
+// RV32: [[META8]] = !{i32 631371}
+//.
+// RV64: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64: [[META2]] = !{!"rv64i2p1"}
+// RV64: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64: [[META5:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64: [[META6:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+// RV64: [[META7]] = !{i32 566246}
+// RV64: [[META8]] = !{i32 631371}
+//.
+// RV64-LARGE: [[META0:![0-9]+]] = !{i32 1, !"target-abi", !"lp64"}
+// RV64-LARGE: [[META1:![0-9]+]] = !{i32 6, !"riscv-isa", [[META2:![0-9]+]]}
+// RV64-LARGE: [[META2]] = !{!"rv64i2p1"}
+// RV64-LARGE: [[META3:![0-9]+]] = !{i32 8, !"cf-protection-branch", i32 1}
+// RV64-LARGE: [[META4:![0-9]+]] = !{i32 1, !"cf-branch-label-scheme", !"func-sig"}
+// RV64-LARGE: [[META5:![0-9]+]] = !{i32 1, !"Code Model", i32 4}
+// RV64-LARGE: [[META6:![0-9]+]] = !{i32 8, !"SmallDataLimit", i32 0}
+// RV64-LARGE: [[META7:![0-9]+]] = !{!"{{.*}}clang version {{.*}}"}
+// RV64-LARGE: [[META8]] = !{i32 566246}
+// RV64-LARGE: [[META9]] = !{i32 631371}
+//.
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-no-bypass.c b/clang/test/CodeGen/RISCV/riscv-zicfilp-no-bypass.c
new file mode 100644
index 00000000000000..b36a4c8bbfd396
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-no-bypass.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s
+// cfi-unchecked is for software CFI and should not disable zicfilp-related functionality.
+typedef void (*CB)(int) __attribute__((cfi_unchecked_callee));
+int test_unchecked_indirect(CB f, int x) {
+ f(x);
+ return 0;
+}
+// CHECK: call void %{{.*}}(i32 noundef %{{.*}}), !riscv_lpad_label [[LABEL:![0-9]+]]
+// CHECK: [[LABEL]] = !{i32 {{[1-9][0-9]*}}}
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-template-exceptionspec-unsupported.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-template-exceptionspec-unsupported.cpp
new file mode 100644
index 00000000000000..209cd996244be8
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-template-exceptionspec-unsupported.cpp
@@ -0,0 +1,20 @@
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/function-pointer.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/member-pointer.cpp
+
+//--- function-pointer.cpp
+template <typename T> struct Wrapper {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing exception spec}}
+void f(Wrapper<void (*)() noexcept>) {}
+
+//--- member-pointer.cpp
+template <typename T> struct Wrapper {};
+struct C {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing exception spec}}
+void f(Wrapper<void (C::*)() noexcept>) {}
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-template-wchart-unsupported.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-template-wchart-unsupported.cpp
new file mode 100644
index 00000000000000..16641d55164d50
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-template-wchart-unsupported.cpp
@@ -0,0 +1,66 @@
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/direct.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/nested.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/function-pointer.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/member-pointer.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -verify %t/integral.cpp
+// RUN: %clang_cc1 -triple riscv64 -std=c++17 -emit-llvm -o /dev/null \
+// RUN: -fcf-protection=branch -mcf-branch-label-scheme=func-sig \
+// RUN: -I %t -verify %t/declaration.cpp
+
+// wchar_t is supported in ordinary signature positions, where
+// SignatureNormalizer rewrites it to the target's underlying type.
+// It is currently unsupported within template arguments because template
+// specializations are not structurally rewritten before mangling.
+
+//--- direct.cpp
+template <typename T> struct Wrapper {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing wchar_t}}
+void f1(Wrapper<wchar_t>) {}
+
+//--- nested.cpp
+template <typename T> struct Wrapper {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing wchar_t}}
+void f2(Wrapper<Wrapper<wchar_t>>) {}
+
+//--- function-pointer.cpp
+template <typename T> struct Wrapper {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing wchar_t}}
+void f3(Wrapper<void (*)(wchar_t)>) {}
+
+//--- member-pointer.cpp
+template <typename T> struct Wrapper {};
+struct C {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing wchar_t}}
+void f4(Wrapper<void (C::*)(wchar_t)>) {}
+
+//--- integral.cpp
+template <wchar_t C> struct Character {};
+
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support template arguments containing wchar_t}}
+void f5(Character<L'x'>) {}
+
+//--- declaration.cpp
+template <auto Value>
+struct ValueWrapper {};
+
+void target(wchar_t);
+
+// Declaration-valued template arguments are conservatively unsupported.
+// The referenced function's mangled name encodes its wchar_t parameter type.
+// expected-error at +1 {{RISC-V landing pad label generation does not yet support this template argument form}}
+void f(ValueWrapper<&target>) {}
\ No newline at end of file
diff --git a/clang/test/CodeGen/RISCV/riscv-zicfilp-virtual-destructor.cpp b/clang/test/CodeGen/RISCV/riscv-zicfilp-virtual-destructor.cpp
new file mode 100644
index 00000000000000..44a3f2231b4135
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-zicfilp-virtual-destructor.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -triple riscv32 -emit-llvm -fcf-protection=branch -mcf-branch-label-scheme=func-sig %s -o - | FileCheck %s
+
+class Base {
+public:
+ virtual ~Base();
+};
+class Derived : public Base {
+public:
+ ~Derived() override;
+};
+
+void destroy(Base *b) {
+ delete b;
+}
+
+// CHECK: !riscv_lpad_label [[LABEL:![0-9]+]]
+// CHECK: [[LABEL]] = !{i32 {{[1-9][0-9]*}}}
\ No newline at end of file
diff --git a/clang/test/Preprocessor/riscv-cf-protection-branch.c b/clang/test/Preprocessor/riscv-cf-protection-branch.c
index f658e0a8c6c0fa..62577ae33f4cc9 100644
--- a/clang/test/Preprocessor/riscv-cf-protection-branch.c
+++ b/clang/test/Preprocessor/riscv-cf-protection-branch.c
@@ -1,3 +1,31 @@
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32i_zicfilp1p0 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM %s -o - | FileCheck \
+// RUN: --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32i_zicfilp1p0 -fcf-protection=full \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM %s -o - | FileCheck \
+// RUN: --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64i_zicfilp1p0 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM %s -o - | FileCheck \
+// RUN: --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64i_zicfilp1p0 -fcf-protection=full \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM %s -o - | FileCheck \
+// RUN: --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
+// RUN: %clang --target=riscv32 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM -emit-llvm %s -o - | \
+// RUN: FileCheck --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
+// RUN: %clang --target=riscv64 -fcf-protection=branch \
+// RUN: -mcf-branch-label-scheme=func-sig -E -dM %s -o - | FileCheck \
+// RUN: --check-prefixes=LPAD-MACRO,FUNCSIG-MACRO %s
+
// RUN: %clang --target=riscv32 -menable-experimental-extensions \
// RUN: -march=rv32i_zicfilp1p0 -fcf-protection=branch \
// RUN: -mcf-branch-label-scheme=unlabeled -E -dM %s -o - | FileCheck \
@@ -78,6 +106,7 @@
// LPAD-MACRO: __riscv_landing_pad 1{{$}}
// UNLABELED-MACRO: __riscv_landing_pad_unlabeled 1{{$}}
+// FUNCSIG-MACRO: __riscv_landing_pad_func_sig 1{{$}}
// NO-MACRO-NOT: __riscv_landing_pad
// NO-MACRO-NOT: __riscv_landing_pad_unlabeled
// NO-MACRO-NOT: __riscv_landing_pad_func_sig
diff --git a/clang/unittests/CMakeLists.txt b/clang/unittests/CMakeLists.txt
index b2fee01649abc6..c5fc49d73c1af4 100644
--- a/clang/unittests/CMakeLists.txt
+++ b/clang/unittests/CMakeLists.txt
@@ -133,3 +133,6 @@ add_distinct_clang_unittest(AllClangUnitTests
# the merged clang unit test binary, we can update the include paths and make
# this the default.
include_directories(Tooling)
+# RISCVLpadLabelGenTest.cpp needs access to clang/lib/CodeGen's private
+# headers (RISCVLpadLabelGen.h) for direct unit testing.
+include_directories(${CLANG_SOURCE_DIR}/lib/CodeGen)
diff --git a/clang/unittests/CodeGen/CMakeLists.txt b/clang/unittests/CodeGen/CMakeLists.txt
index 7e2782e09117cb..d6646d930900dd 100644
--- a/clang/unittests/CodeGen/CMakeLists.txt
+++ b/clang/unittests/CodeGen/CMakeLists.txt
@@ -4,6 +4,7 @@ add_clang_unittest(ClangCodeGenTests
DemangleTrapReasonInDebugInfo.cpp
TBAAMetadataTest.cpp
CheckTargetFeaturesTest.cpp
+ RISCVLpadLabelGenTest.cpp
QualTypeMapperTest.cpp
CLANG_LIBS
clangAST
diff --git a/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp b/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
new file mode 100644
index 00000000000000..c307618825d672
--- /dev/null
+++ b/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
@@ -0,0 +1,457 @@
+//===- clang/unittest/CodeGen/RISCVLpadLabelGenTest.cpp - lpad unittests --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements unit tests for the RISC-V cf-protection=branch func-sig label scheme
+//
+//===----------------------------------------------------------------------===//
+
+#include "RISCVLpadLabelGen.h"
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/MD5.h"
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/Mangle.h"
+#include "clang/AST/Type.h"
+#include "clang/Basic/Diagnostic.h"
+
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Tooling/Tooling.h"
+
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::CodeGen;
+
+namespace {
+
+// Parses Code, locates the single Decl matching Matcher, and returns the
+// psABI signature string computed for it. Fails the test if the match
+// isn't unique.
+template <typename MatcherT>
+std::string sigFor(llvm::StringRef Code, MatcherT Matcher,
+ std::vector<std::string> Args = {"-fsyntax-only",
+ "-std=c++17", "-triple",
+ "riscv32"},
+ llvm::StringRef FileName = "input.cc") {
+ auto AST = tooling::buildASTFromCodeWithArgs(Code, Args, FileName);
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+
+ auto Results = match(functionDecl(Matcher).bind("fn"), Ctx);
+ if (Results.size() != 1) {
+ ADD_FAILURE() << "expected exactly 1 match, got " << Results.size();
+ return {};
+ }
+ const auto *FD = Results[0].template getNodeAs<FunctionDecl>("fn");
+ return getRISCVLpadSignatureString(Ctx, *MC, FD);
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------
+// Decl-level special cases
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadSignature, Main) {
+ EXPECT_EQ("FiiPPcE", sigFor("int main(int argc, char **argv) { return 0; }",
+ hasName("main")));
+}
+
+TEST(RISCVLpadSignature, MainEmptyParams) {
+ EXPECT_EQ("FiiPPcE", sigFor("int main() { return 0; }", hasName("main")));
+}
+
+TEST(RISCVLpadSignature, DlRuntimeResolveIsZeroNotHashed) {
+ // Special-cased to the literal label 0, bypassing signature/hash
+ // computation entirely -- test createRISCVEntryLpadTypeId directly here,
+ // not getRISCVLpadSignatureString.
+ auto AST =
+ tooling::buildASTFromCode("extern \"C\" void _dl_runtime_resolve();");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results =
+ match(functionDecl(hasName("_dl_runtime_resolve")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ EXPECT_EQ(0u, createRISCVEntryLpadTypeId(Ctx, *MC, FD));
+}
+
+TEST(RISCVLpadSignature, DlRuntimeResolveEntryAndCallSiteLabels) {
+ auto AST =
+ tooling::buildASTFromCode("extern \"C\" void _dl_runtime_resolve();");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+
+ auto Results =
+ match(functionDecl(hasName("_dl_runtime_resolve")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ EXPECT_EQ(0u, createRISCVEntryLpadTypeId(Ctx, *MC, FD));
+
+ uint32_t CallSiteLabel = createRISCVCallSiteLpadTypeId(Ctx, *MC, FD);
+ EXPECT_NE(0u, CallSiteLabel);
+ EXPECT_EQ(computeRISCVLpadLabel(getRISCVLpadSignatureString(Ctx, *MC, FD)),
+ CallSiteLabel);
+}
+
+TEST(RISCVLpadSignature, StaticDlRuntimeResolveNameCollisionIsNotExempt) {
+ auto AST = tooling::buildASTFromCodeWithArgs(
+ "static void _dl_runtime_resolve(void) {}",
+ {"-fsyntax-only", "-std=c17", "-x", "c"},
+ /*FileName=*/"input.c");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results =
+ match(functionDecl(hasName("_dl_runtime_resolve")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ // A static function sharing the name must not receive the
+ // _dl_runtime_resolve exemption.
+ EXPECT_NE(0u, createRISCVEntryLpadTypeId(Ctx, *MC, FD));
+}
+
+TEST(RISCVLpadSignature, Destructor) {
+ EXPECT_EQ("FvPvE",
+ sigFor("class Foo { public: ~Foo(); };", cxxDestructorDecl()));
+}
+
+TEST(RISCVLpadSignature, BlockCopyHelperSignature) {
+ // void(void*, void*) -- expect second void* to compress via Itanium
+ // substitution rather than being re-spelled.
+ auto AST = tooling::buildASTFromCode("");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ EXPECT_EQ("FvPvS_E", getRISCVLpadSignatureString(
+ Ctx, *MC, buildBlockCopyHelperSigTy(Ctx)));
+}
+
+// ---------------------------------------------------------------------
+// Member pointer class substitution + static exemption
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadSignature, PlainMemberFunction) {
+ EXPECT_EQ("M1vFvvE",
+ sigFor("class Foo { public: void bar(); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, StaticMemberTreatedAsFreeFunction) {
+ EXPECT_EQ("FviE", sigFor("class Foo { public: static void bar(int); };",
+ hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, UnprototypedCFunctionTreatedAsVoid) {
+ EXPECT_EQ("FvvE", sigFor("void foo();", hasName("foo"),
+ {"-fsyntax-only", "-std=c17", "-x", "c"},
+ /*FileName=*/"input.c"));
+}
+
+// ---------------------------------------------------------------------
+// substituteCovariantReturn
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadSignature, PointerToClassReturnSubstituted) {
+ EXPECT_EQ("M1vFPviE",
+ sigFor("class Foo { public: Foo *bar(int); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, ReferenceToClassReturnSubstituted) {
+ EXPECT_EQ("M1vFRvvE",
+ sigFor("class Foo { public: Foo &bar(); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, RvalueReferenceToClassReturnSubstituted) {
+ EXPECT_EQ("M1vFOvvE",
+ sigFor("class Foo { public: Foo &&bar(); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, ValueClassReturnNotSubstituted) {
+ EXPECT_EQ("M1vF3BarvE", sigFor("class Bar; class Foo { public: Bar baz(); };",
+ hasName("baz")));
+}
+
+TEST(RISCVLpadSignature, NonClassPointerReturnUnaffected) {
+ EXPECT_EQ("M1vFPivE",
+ sigFor("class Foo { public: int *bar(); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, MultiLevelPointerExempted) {
+ // Pointee of the outer pointer is Foo*, not a record -- rule shouldn't
+ // fire; inner Foo stays as a real mangled class name.
+ EXPECT_EQ("M1vFPP3FoovE",
+ sigFor("class Foo { public: Foo **bar(); };", hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, CovariantReturnConsistentAcrossCallSiteAndOverride) {
+ const char *Code = R"cpp(
+ class Base { public: virtual Base *f(int); };
+ class Derived : public Base { public: virtual Derived *f(int) override; };
+ )cpp";
+ EXPECT_EQ(
+ sigFor(Code, cxxMethodDecl(hasName("f"), ofClass(hasName("Base")))),
+ sigFor(Code, cxxMethodDecl(hasName("f"), ofClass(hasName("Derived")))));
+}
+
+TEST(RISCVLpadSignature, CompressionAppliesSubstitution) {
+ // Foo appears twice (param + another param of the same pointer-to-Foo
+ // type) -- Itanium compression should back-reference the second
+ // occurrence rather than re-spelling it.
+ EXPECT_EQ("FvP3FooS0_E",
+ sigFor("class Foo; void bar(Foo*, Foo*);", hasName("bar")));
+}
+
+// ---------------------------------------------------------------------
+// stripExceptionSpec
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadSignature, NoexceptMemberFunctionIgnored) {
+ EXPECT_EQ("M1vFvvE", sigFor("class Foo { public: void bar() noexcept; };",
+ hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, NoexceptFreeFunctionIgnored) {
+ EXPECT_EQ("FviE", sigFor("void foo(int) noexcept;", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, NestedExceptionSpecStripped) {
+ EXPECT_EQ("FvPFvvEE",
+ sigFor("void foo(void (*)() noexcept);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature,
+ ExceptionSpecInFunctionPointerTemplateArgumentIsHardError) {
+ auto AST =
+ tooling::buildASTFromCode("template<typename T> class Wrapper {};"
+ "void bar(Wrapper<void (*)() noexcept>);");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("bar")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ DiagnosticsEngine &Diags = Ctx.getDiagnostics();
+ Diags.setClient(new IgnoringDiagConsumer(), /*ShouldOwnClient=*/true);
+ DiagnosticErrorTrap Trap(Diags);
+
+ (void)getRISCVLpadSignatureString(Ctx, *MC, FD);
+ EXPECT_TRUE(Trap.hasErrorOccurred());
+}
+
+TEST(RISCVLpadSignature,
+ ExceptionSpecInMemberFunctionPointerTemplateArgumentIsHardError) {
+ // Covers the reviewer's concern more fully: the member-pointer pointee
+ // recursion is a structurally distinct path from the plain-pointer one
+ // above (see MemberPointerType handling in the recursive scanner).
+ auto AST =
+ tooling::buildASTFromCode("template<typename T> class Wrapper {};"
+ "struct C {};"
+ "void bar(Wrapper<void (C::*)() noexcept>);");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("bar")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ DiagnosticsEngine &Diags = Ctx.getDiagnostics();
+ Diags.setClient(new IgnoringDiagConsumer(), /*ShouldOwnClient=*/true);
+ DiagnosticErrorTrap Trap(Diags);
+
+ (void)getRISCVLpadSignatureString(Ctx, *MC, FD);
+ EXPECT_TRUE(Trap.hasErrorOccurred());
+}
+
+TEST(RISCVLpadSignature,
+ NoexceptFunctionPointerOutsideTemplateArgumentIsIgnored) {
+ // Contrast with ExceptionSpecInFunctionPointerTemplateArgumentIsHardError:
+ // the same shape, without a template argument boundary, must remain
+ // unaffected
+ EXPECT_EQ("FvPFvvEE",
+ sigFor("void foo(void (*)() noexcept);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, ExceptionSpecInNestedTemplateArgumentIsHardError) {
+ auto AST =
+ tooling::buildASTFromCode("template<typename T> class Inner {};"
+ "template<typename T> class Outer {};"
+ "void bar(Outer<Inner<void (*)() noexcept>>);");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("bar")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ DiagnosticsEngine &Diags = Ctx.getDiagnostics();
+ Diags.setClient(new IgnoringDiagConsumer(), /*ShouldOwnClient=*/true);
+ DiagnosticErrorTrap Trap(Diags);
+
+ (void)getRISCVLpadSignatureString(Ctx, *MC, FD);
+ EXPECT_TRUE(Trap.hasErrorOccurred());
+}
+
+// ---------------------------------------------------------------------
+// rewriteWCharT
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadSignature, WCharTParam) {
+ EXPECT_EQ("FviE", sigFor("void foo(wchar_t);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTReturn) {
+ EXPECT_EQ("FivE", sigFor("wchar_t foo();", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTPointer) {
+ EXPECT_EQ("FvPiE", sigFor("void foo(wchar_t*);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTConstReference) {
+ EXPECT_EQ("FvRKiE", sigFor("void foo(const wchar_t&);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTDoublePointerFullyRecurses) {
+ EXPECT_EQ("FvPPiE", sigFor("void foo(wchar_t**);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTInsideMemberPointerPointee) {
+ EXPECT_EQ("M1vFviE", sigFor("class Foo { public: void bar(wchar_t); };",
+ hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, WCharTPointerToArray) {
+ EXPECT_EQ("FvPA4_iE", sigFor("void foo(wchar_t (*)[4]);", hasName("foo")));
+}
+
+TEST(RISCVLpadSignature, WCharTThroughTypedefAlias) {
+ EXPECT_EQ("FviE", sigFor("using W = wchar_t; void f(W);", hasName("f")));
+}
+
+TEST(RISCVLpadSignature, WCharTInsideNestedMemberPointerParam) {
+ EXPECT_EQ("FvM3FooFviEE", sigFor("class Foo { public: void bar(wchar_t); };"
+ "void baz(void (Foo::*)(wchar_t));",
+ hasName("baz")));
+}
+
+TEST(RISCVLpadSignature, WCharTInsideBlockPointer) {
+ EXPECT_EQ(
+ "FvU13block_pointerFviEE", // confirm exact mangling empirically
+ sigFor("void foo(void (^)(wchar_t));", hasName("foo"),
+ {"-fsyntax-only", "-std=c++17", "-fblocks", "--target=riscv32"}));
+}
+
+/// FIXME: the signatureNormalizer does not work on wchar_t template arguments.
+TEST(RISCVLpadSignature, WCharTInTemplateArgumentIsHardError) {
+ auto AST = tooling::buildASTFromCode(
+ "template<typename T> class Foo {}; void bar(Foo<wchar_t>);");
+ ASTContext &Ctx = AST->getASTContext();
+
+ DiagnosticsEngine &Diags = Ctx.getDiagnostics();
+ Diags.setClient(new IgnoringDiagConsumer(), /*ShouldOwnClient=*/true);
+
+ DiagnosticErrorTrap Trap(Diags);
+
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("bar")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ (void)getRISCVLpadSignatureString(Ctx, *MC, FD);
+
+ EXPECT_TRUE(Trap.hasErrorOccurred());
+}
+
+TEST(RISCVLpadSignature, WCharTNestedTwoLevelsInTemplateArgumentIsHardError) {
+ // Foo<Bar<wchar_t>> -- confirms the recursive (not just one-level) case.
+ auto AST = tooling::buildASTFromCode("template<typename T> class Bar {};"
+ "template<typename T> class Foo {};"
+ "void baz(Foo<Bar<wchar_t>>);");
+ ASTContext &Ctx = AST->getASTContext();
+
+ DiagnosticsEngine &Diags = Ctx.getDiagnostics();
+ Diags.setClient(new IgnoringDiagConsumer(), /*ShouldOwnClient=*/true);
+
+ DiagnosticErrorTrap Trap(Diags);
+
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("baz")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ (void)getRISCVLpadSignatureString(Ctx, *MC, FD);
+
+ EXPECT_TRUE(Trap.hasErrorOccurred());
+}
+
+TEST(RISCVLpadSignature, ShortWCharUsesUnsignedShort) {
+ EXPECT_EQ("FvtE", sigFor("void foo(wchar_t);", hasName("foo"),
+ {"-fsyntax-only", "-std=c++17", "-fshort-wchar",
+ "--target=riscv32"}));
+}
+
+TEST(RISCVLpadSignature, PointerToVariableLengthArray) {
+ EXPECT_EQ("FviPA_iE", sigFor("void foo(int n, int (*p)[n]);", hasName("foo"),
+ {"-fsyntax-only", "-std=c17", "-x", "c",
+ "--target=riscv32"}));
+}
+
+// ---------------------------------------------------------------------
+// End-to-end: confirms signature-building and hashing are wired together
+// correctly.
+// ---------------------------------------------------------------------
+
+TEST(RISCVLpadLabel, EndToEndMatchesIndependentHash) {
+ auto AST = tooling::buildASTFromCode("class Foo { public: void bar(); };");
+ ASTContext &Ctx = AST->getASTContext();
+ auto MC = ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics());
+ auto Results = match(functionDecl(hasName("bar")).bind("fn"), Ctx);
+ ASSERT_EQ(Results.size(), 1u);
+ const auto *FD = Results[0].getNodeAs<FunctionDecl>("fn");
+
+ std::string Sig = getRISCVLpadSignatureString(Ctx, *MC, FD);
+ EXPECT_EQ(computeRISCVLpadLabel(llvm::StringRef(Sig)),
+ createRISCVEntryLpadTypeId(Ctx, *MC, FD));
+}
+
+// Clang's Itanium mangler does not currently emit the 'Y' (language
+// linkage) marker from CWG1259 for these constructs. Since we delegate
+// to Clang's own mangler for <function-type> encoding, there is nothing
+// for RISCVLpadLabelGen to strip. These tests pin that behaviour
+/// FIXME: if Clang's mangler changes and starts emitting 'Y',
+/// getRISCVLpadCanonicalSignature will need an explicit stripping step added.
+
+TEST(RISCVLpadSignature, NoLanguageLinkageMarkerForExternCFunction) {
+ EXPECT_EQ("FviE", sigFor(R"cpp(
+ extern "C" void c_function(int);
+ )cpp",
+ hasName("c_function")));
+}
+
+TEST(RISCVLpadSignature, NoLanguageLinkageMarkerForCFunctionPointerParam) {
+ EXPECT_EQ("FvPFviEE", sigFor(R"cpp(
+ extern "C" void realfunc(int);
+ void bar(decltype(realfunc) *p);
+ )cpp",
+ hasName("bar")));
+}
+
+TEST(RISCVLpadSignature, NoLanguageLinkageMarkerForCFunctionPointerTypedef) {
+ EXPECT_EQ("FvPFviEE", sigFor(R"cpp(
+ extern "C" typedef void Callback(int);
+ void takes_callback(Callback *);
+ )cpp",
+ hasName("takes_callback")));
+}
diff --git a/llvm/include/llvm/Transforms/Utils/RISCVZicfilpHash.h b/llvm/include/llvm/Transforms/Utils/RISCVZicfilpHash.h
new file mode 100644
index 00000000000000..35785c4aeee234
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Utils/RISCVZicfilpHash.h
@@ -0,0 +1,33 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Helpers for computing the 20-bit RISCV-Zicfilp landing pad label from a
+// mangled type name.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_TRANSFORMS_UTILS_RISCVZICFILPHASH_H
+#define LLVM_TRANSFORMS_UTILS_RISCVZICFILPHASH_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MD5.h"
+#include <cstdint>
+
+namespace llvm {
+namespace RISCVCFI {
+constexpr uint32_t ZicfilpFuncSigFallbackLabel = 0xfea61;
+
+/// Apply the psABI 128-bit-MD5-to-20-bit-label reduction.
+LLVM_ABI uint32_t reduceZicfilpFuncSigLabel(const MD5::MD5Result &Digest);
+
+/// Compute MD5(Signature), then apply the psABI reduction.
+LLVM_ABI uint32_t getZicfilpFuncSigLabel(StringRef Signature);
+} // namespace RISCVCFI
+} // namespace llvm
+
+#endif // LLVM_TRANSFORMS_UTILS_RISCVZICFILPHASH_H
diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt b/llvm/lib/Transforms/Utils/CMakeLists.txt
index 3b7a134b49e2e1..3dc7aa762cbfed 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -76,6 +76,7 @@ add_llvm_component_library(LLVMTransformUtils
ProfileVerify.cpp
PromoteMemoryToRegister.cpp
RelLookupTableConverter.cpp
+ RISCVZicfilpHash.cpp
ScalarEvolutionExpander.cpp
SCCPSolver.cpp
StripConvergenceIntrinsics.cpp
diff --git a/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp b/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
new file mode 100644
index 00000000000000..e0324d7d80dba7
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
@@ -0,0 +1,55 @@
+//===-- RISCVZicfilpHash.cpp - helpers to generate lpad labels ------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Generates RISCV-Zicfilp landing pad labels
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Transforms/Utils/RISCVZicfilpHash.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/ArrayRef.h"
+
+namespace llvm {
+namespace RISCVCFI {
+uint32_t reduceZicfilpFuncSigLabel(const llvm::MD5::MD5Result &Digest) {
+ // per riscv-elf-psabi (draft
+ // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/pull/434), the rules
+ // to determine the label are:
+ // 1. use the lower 20 bits of the hash
+ // 2. if the current value is 0, use the next 20 bits
+ // 3. if fewer than 20 bits remain, pad with 0
+ // 4. if the value is still 0, hash the string "RISC-V" and use the lower 20
+ // bits of its hash. (this value is constant: 0xfea61. no need to compute
+ // every time.)
+
+ // Treat the digest as a single little-endian 128-bit integer. Zero-extend it
+ // so that the final 20-bit chunk is padded with zeros (rule 3).
+ const uint64_t Words[] = {Digest.low(), Digest.high()};
+ llvm::APInt Hash = llvm::APInt(128, Words).zext(140);
+
+ uint32_t Label = 0;
+ for (unsigned Shift = 0; Shift < 128 && !Label; Shift += 20)
+ // extractBitsAsZExtValue doesn't pad the selected bit range, it pads the returned uint64_t.
+ // ordinary extractBits would return an APInt which needs to be unwrapped with .getZExtValue before casting to uint32_t.
+ Label = static_cast<uint32_t>(Hash.extractBitsAsZExtValue(20, Shift));
+ if (!Label)
+ Label = ZicfilpFuncSigFallbackLabel;
+
+ return Label;
+}
+
+/// Compute MD5(Signature), then apply the psABI reduction.
+uint32_t getZicfilpFuncSigLabel(StringRef Signature) {
+ llvm::MD5 Hash;
+ Hash.update(Signature);
+ llvm::MD5::MD5Result Result;
+ Hash.final(Result);
+ return reduceZicfilpFuncSigLabel(Result);
+}
+} // namespace RISCVCFI
+} // namespace llvm
\ No newline at end of file
diff --git a/llvm/unittests/Transforms/Utils/CMakeLists.txt b/llvm/unittests/Transforms/Utils/CMakeLists.txt
index f4e4c817114c1b..bac8441299abdf 100644
--- a/llvm/unittests/Transforms/Utils/CMakeLists.txt
+++ b/llvm/unittests/Transforms/Utils/CMakeLists.txt
@@ -34,4 +34,5 @@ add_llvm_unittest(UtilsTests
UnrollLoopTest.cpp
ValueMapperTest.cpp
ProfDataUtilTest.cpp
+ RISCVZicfilpHashTest.cpp
)
diff --git a/llvm/unittests/Transforms/Utils/RISCVZicfilpHashTest.cpp b/llvm/unittests/Transforms/Utils/RISCVZicfilpHashTest.cpp
new file mode 100644
index 00000000000000..0aa169f0b51479
--- /dev/null
+++ b/llvm/unittests/Transforms/Utils/RISCVZicfilpHashTest.cpp
@@ -0,0 +1,102 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements unit tests for the RISCVZicfilpHash header.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Transforms/Utils/RISCVZicfilpHash.h"
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/MD5.h"
+
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace llvm::RISCVCFI;
+namespace {
+MD5::MD5Result makeResult(uint64_t Low, uint64_t High) {
+ MD5::MD5Result R;
+ support::endian::write<uint64_t, endianness::little>(R.data(), Low);
+ support::endian::write<uint64_t, endianness::little>(R.data() + 8, High);
+ return R;
+}
+
+// creates an MD5Result where the first x bits are 0, followed by 'value' to
+// test the fallback logic.
+llvm::MD5::MD5Result makeResultWithFirstNonzeroAt(unsigned SkipBits,
+ uint32_t Value) {
+ uint64_t Low = 0, High = 0;
+ if (SkipBits < 64) {
+ Low = static_cast<uint64_t>(Value) << SkipBits;
+ if (SkipBits + 20 > 64)
+ High = static_cast<uint64_t>(Value) >> (64 - SkipBits);
+ } else {
+ High = static_cast<uint64_t>(Value) << (SkipBits - 64);
+ }
+ return makeResult(Low, High);
+}
+
+} // namespace
+
+TEST(RISCVZicfilpHash, SkipsLeadingZeroSegment) {
+ // Lower 20 bits zero, next 20 bits = 0x12345.
+ uint64_t Low = 0x12345ull << 20;
+ auto Result = makeResult(Low, 0);
+ EXPECT_EQ(0x12345u, reduceZicfilpFuncSigLabel(Result));
+}
+
+TEST(RISCVZicfilpHash, AllZeroFallsBackToConstant) {
+ EXPECT_EQ(ZicfilpFuncSigFallbackLabel,
+ reduceZicfilpFuncSigLabel(makeResult(0, 0)));
+}
+
+TEST(RISCVZicfilpHash, FallbackConstantMatchesRiscVHash) {
+ EXPECT_EQ(ZicfilpFuncSigFallbackLabel,
+ getZicfilpFuncSigLabel(llvm::StringRef("RISC-V")));
+}
+
+TEST(RISCVZicfilpHash, FirstNonzeroAt0) {
+ EXPECT_EQ(0x12345u, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(0, 0x12345)));
+}
+TEST(RISCVZicfilpHash, FirstNonzeroAt20) {
+ EXPECT_EQ(0x6789Au, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(20, 0x6789A)));
+}
+TEST(RISCVZicfilpHash, FirstNonzeroAt40) {
+ EXPECT_EQ(0xABCDEu, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(40, 0xABCDE)));
+}
+TEST(RISCVZicfilpHash, FirstNonzeroAt60) {
+ EXPECT_EQ(0x3ABCDu, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(60, 0x3ABCD)));
+} // straddles Low/High
+TEST(RISCVZicfilpHash, FirstNonzeroAt80) {
+ EXPECT_EQ(0x54321u, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(80, 0x54321)));
+}
+TEST(RISCVZicfilpHash, FirstNonzeroAt100) {
+ EXPECT_EQ(0xFEDCBu, reduceZicfilpFuncSigLabel(
+ makeResultWithFirstNonzeroAt(100, 0xFEDCB)));
+}
+TEST(RISCVZicfilpHash, FirstNonzeroAt120) {
+ // Only 8 bits remain (120..127); the rest of the 20-bit field is 0-padded
+ EXPECT_EQ(0xABu,
+ reduceZicfilpFuncSigLabel(makeResultWithFirstNonzeroAt(120, 0xAB)));
+}
+
+TEST(RISCVZicfilpHash, RiscVHashLower20BitsMatchesFallbackConstant) {
+ llvm::MD5 Hash;
+ Hash.update(llvm::StringRef("RISC-V"));
+ llvm::MD5::MD5Result Result;
+ Hash.final(Result);
+ EXPECT_EQ(ZicfilpFuncSigFallbackLabel,
+ static_cast<uint32_t>(Result.low() & 0xFFFFF));
+}
>From c14a4be053c0e39c9ff9e34205b2adc507d58524 Mon Sep 17 00:00:00 2001
From: Benedikt Steinberg <benedikt.steinberg at aisec.fraunhofer.de>
Date: Fri, 13 Nov 2026 12:42:28 +0000
Subject: [PATCH 2/3] cut overly verbose comments
---
clang/lib/CodeGen/RISCVLpadLabelGen.cpp | 16 +++-------------
1 file changed, 3 insertions(+), 13 deletions(-)
diff --git a/clang/lib/CodeGen/RISCVLpadLabelGen.cpp b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
index 7842171a877702..97152a603a4c45 100644
--- a/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
+++ b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
@@ -108,9 +108,7 @@ class SignatureNormalizer : public TypeVisitor<SignatureNormalizer, QualType> {
return Ctx.getRValueReferenceType(Visit(T->getPointeeType()));
}
- // Pointer-to-array (e.g. "wchar_t (*)[4]") -- the only shape an array
- // can take inside a mangled function signature, since arrays decay to
- // pointers in parameter position and can't be returned directly.
+ // Pointer-to-array
QualType VisitConstantArrayType(const ConstantArrayType *T) {
return Ctx.getConstantArrayType(Visit(T->getElementType()), T->getSize(),
T->getSizeExpr(), T->getSizeModifier(),
@@ -122,10 +120,7 @@ class SignatureNormalizer : public TypeVisitor<SignatureNormalizer, QualType> {
T->getIndexTypeCVRQualifiers());
}
- // Nested pointer-to-member (e.g. as a parameter type): per psABI, the
- // class/covariant-return substitutions only apply at the top level, so
- // we only recurse for wchar_t/exception-spec normalization here --
- // the class and pointee are otherwise left as-is.
+ // Nested pointer-to-member
QualType VisitMemberPointerType(const MemberPointerType *T) {
QualType NewPointee = Visit(T->getPointeeType());
return Ctx.getMemberPointerType(NewPointee, std::nullopt,
@@ -302,10 +297,6 @@ combineTemplateArgScanResults(TemplateArgScanResult LHS,
static TemplateArgScanResult
scanTemplateArgumentForWCharT(const TemplateArgument &Arg);
-// Looks through sugar via getAsCXXRecordDecl() rather than matching a
-// specific Type subclass, so this is robust regardless of which sugar
-// node (TemplateSpecializationType/ElaboratedType/RecordType) the AST
-// actually uses for a given specialization.
static TemplateArgScanResult
scanTypeForWCharTInTemplateArgs(QualType T, bool WithinTemplateArgs = false) {
if (WithinTemplateArgs && isWCharT(T))
@@ -327,8 +318,7 @@ scanTypeForWCharTInTemplateArgs(QualType T, bool WithinTemplateArgs = false) {
return Result;
}
}
- // Mirrors a subset of SignatureNormalizer's own structural recursion --
- // if SignatureNormalizer gains a new recursive case, update this too.
+
if (const auto *PT = T->getAs<PointerType>())
return scanTypeForWCharTInTemplateArgs(PT->getPointeeType(),
WithinTemplateArgs);
>From 01d82c18acb02fbed9a5864435fb9bc831b5cd12 Mon Sep 17 00:00:00 2001
From: Benedikt Steinberg <benedikt.steinberg at aisec.fraunhofer.de>
Date: Mon, 23 Nov 2026 09:22:23 +0000
Subject: [PATCH 3/3] run git-clang-format
---
clang/lib/CodeGen/RISCVLpadLabelGen.cpp | 4 ++--
clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp | 3 ++-
llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp | 5 +++--
3 files changed, 7 insertions(+), 5 deletions(-)
diff --git a/clang/lib/CodeGen/RISCVLpadLabelGen.cpp b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
index 97152a603a4c45..b29ff98da86d61 100644
--- a/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
+++ b/clang/lib/CodeGen/RISCVLpadLabelGen.cpp
@@ -108,7 +108,7 @@ class SignatureNormalizer : public TypeVisitor<SignatureNormalizer, QualType> {
return Ctx.getRValueReferenceType(Visit(T->getPointeeType()));
}
- // Pointer-to-array
+ // Pointer-to-array
QualType VisitConstantArrayType(const ConstantArrayType *T) {
return Ctx.getConstantArrayType(Visit(T->getElementType()), T->getSize(),
T->getSizeExpr(), T->getSizeModifier(),
@@ -318,7 +318,7 @@ scanTypeForWCharTInTemplateArgs(QualType T, bool WithinTemplateArgs = false) {
return Result;
}
}
-
+
if (const auto *PT = T->getAs<PointerType>())
return scanTypeForWCharTInTemplateArgs(PT->getPointeeType(),
WithinTemplateArgs);
diff --git a/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp b/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
index c307618825d672..081d939db413ee 100644
--- a/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
+++ b/clang/unittests/CodeGen/RISCVLpadLabelGenTest.cpp
@@ -6,7 +6,8 @@
//
//===----------------------------------------------------------------------===//
//
-// This file implements unit tests for the RISC-V cf-protection=branch func-sig label scheme
+// This file implements unit tests for the RISC-V cf-protection=branch func-sig
+// label scheme
//
//===----------------------------------------------------------------------===//
diff --git a/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp b/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
index e0324d7d80dba7..5ee533a85a009d 100644
--- a/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
+++ b/llvm/lib/Transforms/Utils/RISCVZicfilpHash.cpp
@@ -34,8 +34,9 @@ uint32_t reduceZicfilpFuncSigLabel(const llvm::MD5::MD5Result &Digest) {
uint32_t Label = 0;
for (unsigned Shift = 0; Shift < 128 && !Label; Shift += 20)
- // extractBitsAsZExtValue doesn't pad the selected bit range, it pads the returned uint64_t.
- // ordinary extractBits would return an APInt which needs to be unwrapped with .getZExtValue before casting to uint32_t.
+ // extractBitsAsZExtValue doesn't pad the selected bit range, it pads the
+ // returned uint64_t. ordinary extractBits would return an APInt which needs
+ // to be unwrapped with .getZExtValue before casting to uint32_t.
Label = static_cast<uint32_t>(Hash.extractBitsAsZExtValue(20, Shift));
if (!Label)
Label = ZicfilpFuncSigFallbackLabel;
More information about the cfe-commits
mailing list