BPF: add AdjustOpt IR pass to generate verifier friendly codes
authorYonghong Song <yhs@fb.com>
Thu, 6 Aug 2020 16:06:43 +0000 (09:06 -0700)
committerYonghong Song <yhs@fb.com>
Wed, 7 Oct 2020 15:49:10 +0000 (08:49 -0700)
commitddf1864ace484035e3cde5e83b3a31ac81e059c6
treeaa76f6811253be800159f3dce24ebc7806896527
parent9908ee5670596db4fdc2bd7ea7c3071c0e02a784
BPF: add AdjustOpt IR pass to generate verifier friendly codes

Add an IR phase right before main module optimization.
This is to modify IR to restrict certain downward optimizations
in order to generate verifier friendly code.
  > prevent certain instcombine optimizations, handling both
    in-block/cross-block instcombines.
  > avoid speculative code motion if the variable used in
    condition is also used in the later blocks.

Internally, a bpf IR builtin
  result = __builtin_bpf_passthrough(seq_num, result)
is used to enforce ordering. This builtin is only used
during target independent IR optimizations and it will
be removed at the beginning of target dependent IR
optimizations.

For example, removing the following workaround,
  --- a/tools/testing/selftests/bpf/progs/test_sysctl_loop1.c
  +++ b/tools/testing/selftests/bpf/progs/test_sysctl_loop1.c
  @@ -47,7 +47,7 @@ int sysctl_tcp_mem(struct bpf_sysctl *ctx)
          /* a workaround to prevent compiler from generating
           * codes verifier cannot handle yet.
           */
  -       volatile int ret;
  +       int ret;
this patch is able to generate code which passed the verifier.

To disable optimization, users need to use "opt" command like below:
  clang -target bpf -O2 -S -emit-llvm -Xclang -disable-llvm-passes test.c
  // disable icmp serialization
  opt -O2 -bpf-disable-serialize-icmp test.ll | llvm-dis > t.ll
  // disable avoid-speculation
  opt -O2 -bpf-disable-avoid-speculation test.ll | llvm-dis > t.ll
  llc t.ll

Differential Revision: https://reviews.llvm.org/D85570
llvm/lib/Target/BPF/BPF.h
llvm/lib/Target/BPF/BPFAdjustOpt.cpp [new file with mode: 0644]
llvm/lib/Target/BPF/BPFTargetMachine.cpp
llvm/lib/Target/BPF/CMakeLists.txt
llvm/test/CodeGen/BPF/adjust-opt-icmp1.ll [new file with mode: 0644]
llvm/test/CodeGen/BPF/adjust-opt-icmp2.ll [new file with mode: 0644]
llvm/test/CodeGen/BPF/adjust-opt-speculative1.ll [new file with mode: 0644]
llvm/test/CodeGen/BPF/adjust-opt-speculative2.ll [new file with mode: 0644]