Skip to content

[RISC-V] Do not emit cm.popret[z] with zicfiss - #196267

Merged
nemanjai merged 1 commit into
llvm:mainfrom
nemanjai:nemanja/fix-zicfiss-zcmp
Jul 28, 2026
Merged

nemanjai merged 1 commit into
llvm:mainfrom
nemanjai:nemanja/fix-zicfiss-zcmp

Conversation

@nemanjai

@nemanjai nemanjai commented May 7, 2026

Copy link
Copy Markdown
Member

When emitting shadow call stack protection instructions, the push/pop optimization needs to be turned off because an sspopchk before a cm.popret[z] is guaranteed to fail in a non-leaf function. In addition, the sspopchk must be emitted after a cm.pop so that the ra has the correct value when the check is performed.

Fixes: #196261

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-backend-risc-v

Author: Nemanja Ivanovic (nemanjai)

Changes

When emitting shadow call stack protection instructions, the push/pop optimization needs to be turned off because an sspopchk before a cm.popret[z] is guaranteed to fail in a non-leaf function. In addition, the sspopchk must be emitted after a cm.pop so that the ra has the correct value when the check is performed.

Fixes: #196261


Full diff: https://github.com/llvm/llvm-project/pull/196267.diff

3 Files Affected:

  • (modified) llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (+4)
  • (modified) llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp (+6)
  • (added) llvm/test/CodeGen/RISCV/shadow-stack-zcmp.ll (+52)
diff --git a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
index 1be81ea93129a..4b683e05659fe 100644
--- a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
@@ -12,6 +12,7 @@
 
 #include "RISCVFrameLowering.h"
 #include "MCTargetDesc/RISCVBaseInfo.h"
+#include "MCTargetDesc/RISCVMCTargetDesc.h"
 #include "RISCVMachineFunctionInfo.h"
 #include "RISCVSubtarget.h"
 #include "llvm/BinaryFormat/Dwarf.h"
@@ -197,6 +198,9 @@ static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
 
   const RISCVInstrInfo *TII = STI.getInstrInfo();
   if (HasHWShadowStack) {
+    // The shadow call stack popchk needs to happen after cm.pop that loads ra.
+    if (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP)
+      MI = std::next(MI);
     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoMOP_SSPOPCHK)).addReg(RAReg);
     return;
   }
diff --git a/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp b/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
index eae7e8697f0ad..97f7c2d387b21 100644
--- a/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
+++ b/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
@@ -138,6 +138,12 @@ bool RISCVPushPopOpt::runOnMachineFunction(MachineFunction &Fn) {
   if (!Subtarget->hasStdExtZcmp() && !Subtarget->hasVendorXqccmp())
     return false;
 
+  // We don't want any popret[z] instructions when emitting code with hardware
+  // shadow stack protection.
+  if (Fn.getFunction().hasFnAttribute("hw-shadow-stack") &&
+      Subtarget->hasStdExtZimop())
+    return false;
+
   TII = Subtarget->getInstrInfo();
   TRI = Subtarget->getRegisterInfo();
 
diff --git a/llvm/test/CodeGen/RISCV/shadow-stack-zcmp.ll b/llvm/test/CodeGen/RISCV/shadow-stack-zcmp.ll
new file mode 100644
index 0000000000000..75e9362dd9124
--- /dev/null
+++ b/llvm/test/CodeGen/RISCV/shadow-stack-zcmp.ll
@@ -0,0 +1,52 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 6
+; RUN: llc -mtriple=riscv32 -verify-machineinstrs < %s \
+; RUN:   | FileCheck %s --check-prefix=RV32
+@.str = private unnamed_addr constant [13 x i8] c"Val[%d]: %d\0A\00", align 1
+
+; Function Attrs: nofree nounwind
+define dso_local noundef i32 @printSomething(ptr noundef readonly captures(none) %arr, i32 noundef returned %len) local_unnamed_addr #0 {
+; RV32-LABEL: printSomething:
+; RV32:       # %bb.0: # %entry
+; RV32-NEXT:    sspush ra
+; RV32-NEXT:    cm.push {ra, s0-s3}, -32
+; RV32-NEXT:    mv s2, a1
+; RV32-NEXT:    blez a1, .LBB0_3
+; RV32-NEXT:  # %bb.1: # %for.body.preheader
+; RV32-NEXT:    mv s1, a0
+; RV32-NEXT:    li s0, 0
+; RV32-NEXT:    lui s3, %hi(.L.str)
+; RV32-NEXT:    addi s3, s3, %lo(.L.str)
+; RV32-NEXT:  .LBB0_2: # %for.body
+; RV32-NEXT:    # =>This Inner Loop Header: Depth=1
+; RV32-NEXT:    lw a2, 0(s1)
+; RV32-NEXT:    cm.mva01s s3, s0
+; RV32-NEXT:    call printf
+; RV32-NEXT:    addi s0, s0, 1
+; RV32-NEXT:    addi s1, s1, 4
+; RV32-NEXT:    bne s2, s0, .LBB0_2
+; RV32-NEXT:  .LBB0_3: # %for.cond.cleanup
+; RV32-NEXT:    mv a0, s2
+; RV32-NEXT:    cm.pop {ra, s0-s3}, 32
+; RV32-NEXT:    mop.r.28 zero, ra
+; RV32-NEXT:    ret
+entry:
+  %cmp5 = icmp sgt i32 %len, 0
+  br i1 %cmp5, label %for.body, label %for.cond.cleanup
+
+for.cond.cleanup:                                 ; preds = %for.body, %entry
+  ret i32 %len
+
+for.body:                                         ; preds = %entry, %for.body
+  %i.06 = phi i32 [ %inc, %for.body ], [ 0, %entry ]
+  %arrayidx = getelementptr inbounds nuw [4 x i8], ptr %arr, i32 %i.06
+  %0 = load i32, ptr %arrayidx, align 4
+  %call = tail call i32 (ptr, ...) @printf(ptr noundef nonnull dereferenceable(1) @.str, i32 noundef %i.06, i32 noundef %0)
+  %inc = add nuw nsw i32 %i.06, 1
+  %exitcond.not = icmp eq i32 %inc, %len
+  br i1 %exitcond.not, label %for.cond.cleanup, label %for.body
+}
+
+; Function Attrs: nofree nounwind
+declare dso_local noundef i32 @printf(ptr noundef readonly captures(none), ...) local_unnamed_addr #0
+
+attributes #0 = { nofree nounwind "hw-shadow-stack" "target-cpu"="generic-rv32" "target-features"="+32bit,+c,+experimental-zicfiss,+i,+zcmop,+zcmp,+zimop" }

@lenary lenary left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch.

@nemanjai
nemanjai force-pushed the nemanja/fix-zicfiss-zcmp branch from ccd8bed to 22ece2f Compare May 12, 2026 07:07
@topperc
topperc self-requested a review May 12, 2026 16:50

@lenary lenary left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving because I will be afk. I do not have more comments, but please wait for @topperc to approve before merging this.

@lenary

lenary commented Jun 9, 2026

Copy link
Copy Markdown
Member

@nemanjai reverse ping, how are you getting on with Craig's comments?

@nemanjai

Copy link
Copy Markdown
Member Author

I am really sorry about the delay. I was on vacation and then in transition from Synopsys to Global Foundries. I'll get this updated now.

@nemanjai
nemanjai force-pushed the nemanja/fix-zicfiss-zcmp branch from 22ece2f to d4683ec Compare June 15, 2026 07:48
@lenary

lenary commented Jun 18, 2026

Copy link
Copy Markdown
Member

Sorry, you now have a conflict with #203635 which just landed - can you git merge main or similar?

When emitting shadow call stack protection instructions,
the push/pop optimization needs to be turned off because
an sspopchk before a cm.popret[z] is guaranteed to fail
in a non-leaf function. In addition, the sspopchk must
be emitted after a cm.pop so that the ra has the correct
value when the check is performed.

Fixes: llvm#196261
@nemanjai
nemanjai force-pushed the nemanja/fix-zicfiss-zcmp branch from d4683ec to 92b582b Compare July 28, 2026 14:56
@nemanjai

Copy link
Copy Markdown
Member Author

Conflict resolved, comments addressed. I'll leave this PR open for another day in case you want to take another look after the update.

@topperc topperc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nemanjai
nemanjai merged commit 255162a into llvm:main Jul 28, 2026
12 checks passed
@ilovepi

ilovepi commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Hi, we'r seeing a failure in our CI after this patch.

Bot: https://ci.chromium.org/ui/p/fuchsia/builders/toolchain.ci/clang-linux-arm64/b8675003321337857313/overview

Logs: https://logs.chromium.org/logs/fuchsia/buildbucket/cr-buildbucket/8675003321337857313/+/u/clang/build/stdout

Error:

FAILED: CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj 
/b/s/w/ir/x/w/llvm_build/bin/clang --target=riscv64-unknown-fuchsia --sysroot=/b/s/w/ir/x/w/sdk/arch/riscv64/sysroot -DVISIBILITY_HIDDEN -I/b/s/w/ir/x/w/llvm-llvm-project/compiler-rt/lib/builtins/../../../third-party/siphash/include --target=riscv64-unknown-fuchsia -I/b/s/w/ir/x/w/sdk/pkg/sync/include -I/b/s/w/ir/x/w/sdk/pkg/fdio/include -fstack-size-section -fexperimental-call-graph-section -O2 -g -DNDEBUG -std=gnu11 -fno-lto -nostdinc++ -Wno-c2y-extensions -fPIC -fno-builtin -fvisibility=hidden -fomit-frame-pointer -DCOMPILER_RT_HAS_FLOAT16 -MD -MT CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj -MF CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj.d -o CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj -c /b/s/w/ir/x/w/llvm-llvm-project/compiler-rt/lib/builtins/floattisf.c
clang: llvm/include/llvm/ADT/ilist_iterator.h:168: reference llvm::ilist_iterator<llvm::ilist_detail::node_options<llvm::MachineInstr, true, true, void, false, void>, false, false>::operator*() const [OptionsT = llvm::ilist_detail::node_options<llvm::MachineInstr, true, true, void, false, void>, IsReverse = false, IsConst = false]: Assertion `!NodePtr->isKnownSentinel()' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace and dumped files.
Stack dump:
0.	Program arguments: /b/s/w/ir/x/w/llvm_build/bin/clang --target=riscv64-unknown-fuchsia --sysroot=/b/s/w/ir/x/w/sdk/arch/riscv64/sysroot -DVISIBILITY_HIDDEN -I/b/s/w/ir/x/w/llvm-llvm-project/compiler-rt/lib/builtins/../../../third-party/siphash/include --target=riscv64-unknown-fuchsia -I/b/s/w/ir/x/w/sdk/pkg/sync/include -I/b/s/w/ir/x/w/sdk/pkg/fdio/include -fstack-size-section -fexperimental-call-graph-section -O2 -g -DNDEBUG -std=gnu11 -fno-lto -nostdinc++ -Wno-c2y-extensions -fPIC -fno-builtin -fvisibility=hidden -fomit-frame-pointer -DCOMPILER_RT_HAS_FLOAT16 -MD -MT CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj -MF CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj.d -o CMakeFiles/clang_rt.builtins-riscv64.dir/floattisf.c.obj -c /b/s/w/ir/x/w/llvm-llvm-project/compiler-rt/lib/builtins/floattisf.c
1.	<eof> parser at end of file
2.	Code generation
3.	Running pass 'Function Pass Manager' on module '/b/s/w/ir/x/w/llvm-llvm-project/compiler-rt/lib/builtins/floattisf.c'.
4.	Running pass 'Prologue/Epilogue Insertion & Frame Finalization' on function '@__floattisf'
#0 0x0000aaaaeccbe704 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/b/s/w/ir/x/w/llvm_build/bin/clang+0x90de704)
clang: error: clang frontend command failed due to signal (use -v to see invocation)
Fuchsia clang version 24.0.0git (https://llvm.googlesource.com/llvm-project 83dfacdbda1a8b87c1f170ec6ce4e240e1fa79db)
Target: riscv64-unknown-fuchsia
Thread model: posix
InstalledDir: /b/s/w/ir/x/w/llvm_build/bin
Build config: +assertions
clang: note: diagnostic msg: 
********************

Since your change is in riscv and we see the crash in riscv runtimes, I'm guessing this is related to your patch. could you take a look?

Comment on lines +197 to +199
// The shadow call stack popchk needs to happen after cm.pop that loads ra.
if (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP)
++MI;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the assert, I'm guessing the guard here isn't quite right.

@ilovepi

ilovepi commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

In case the reproducer helps.

floattidf-371435.sh
floattidf-371435.c

@nemanjai

Copy link
Copy Markdown
Member Author

In case the reproducer helps.

floattidf-371435.sh floattidf-371435.c

I'll have a look. Thanks for providing the repro.

@nemanjai

Copy link
Copy Markdown
Member Author

In case the reproducer helps.

floattidf-371435.sh floattidf-371435.c

Fix in #212791

asudarsa-qti pushed a commit to asudarsa-qti/llvm-project that referenced this pull request Jul 29, 2026
When emitting shadow call stack protection instructions, the push/pop
optimization needs to be turned off because an sspopchk before a
cm.popret[z] is guaranteed to fail in a non-leaf function. In addition,
the sspopchk must be emitted after a cm.pop so that the ra has the
correct value when the check is performed.

Fixes: llvm#196261

Co-authored-by: Nemanja Ivanovic <[email protected]>
jgreenbaum pushed a commit to jgreenbaum/llvm-project that referenced this pull request Aug 3, 2026
When emitting shadow call stack protection instructions, the push/pop
optimization needs to be turned off because an sspopchk before a
cm.popret[z] is guaranteed to fail in a non-leaf function. In addition,
the sspopchk must be emitted after a cm.pop so that the ra has the
correct value when the check is performed.

Fixes: llvm#196261

Co-authored-by: Nemanja Ivanovic <[email protected]>
@lenary lenary added this to the LLVM 23.x Release milestone Sep 24, 2026
@github-project-automation github-project-automation Bot moved this to Needs Triage in LLVM Release Status Sep 24, 2026
@github-project-automation github-project-automation Bot moved this from Needs Triage to Done in LLVM Release Status Sep 24, 2026
@lenary

lenary commented Sep 24, 2026

Copy link
Copy Markdown
Member

/cherry-pick 255162a f24da9d

@llvmbot

llvmbot commented Sep 24, 2026

Copy link
Copy Markdown
Member

/pull-request #226322

tru pushed a commit that referenced this pull request Sep 25, 2026
When emitting shadow call stack protection instructions, the push/pop
optimization needs to be turned off because an sspopchk before a
cm.popret[z] is guaranteed to fail in a non-leaf function. In addition,
the sspopchk must be emitted after a cm.pop so that the ra has the
correct value when the check is performed.

Fixes: #196261

Co-authored-by: Nemanja Ivanovic <[email protected]>
(cherry picked from commit 255162a)
lenary added a commit to qualcomm/cpullvm-toolchain that referenced this pull request Oct 7, 2026
This contains the patch files corresponding to:
1. llvm/llvm-project#196267 and
llvm/llvm-project#212791
2. llvm/llvm-project#226309
3. llvm/llvm-project#226633

This also fixes up previously added patch files so they work with
`--method am`.

Signed-off-by: Sam Elliott <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Development

Successfully merging this pull request may close these issues.

[RISC-V] Invalid codegen with Zicfiss + Zcmp

5 participants