From 0bb1d6a81627dbbe88f1504e3955deb7015e134d Mon Sep 17 00:00:00 2001 From: Jens Sonnenberg <10518877+jenswl@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:38:38 +0100 Subject: [PATCH 1/3] Run the SSE4.2 span scanners on default x86-64 builds via runtime dispatch llparse has emitted SSE4.2 span scanners (`_mm_cmpestri`) for the header-value and header-field states since 2019, but they are guarded by `#ifdef __SSE4_2__`. Node.js and the common Linux distributions build with no `-march`, so every shipped x86-64 binary contains zero `pcmpestri` and the fast path is dead; it is live only where the build baseline is >= x86-64-v2 (e.g. RHEL). Passing `-msse4.2` globally was rejected before, and an earlier per-call dispatch attempt measured slower. This compiles the generated parser a second time with `-msse4.2` under renamed internal symbols and lets `llhttp_execute()` select it once per process with `__builtin_cpu_supports("sse4.2")`: - bin/generate.ts additionally emits `llhttp_sse42_rename.h` (renames the defined `llhttp__internal*` symbols, derived from the generated source so it stays correct across grammar changes) and the small `llhttp_sse42.c` wrapper that includes the generated parser under those renames. The imported callbacks (`llhttp__on_*`) keep their names and stay shared. - src/native/api.c dispatches in `llhttp_execute` on x86-64 GCC/clang builds that were compiled without `-msse4.2`. Both instantiations come from the same source, so the parser state layout is identical. - Makefile and CMakeLists build the second object with `-msse4.2`, on x86-64 only, skipped on MSVC. One well-predicted branch per `llhttp_execute` call (per TCP chunk), not per byte or per span. Measurements (Zen 5, this parser; standalone harness, 8 interleaved runs, 95% CI): 4-header GET -4.8% [-6.5, -3.0] 32-header GET -11.6% [-12.6, -10.5] browser GET -18.0% [-19.0, -17.1] (instructions -43%) 10 KiB POST -8.2% [-10.5, -5.9] Node benchmark/http/bench-parser.js (compare.js, 30 runs, Welch): +4.8% (32 headers, p=3e-8), +3.9% (16), +2.3% (8), +2.2% (4); all significant. Correctness: a libFuzzer differential harness (ASan+UBSan) drove the base and SSE4.2 instantiations with identical random chunking and lenient-flag combinations, comparing error code and the full callback sequence; ~5.5e8 executions, 0 divergences. The 16-byte SSE loads stay in bounds (the generated code guards `endp - p >= 16`). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_0139J1kq4EkxBPrZELPKPfF3 --- CMakeLists.txt | 12 ++++++++++++ Makefile | 20 +++++++++++++++++--- bin/generate.ts | 31 +++++++++++++++++++++++++++++++ src/native/api.c | 24 ++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) mode change 100755 => 100644 bin/generate.ts diff --git a/CMakeLists.txt b/CMakeLists.txt index 54ae1b1a..500b6a89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,18 @@ set(LLHTTP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/api.c ) +# On x86-64, compile a second instantiation of the parser with SSE4.2 enabled so +# llhttp_execute() can select it at runtime (see src/api.c). The default build +# passes no -march, so the SSE4.2 span scanners in the generated code are +# otherwise never compiled in. Skipped on MSVC (no __builtin_cpu_supports). +if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$") + list(APPEND LLHTTP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/llhttp_sse42.c) + set_source_files_properties( + ${CMAKE_CURRENT_SOURCE_DIR}/src/llhttp_sse42.c + PROPERTIES COMPILE_OPTIONS "-msse4.2" + ) +endif() + set(LLHTTP_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/include/llhttp.h ) diff --git a/Makefile b/Makefile index 16fe819f..f92fbe65 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,15 @@ endif INCLUDES += -Ibuild/ +# On x86-64, also build a second instantiation of the generated parser with +# -msse4.2 so llhttp_execute() can select the SSE4.2 span scanners at runtime +# (see src/native/api.c). The default build passes no -march, so without this +# the SSE4.2 code generated under `#ifdef __SSE4_2__` is never compiled in. +ARCH ?= $(shell uname -m) +ifneq (,$(filter $(ARCH),x86_64 amd64 AMD64)) + SSE42_OBJ = build/c/llhttp_sse42.o +endif + INSTALL ?= install PREFIX ?= /usr/local LIBDIR = $(PREFIX)/lib @@ -23,17 +32,20 @@ clean: rm -rf build/ rm -rf test/tmp -build/libllhttp.so: build/c/llhttp.o build/native/api.o \ +build/libllhttp.so: build/c/llhttp.o $(SSE42_OBJ) build/native/api.o \ build/native/http.o $(CLANG) -shared $^ -o $@ -build/libllhttp.a: build/c/llhttp.o build/native/api.o \ +build/libllhttp.a: build/c/llhttp.o $(SSE42_OBJ) build/native/api.o \ build/native/http.o - $(AR) rcs $@ build/c/llhttp.o build/native/api.o build/native/http.o + $(AR) rcs $@ build/c/llhttp.o $(SSE42_OBJ) build/native/api.o build/native/http.o build/c/llhttp.o: build/c/llhttp.c $(CLANG) $(CFLAGS) $(INCLUDES) -c $< -o $@ +build/c/llhttp_sse42.o: build/c/llhttp_sse42.c build/c/llhttp.c + $(CLANG) $(CFLAGS) -msse4.2 $(INCLUDES) -c $< -o $@ + build/native/%.o: src/native/%.c build/llhttp.h src/native/api.h \ build/native $(CLANG) $(CFLAGS) $(INCLUDES) -c $< -o $@ @@ -52,6 +64,8 @@ release: clean all generate mkdir -p release/include cp -rf build/llhttp.h release/include/ cp -rf build/c/llhttp.c release/src/ + cp -rf build/c/llhttp_sse42.c release/src/ + cp -rf build/c/llhttp_sse42_rename.h release/src/ cp -rf src/native/*.c release/src/ cp -rf src/llhttp.gyp release/ cp -rf src/common.gypi release/ diff --git a/bin/generate.ts b/bin/generate.ts old mode 100755 new mode 100644 index 727269dd..dbb4c993 --- a/bin/generate.ts +++ b/bin/generate.ts @@ -11,6 +11,8 @@ const semverRE = /^(?0|[1-9]\d*)\.(?0|[1-9]\d*)\.(?0|[1-9]\ const C_FILE = resolve(__dirname, '../build/c/llhttp.c'); const HEADER_FILE = resolve(__dirname, '../build/llhttp.h'); +const SSE42_RENAME_FILE = resolve(__dirname, '../build/c/llhttp_sse42_rename.h'); +const SSE42_C_FILE = resolve(__dirname, '../build/c/llhttp_sse42.c'); const pkg = JSON.parse( readFileSync(resolve(__dirname, '..', 'package.json')).toString(), @@ -49,3 +51,32 @@ ${nativeHeaders} mkdirSync(dirname(C_FILE), { recursive: true }); writeFileSync(HEADER_FILE, headers); writeFileSync(C_FILE, generated.c); + +// A second instantiation of the generated parser, compiled with -msse4.2, lets +// llhttp_execute() use the SSE4.2 span scanners at runtime on default x86-64 +// builds (which pass no -march, so the `#ifdef __SSE4_2__` code is otherwise +// dead). The parser defines symbols prefixed `llhttp__internal`; the callbacks +// it imports are prefixed `llhttp__on`/`llhttp__before`/`llhttp__after` and stay +// shared. Rename only the defined `llhttp__internal*` symbols so the second copy +// links beside the first. Derived from the generated source, so it stays correct +// across grammar changes. +const internalSymbols = Array.from( + new Set(generated.c.match(/\bllhttp__internal[0-9A-Za-z_]*/g) ?? []), +).sort(); +const renameHeader = `/* Generated by bin/generate.ts. Renames the defined symbols of llhttp.c so a + * second, -msse4.2 instantiation (llhttp_sse42.c) can link beside the first. */ +#ifndef INCLUDE_LLHTTP_SSE42_RENAME_H_ +#define INCLUDE_LLHTTP_SSE42_RENAME_H_ +${internalSymbols.map((s) => `#define ${s} ${s}_sse42`).join('\n')} +#endif /* INCLUDE_LLHTTP_SSE42_RENAME_H_ */ +`; +const sse42Wrapper = `/* Generated by bin/generate.ts. See src/native/api.c: a second instantiation of + * the generated parser with the SSE4.2 span scanners enabled, selected once at + * runtime by llhttp_execute(). Built with -msse4.2 by the build system. */ +#if defined(__x86_64__) || defined(_M_X64) +#include "llhttp_sse42_rename.h" +#include "llhttp.c" +#endif +`; +writeFileSync(SSE42_RENAME_FILE, renameHeader); +writeFileSync(SSE42_C_FILE, sse42Wrapper); diff --git a/src/native/api.c b/src/native/api.c index ae5e862d..3c483659 100644 --- a/src/native/api.c +++ b/src/native/api.c @@ -122,9 +122,33 @@ void llhttp_reset(llhttp_t* parser) { } +#if (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ + (defined(__GNUC__) || defined(__clang__)) +/* A second instantiation of the generated parser, compiled with -msse4.2 (see + * llhttp_sse42.c), which turns on the SSE4.2 span scanners that the generated + * code guards with `#ifdef __SSE4_2__`. The default x86-64 build (no -march) + * never contains them, so pick the SSE4.2 build once at runtime. Both + * instantiations come from the same generated source, so the parser state + * layout is identical and a parser may be driven by either. */ +llhttp_errno_t llhttp__internal_execute_sse42(llhttp_t* state, const char* p, + const char* endp); + +static int llhttp__sse42 = -1; + +llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) { + if (llhttp__sse42 < 0) { + llhttp__sse42 = __builtin_cpu_supports("sse4.2") ? 1 : 0; + } + if (llhttp__sse42) { + return llhttp__internal_execute_sse42(parser, data, data + len); + } + return llhttp__internal_execute(parser, data, data + len); +} +#else llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) { return llhttp__internal_execute(parser, data, data + len); } +#endif void llhttp_settings_init(llhttp_settings_t* settings) { From 7807968227527da97ee3b40db82a885a8b707b6f Mon Sep 17 00:00:00 2001 From: Jens Sonnenberg <10518877+jenswl@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:25:30 +0100 Subject: [PATCH 2/3] Add the SSE4.2 object to the gyp build and a dispatch test Review follow-up for the runtime SSE4.2 dispatch. src/llhttp.gyp -- which ships in the release tarball and is what Node's deps/llhttp builds -- still listed only llhttp.c, api.c and http.c. With the dispatch added to api.c but no SSE4.2 object, that build fails to link with `undefined reference to llhttp__internal_execute_sse42`. - src/llhttp.gyp: on x86-64 (non-MSVC), build src/llhttp_sse42.c as a separate static_library target with -msse4.2 and make the main llhttp target depend on it. The flag is scoped to that one translation unit; the target and the dependency are both guarded by the same arch condition, so other targets and non-x86-64 builds are unchanged. (The release Makefile already copies llhttp_sse42.c and llhttp_sse42_rename.h into release/src.) - test/dispatch/dispatch_test.c: links against the built library (which contains api.c and, on x86-64, both parser instantiations) and drives the runtime dispatch that the markdown suite never compiles. It parses a request with header values long enough to take the SSE4.2 span scanners, once in one call and once one byte at a time, and asserts the two agree and are correct. - Makefile: `make test-c` builds and runs it against build/libllhttp.a. - ci.yaml: run `make test-c` after building the library. Verified by building the release-layout gyp with a consumer executable: it links and runs, -msse4.2 is applied only to llhttp_sse42.c, and reverting the gyp change reproduces the undefined-reference link error. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_0139J1kq4EkxBPrZELPKPfF3 --- .github/workflows/ci.yaml | 5 ++ Makefile | 10 ++- src/llhttp.gyp | 30 ++++++- test/dispatch/dispatch_test.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 202 insertions(+), 2 deletions(-) create mode 100644 test/dispatch/dispatch_test.c diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c129ddea..cb38e98e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -58,6 +58,11 @@ jobs: run: | make build/libllhttp.a + - name: Run dispatch test + shell: bash + run: | + make test-c + - name: Build WebAssembly run: npm run build-wasm if: runner.os == 'Linux' diff --git a/Makefile b/Makefile index f92fbe65..7fdb4c41 100644 --- a/Makefile +++ b/Makefile @@ -101,6 +101,14 @@ postversion: release generate: node --import tsx bin/generate.ts +# Links a small C program against the built library (which contains api.c and, +# on x86-64, both parser instantiations) and drives the runtime dispatch added +# in src/native/api.c. The markdown test suite never compiles api.c. +test-c: build/libllhttp.a + $(CLANG) $(CFLAGS) $(INCLUDES) test/dispatch/dispatch_test.c \ + build/libllhttp.a -o build/dispatch_test + ./build/dispatch_test + install: build/libllhttp.a build/libllhttp.so $(INSTALL) -d $(DESTDIR)$(INCLUDEDIR) $(INSTALL) -d $(DESTDIR)$(LIBDIR) @@ -108,4 +116,4 @@ install: build/libllhttp.a build/libllhttp.so $(INSTALL) -C build/libllhttp.a $(DESTDIR)$(LIBDIR)/libllhttp.a $(INSTALL) build/libllhttp.so $(DESTDIR)$(LIBDIR)/libllhttp.so -.PHONY: all generate clean release postversion github-release +.PHONY: all generate clean release postversion github-release test-c diff --git a/src/llhttp.gyp b/src/llhttp.gyp index c7b8800a..95022cd1 100644 --- a/src/llhttp.gyp +++ b/src/llhttp.gyp @@ -17,6 +17,34 @@ 'sources': [ '<@(llhttp_sources)', ], + 'conditions': [ + # On x86-64, api.c (llhttp_execute) calls llhttp__internal_execute_sse42, + # a second instantiation of the parser compiled with -msse4.2 and chosen + # at runtime via __builtin_cpu_supports (see src/native/api.c). It is a + # separate target so -msse4.2 applies only to that one translation unit. + # Skipped on MSVC, which has no __builtin_cpu_supports (the dispatch in + # api.c is then compiled out and the symbol is not referenced). + ['OS!="win" and (target_arch=="x64" or target_arch=="x86_64")', { + 'dependencies': [ 'llhttp_sse42' ], + }], + ], }, - ] + ], + 'conditions': [ + ['OS!="win" and (target_arch=="x64" or target_arch=="x86_64")', { + 'targets': [ + { + 'target_name': 'llhttp_sse42', + 'type': 'static_library', + 'include_dirs': [ '.', 'include' ], + 'sources': [ 'src/llhttp_sse42.c' ], + 'cflags': [ '-msse4.2' ], + 'cflags_cc': [ '-msse4.2' ], + 'xcode_settings': { + 'OTHER_CFLAGS': [ '-msse4.2' ], + }, + }, + ], + }], + ], } diff --git a/test/dispatch/dispatch_test.c b/test/dispatch/dispatch_test.c new file mode 100644 index 00000000..3d4cc87d --- /dev/null +++ b/test/dispatch/dispatch_test.c @@ -0,0 +1,159 @@ +/* + * Dispatch test for the runtime SSE4.2 selection in src/native/api.c. + * + * The markdown test suite links the generated parser compiled with -msse4.2 + * directly; it never compiles api.c, so the runtime dispatch added in + * llhttp_execute() is not exercised there. This test links against the built + * library (build/libllhttp.a), which contains api.c and -- on x86-64 -- both + * the baseline parser and the -msse4.2 instantiation selected at runtime. + * + * It parses a request whose header values are long enough to drive the SSE4.2 + * span scanners (they need >= 16 bytes in a span), once in a single call and + * once one byte at a time, and asserts the two runs agree and are correct. + * Feeding one byte at a time keeps spans short, so the scalar fallback inside + * the same dispatched parser is exercised too; the single-shot run takes the + * vector path. Any divergence between them, or any parse error, fails. + */ + +#include +#include + +#include "llhttp.h" + +static const char kRequest[] = + "GET /de/catalog?q=widget&page=2 HTTP/1.1\r\n" + "Host: shop.example.de\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36\r\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,*/*;q=0.8\r\n" + "Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7\r\n" + "Cookie: session=0123456789abcdef0123456789abcdef; " + "consent=granted-analytics-marketing-preferences; " + "cart=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6\r\n" + "\r\n"; + +/* + * All counters are chunk-independent: byte lengths are accumulated across + * however many data callbacks occur, and headers are counted via the + * *_complete callbacks, which fire once per header regardless of how the input + * was split. (The raw on_header_* data callbacks fire once per span piece, so + * their invocation count legitimately differs between single-shot and + * byte-wise feeding -- that is not a divergence.) + */ +typedef struct { + int messages; + int headers; + size_t url_len; + size_t header_field_len; + size_t header_value_len; + int errored; +} counters_t; + +static int on_url(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->url_len += len; + return 0; +} + +static int on_header_field(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->header_field_len += len; + return 0; +} + +static int on_header_value(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->header_value_len += len; + return 0; +} + +static int on_header_value_complete(llhttp_t* p) { + ((counters_t*) p->data)->headers++; + return 0; +} + +static int on_message_complete(llhttp_t* p) { + ((counters_t*) p->data)->messages++; + return 0; +} + +static void init_settings(llhttp_settings_t* s) { + llhttp_settings_init(s); + s->on_url = on_url; + s->on_header_field = on_header_field; + s->on_header_value = on_header_value; + s->on_header_value_complete = on_header_value_complete; + s->on_message_complete = on_message_complete; +} + +/* Returns 0 on HPE_OK, else the error code. */ +static int run(counters_t* c, int chunked) { + llhttp_settings_t settings; + llhttp_t parser; + size_t len = sizeof(kRequest) - 1; + + init_settings(&settings); + llhttp_init(&parser, HTTP_REQUEST, &settings); + memset(c, 0, sizeof(*c)); + parser.data = c; + + if (chunked) { + for (size_t i = 0; i < len; i++) { + llhttp_errno_t err = llhttp_execute(&parser, kRequest + i, 1); + if (err != HPE_OK) { + c->errored = 1; + return (int) err; + } + } + return (int) HPE_OK; + } + + return (int) llhttp_execute(&parser, kRequest, len); +} + +static int eq(const counters_t* a, const counters_t* b) { + return a->messages == b->messages && + a->headers == b->headers && + a->url_len == b->url_len && + a->header_field_len == b->header_field_len && + a->header_value_len == b->header_value_len; +} + +int main(void) { + counters_t one_shot, byte_wise; + int err_one = run(&one_shot, 0); + int err_byte = run(&byte_wise, 1); + + if (err_one != (int) HPE_OK) { + fprintf(stderr, "single-shot parse failed: %d\n", err_one); + return 1; + } + if (err_byte != (int) HPE_OK) { + fprintf(stderr, "byte-wise parse failed: %d\n", err_byte); + return 1; + } + if (one_shot.messages != 1) { + fprintf(stderr, "expected 1 message, got %d\n", one_shot.messages); + return 1; + } + if (one_shot.headers != 5) { + fprintf(stderr, "expected 5 headers, got %d\n", one_shot.headers); + return 1; + } + if (!eq(&one_shot, &byte_wise)) { + fprintf(stderr, + "single-shot and byte-wise parses diverged: " + "msgs %d/%d headers %d/%d url %zu/%zu field %zu/%zu value %zu/%zu\n", + one_shot.messages, byte_wise.messages, + one_shot.headers, byte_wise.headers, + one_shot.url_len, byte_wise.url_len, + one_shot.header_field_len, byte_wise.header_field_len, + one_shot.header_value_len, byte_wise.header_value_len); + return 1; + } + + printf("dispatch test OK: 1 message, %d headers, url=%zu, values=%zu bytes\n", + one_shot.headers, one_shot.url_len, one_shot.header_value_len); + return 0; +} From 0255bc8d3abeedc04cd81a9d28ac14f4a17b12fc Mon Sep 17 00:00:00 2001 From: Jens Sonnenberg <10518877+jenswl@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:26:28 +0100 Subject: [PATCH 3/3] Make the SSE4.2 dispatch opt-in so direct source builds still link Second review round. The dispatch in api.c was active by default on x86-64, so a consumer that compiles llhttp.c, api.c and http.c with its own build system (aiohttp's setup.py, distro packagers, other bindings) linked against a missing llhttp__internal_execute_sse42 and failed to load. It is now gated on LLHTTP_SSE42_DISPATCH, which only our Makefile, CMake and gyp define, and only where they also compile llhttp_sse42.c. Without the macro the baseline path is used and no second object is needed. - src/native/api.c: require LLHTTP_SSE42_DISPATCH; also exclude _MSC_VER (MSVC/clang-cl lack __builtin_cpu_supports and skip the second object). Drop the cached flag and call __builtin_cpu_supports() each time -- it only loads and tests __cpu_model, which the runtime initializes in a constructor, so there is no benefit to the cache and no data race without it. - Makefile: detect the target from `$(CLANG) -dumpmachine`, not the host `uname -m`, so a cross-compile does not add an x86-only object; skip Windows/mingw; define LLHTTP_SSE42_DISPATCH where the object is built. - CMakeLists.txt, src/llhttp.gyp: define LLHTTP_SSE42_DISPATCH on the library that compiles api.c, under the same x86-64 (non-MSVC/non-win) condition that builds the second object. - test/dispatch/dispatch_test.c: when built with the dispatch, drive the SSE4.2 instantiation directly and assert it matches the baseline, so the test cannot pass silently on the scalar path. - bin/generate.ts: restore the executable bit (unintentionally dropped). Verified: building the sources as a shared object without the macro leaves no undefined llhttp__internal_execute_sse42 (with the macro it does, confirming the macro gates the reference); the dispatch test reports the SSE4.2 path exercised; the gyp release build links and runs with -msse4.2 only on llhttp_sse42.c; arch detection enables only x86-64 Linux/macOS and skips aarch64, windows-msvc and mingw; 276 md-tests pass. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_0139J1kq4EkxBPrZELPKPfF3 --- CMakeLists.txt | 7 +++++ Makefile | 22 ++++++++++---- bin/generate.ts | 0 src/llhttp.gyp | 3 ++ src/native/api.c | 35 +++++++++++++--------- test/dispatch/dispatch_test.c | 55 ++++++++++++++++++++++++++++++++++- 6 files changed, 101 insertions(+), 21 deletions(-) mode change 100644 => 100755 bin/generate.ts diff --git a/CMakeLists.txt b/CMakeLists.txt index 500b6a89..a180b0a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,6 +60,13 @@ configure_file( function(config_library target) target_sources(${target} PRIVATE ${LLHTTP_SOURCES} ${LLHTTP_HEADERS}) + # Enable the runtime SSE4.2 dispatch in api.c only where the second object + # (llhttp_sse42.c) is also compiled, so a build without it keeps the baseline + # path and does not reference llhttp__internal_execute_sse42. + if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$") + target_compile_definitions(${target} PRIVATE LLHTTP_SSE42_DISPATCH) + endif() + target_include_directories(${target} PUBLIC $ $ diff --git a/Makefile b/Makefile index 7fdb4c41..75581316 100644 --- a/Makefile +++ b/Makefile @@ -11,13 +11,23 @@ endif INCLUDES += -Ibuild/ -# On x86-64, also build a second instantiation of the generated parser with -# -msse4.2 so llhttp_execute() can select the SSE4.2 span scanners at runtime -# (see src/native/api.c). The default build passes no -march, so without this -# the SSE4.2 code generated under `#ifdef __SSE4_2__` is never compiled in. -ARCH ?= $(shell uname -m) -ifneq (,$(filter $(ARCH),x86_64 amd64 AMD64)) +# On x86-64 (non-Windows), also build a second instantiation of the generated +# parser with -msse4.2 so llhttp_execute() can select the SSE4.2 span scanners +# at runtime (see src/native/api.c). The default build passes no -march, so the +# SSE4.2 code generated under `#ifdef __SSE4_2__` is otherwise never compiled +# in. LLHTTP_SSE42_DISPATCH enables the dispatch in api.c and is defined only +# here, where the second object is also built. Detect the *target* from the +# compiler, not the host (uname -m), so a cross-compile (e.g. CLANG with +# --target=aarch64-...) does not add an x86-only object. Windows/MSVC is +# skipped (no __builtin_cpu_supports), matching the CMake and gyp builds. +TARGET_MACHINE ?= $(shell $(CLANG) $(CFLAGS) -dumpmachine 2>/dev/null) +TARGET_CPU := $(firstword $(subst -, ,$(TARGET_MACHINE))) +IS_WINDOWS := $(or $(findstring windows,$(TARGET_MACHINE)),$(findstring mingw,$(TARGET_MACHINE))) +ifeq (,$(IS_WINDOWS)) +ifneq (,$(filter $(TARGET_CPU),x86_64 amd64)) SSE42_OBJ = build/c/llhttp_sse42.o + CFLAGS += -DLLHTTP_SSE42_DISPATCH +endif endif INSTALL ?= install diff --git a/bin/generate.ts b/bin/generate.ts old mode 100644 new mode 100755 diff --git a/src/llhttp.gyp b/src/llhttp.gyp index 95022cd1..28bb6425 100644 --- a/src/llhttp.gyp +++ b/src/llhttp.gyp @@ -26,6 +26,9 @@ # api.c is then compiled out and the symbol is not referenced). ['OS!="win" and (target_arch=="x64" or target_arch=="x86_64")', { 'dependencies': [ 'llhttp_sse42' ], + # Enables the dispatch in api.c; defined only here, where the second + # object is also built, so other consumers keep the baseline path. + 'defines': [ 'LLHTTP_SSE42_DISPATCH' ], }], ], }, diff --git a/src/native/api.c b/src/native/api.c index 3c483659..d6add329 100644 --- a/src/native/api.c +++ b/src/native/api.c @@ -122,24 +122,31 @@ void llhttp_reset(llhttp_t* parser) { } -#if (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ - (defined(__GNUC__) || defined(__clang__)) -/* A second instantiation of the generated parser, compiled with -msse4.2 (see - * llhttp_sse42.c), which turns on the SSE4.2 span scanners that the generated - * code guards with `#ifdef __SSE4_2__`. The default x86-64 build (no -march) - * never contains them, so pick the SSE4.2 build once at runtime. Both - * instantiations come from the same generated source, so the parser state - * layout is identical and a parser may be driven by either. */ +/* Opt-in runtime SSE4.2 dispatch. The build system defines + * LLHTTP_SSE42_DISPATCH only when it also compiles the second parser + * instantiation (llhttp_sse42.c, built with -msse4.2); see the Makefile, + * CMakeLists.txt and src/llhttp.gyp. A consumer that compiles llhttp.c, api.c + * and http.c directly with its own build system (aiohttp, distro packagers, + * other bindings) does not define it and keeps the baseline path, so it needs + * no second object and does not get an unresolved + * llhttp__internal_execute_sse42. _MSC_VER is excluded because MSVC/clang-cl + * lack __builtin_cpu_supports and those builds skip the second object anyway. */ +#if defined(LLHTTP_SSE42_DISPATCH) && \ + (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ + !defined(_MSC_VER) && (defined(__GNUC__) || defined(__clang__)) +/* The second instantiation turns on the SSE4.2 span scanners that the + * generated code guards with `#ifdef __SSE4_2__`; the default x86-64 build (no + * -march) never contains them. Both instantiations come from the same + * generated source, so the parser state layout is identical and a parser may + * be driven by either. */ llhttp_errno_t llhttp__internal_execute_sse42(llhttp_t* state, const char* p, const char* endp); -static int llhttp__sse42 = -1; - llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) { - if (llhttp__sse42 < 0) { - llhttp__sse42 = __builtin_cpu_supports("sse4.2") ? 1 : 0; - } - if (llhttp__sse42) { + /* __builtin_cpu_supports only loads and tests __cpu_model, which libgcc / + * compiler-rt initialize in a constructor, so there is no benefit to caching + * the result and no data race from doing without the cache. */ + if (__builtin_cpu_supports("sse4.2")) { return llhttp__internal_execute_sse42(parser, data, data + len); } return llhttp__internal_execute(parser, data, data + len); diff --git a/test/dispatch/dispatch_test.c b/test/dispatch/dispatch_test.c index 3d4cc87d..1888fa60 100644 --- a/test/dispatch/dispatch_test.c +++ b/test/dispatch/dispatch_test.c @@ -20,6 +20,19 @@ #include "llhttp.h" +/* When the library is built with the SSE4.2 dispatch (LLHTTP_SSE42_DISPATCH, + * set by the Makefile/CMake/gyp on x86-64), expose the internal entry point of + * the -msse4.2 instantiation so the test can drive it directly and confirm it + * is linked and correct -- otherwise the test would pass on the baseline path + * alone and never actually prove the SSE4.2 path works. */ +#if defined(LLHTTP_SSE42_DISPATCH) && \ + (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ + !defined(_MSC_VER) && (defined(__GNUC__) || defined(__clang__)) +#define LLHTTP_HAVE_SSE42_ENTRY 1 +llhttp_errno_t llhttp__internal_execute_sse42(llhttp_t* state, const char* p, + const char* endp); +#endif + static const char kRequest[] = "GET /de/catalog?q=widget&page=2 HTTP/1.1\r\n" "Host: shop.example.de\r\n" @@ -112,6 +125,23 @@ static int run(counters_t* c, int chunked) { return (int) llhttp_execute(&parser, kRequest, len); } +#ifdef LLHTTP_HAVE_SSE42_ENTRY +/* Drive the SSE4.2 instantiation directly (llhttp_execute dispatches to this + * same entry on SSE4.2-capable CPUs). Single shot, so the SSE span scanners + * run. */ +static int run_sse42(counters_t* c) { + llhttp_settings_t settings; + llhttp_t parser; + size_t len = sizeof(kRequest) - 1; + + init_settings(&settings); + llhttp_init(&parser, HTTP_REQUEST, &settings); + memset(c, 0, sizeof(*c)); + parser.data = c; + return (int) llhttp__internal_execute_sse42(&parser, kRequest, kRequest + len); +} +#endif + static int eq(const counters_t* a, const counters_t* b) { return a->messages == b->messages && a->headers == b->headers && @@ -153,7 +183,30 @@ int main(void) { return 1; } - printf("dispatch test OK: 1 message, %d headers, url=%zu, values=%zu bytes\n", +#ifdef LLHTTP_HAVE_SSE42_ENTRY + if (__builtin_cpu_supports("sse4.2")) { + /* The library has the dispatch and this CPU supports SSE4.2, so the + * single-shot run above took the SSE4.2 path. Confirm that instantiation + * is linked and parses identically to the baseline. */ + counters_t sse; + int err_sse = run_sse42(&sse); + if (err_sse != (int) HPE_OK) { + fprintf(stderr, "SSE4.2 instantiation parse failed: %d\n", err_sse); + return 1; + } + if (!eq(&one_shot, &sse)) { + fprintf(stderr, "SSE4.2 instantiation diverged from the baseline parse\n"); + return 1; + } + printf("dispatch test OK: SSE4.2 path exercised and matches baseline; "); + } else { + printf("dispatch test OK (CPU lacks SSE4.2, baseline path): "); + } +#else + printf("dispatch test OK (no SSE4.2 dispatch in this build): "); +#endif + + printf("1 message, %d headers, url=%zu, values=%zu bytes\n", one_shot.headers, one_shot.url_len, one_shot.header_value_len); return 0; }