[llvm] [RISCV][Support] Fix instruction-cache invalidation in Memory::InvalidateInstructionCache (PR #216059)
Fu-Chiang Chang via llvm-commits
llvm-commits at lists.llvm.org
Thu Aug 13 07:15:12 PDT 2026
https://github.com/Com1t created https://github.com/llvm/llvm-project/pull/216059
The RISC-V architecture does not guarantee automatic instruction-cache coherence after code modification. Therefore, JITs and self-modifying code must invalidate the instruction cache before executing newly generated or modified instructions.
However, `Memory::InvalidateInstructionCache()` is currently a `no-op` on RISC-V. As a result, such code may execute stale instructions, potentially leading to incorrect results or crashes.
This change fixes the `Memory::InvalidateInstructionCache()` implementation for RISC-V by calling `__builtin___clear_cache()` to ensure that the instruction cache is invalidated.
Assisted-by: Claude
>From cbd2e60558b06673ff399124539b4f4a8b11e1f7 Mon Sep 17 00:00:00 2001
From: Fu-Chiang Chang <fu-chiang.chang at sifive.com>
Date: Thu, 13 Aug 2026 15:41:54 +0800
Subject: [PATCH] Ensure icache is flushed after calling
InvalidateInstructionCache on RISC-V
---
llvm/lib/Support/Unix/Memory.inc | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/llvm/lib/Support/Unix/Memory.inc b/llvm/lib/Support/Unix/Memory.inc
index bac208a7d543c..ccec5c575e185 100644
--- a/llvm/lib/Support/Unix/Memory.inc
+++ b/llvm/lib/Support/Unix/Memory.inc
@@ -237,6 +237,12 @@ void Memory::InvalidateInstructionCache(const void *Addr, size_t Len) {
for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
asm volatile("icbi 0, %0" : : "r"(Line));
asm volatile("isync");
+#elif defined(__riscv) && defined(__GNUC__)
+ // __clear_cache() is a no-op in libgcc on RISC-V and is not lowered
+ // by Clang; the builtin lowers to __riscv_flush_icache.
+ const char *Start = static_cast<const char *>(Addr);
+ const char *End = Start + Len;
+ __builtin___clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
#elif (defined(__arm__) || defined(__aarch64__) || defined(__loongarch__) || \
defined(__mips__)) && \
defined(__GNUC__)
More information about the llvm-commits
mailing list