[llvm] [BPF] Handle unreachable with a kfunc call (PR #131731)

via llvm-commits llvm-commits at lists.llvm.org
Thu May 22 11:02:09 PDT 2025


eddyz87 wrote:

> Okay, with __bpf_unreachable, we will have a conflict with kernel. In bpf_helpers.h,
> 
> ```
> /*
>  * Helper macro to throw a compilation error if __bpf_unreachable() gets
>  * built into the resulting code. This works given BPF back end does not
>  * implement __builtin_trap(). This is useful to assert that certain paths
>  * of the program code are never used and hence eliminated by the compiler.
>  *
>  * For example, consider a switch statement that covers known cases used by
>  * the program. __bpf_unreachable() can then reside in the default case. If
>  * the program gets extended such that a case is not covered in the switch
>  * statement, then it will throw a build error due to the default case not
>  * being compiled out.
>  */
> #ifndef __bpf_unreachable
> # define __bpf_unreachable()    __builtin_trap()
> #endif
> ```
> 
> We need to pick a different symbol name.

`__builtin_trap()` is now supported by the backend and is translated as a call to `__bpf_unreachable`, e.g.:

```
$ cat ~/work/tmp/test_trap.c 
void foo(void);
void bar(void);
void buz(int p) {
  if (p) {
    foo();
    __builtin_trap();
  } else {
    bar();
  }
}
$ build/bin/clang --target=bpf -mcpu=v3 -S -o - ~/work/tmp/test_trap.c 
	...
buz:                                    # @buz
# %bb.0:                                # %entry
	*(u32 *)(r10 - 4) = w1
	w1 = *(u32 *)(r10 - 4)
	if w1 == 0 goto LBB0_2
	goto LBB0_1
LBB0_1:                                 # %if.then
	call foo
	call __bpf_unreachable
	goto LBB0_3
LBB0_2:                                 # %if.else
	call bar
	goto LBB0_3
LBB0_3:                                 # %if.end
	exit
.Lfunc_end0:
	...
```

Looks like `bpf_helpers.h` now needs to distinguish between compile time and load time asserts (use different macro definitions).

https://github.com/llvm/llvm-project/pull/131731


More information about the llvm-commits mailing list