This is an archive of the discontinued LLVM Phabricator instance.

[BPF] Hoist load's to getelementptr's when possible
DraftPublic

Authored by eddyz87 on Aug 25 2022, 9:19 AM.
This is a draft revision that has not yet been submitted for review.

Details

Reviewers
None
Summary

This commit adds a new BPF specific pass named
BPFHoistGetElementPtrLoadsPass. The goal of this pass is to hoist
load instructions to the corresponding getelementptr instructions when
this is deemed safe.

BPF verifier limits access patterns allowed for certain data
types. E.g. struct __sk_buff and struct bpf_sock_ops. For these types
only BASE + static-offset memory loads and stores are allowed.

This is so because offsets of the fields of these structures do not
match real offsets in the running kernel. During BPF program
load/verification loads and stores to the fields of these types are
rewritten so that offsets match real offsets. For this rewrite to
happen static offsets have to be encoded in the instructions.

See kernel/bpf/verifier.c:convert_ctx_access function in the Linux
kernel source tree for details.

During instruction selection phase the following sequence of
instructions:

%x = getelementptr %ptr, %offset
%y = load %x

Is translated as a single load instruction with embedded offset,
e.g. LDW %ptr, %offset, which matches access pattern necessary for
the restricted set of types described above (when %offset is static).

However, several optimization passes might sink load instruction or
hoist getelementptr instruction so that the instructions are no
longer in sequence. Examples of such passes are SimplifyCFGPass and
InstCombinePass.

The BPFHoistArgumentAccess undoes sinking of the load / store
instructions by hoisting load/store instructions to predecessor basic
blocks.

This addresses the issue reported in the following thread:

https://lore.kernel.org/bpf/CAA-VZPmxh8o8EBcJ=m-DH4ytcxDFmo0JKsm1p1gf40kS0CE3NQ@mail.gmail.com/T/#m4b9ce2ce73b34f34172328f975235fc6f19841b6

Diff Detail

Event Timeline

eddyz87 created this revision.Aug 25 2022, 9:19 AM
Herald added a project: Restricted Project. · View Herald TranscriptAug 25 2022, 9:19 AM
eddyz87 updated this revision to Diff 555643.Sep 3 2023, 5:35 PM
eddyz87 edited the summary of this revision. (Show Details)

Completer rework:

  • limit transformation to access to function arguments
  • handle predecessors with multiple successors
  • copy getelementptr when necessary
  • support for preserve_access_index patterns