Skip to content

Commit

Permalink
[Clang][RISCV] Support -fcf-protection=return for RISC-V (#112477)
Browse files Browse the repository at this point in the history
Enables the support of `-fcf-protection=return` on RISC-V, which
requires Zicfiss. It also adds a string attribute "hw-shadow-stack"
to every function if the option is set on RISC-V
  • Loading branch information
jaidTw authored Oct 29, 2024
1 parent 66fc81c commit 335e68d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
7 changes: 7 additions & 0 deletions clang/lib/Basic/Targets/RISCV.h
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ class RISCVTargetInfo : public TargetInfo {
return true;
}

bool
checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const override {
if (ISAInfo->hasExtension("zicfiss"))
return true;
return TargetInfo::checkCFProtectionReturnSupported(Diags);
}

CFBranchLabelSchemeKind getDefaultCFBranchLabelScheme() const override {
return CFBranchLabelSchemeKind::FuncSig;
}
Expand Down
7 changes: 5 additions & 2 deletions clang/lib/CodeGen/Targets/RISCV.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,11 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) return;

auto *Fn = cast<llvm::Function>(GV);

if (CGM.getCodeGenOpts().CFProtectionReturn)
Fn->addFnAttr("hw-shadow-stack");

const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
if (!Attr)
return;
Expand All @@ -604,8 +609,6 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
case RISCVInterruptAttr::machine: Kind = "machine"; break;
}

auto *Fn = cast<llvm::Function>(GV);

Fn->addFnAttr("interrupt", Kind);
}
};
Expand Down
9 changes: 9 additions & 0 deletions clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-zicfiss -emit-llvm -o - %s -fcf-protection=return | FileCheck %s
// RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-zicfiss -emit-llvm -o - %s | FileCheck -check-prefix=NOSHADOWSTACK %s
// RUN: %clang_cc1 -triple riscv32 -target-feature +experimental-zicfiss -emit-llvm -o - %s -fcf-protection=return | FileCheck %s
// RUN: %clang_cc1 -triple riscv32 -target-feature +experimental-zicfiss -emit-llvm -o - %s | FileCheck -check-prefix=NOSHADOWSTACK %s

int foo(int *a) { return *a; }

// CHECK: attributes {{.*}}"hw-shadow-stack"{{.*}}
// NOSHADOWSTACK-NOT: attributes {{.*}}"hw-shadow-stack"{{.*}}

0 comments on commit 335e68d

Please sign in to comment.