Skip to content

bloat: move more FL_WARN/FL_ERROR per-call-site code into log_emit (shrink call-site burst from ~200 B to ~50 B) #2982

Closed

Description

@zackees

Tracked in #2974 (sub-issue B — cross-cutting infrastructure change).

Background

PR #2968 landed Option 3: a centralized fl::detail::log_emit(log_kind, file, line, fl::sstream& body) helper, marked FL_NO_INLINE. The prefix-format chain (<< file << "(" << line << "): KIND: ") is now compiled exactly once in libFastLED instead of inlined at every site. Good.

But each call site STILL inlines the user-payload formatting burst:

// Macro expansion (src/fl/log/log.h:228):
#define FL_WARN(X) fl::detail::log_emit( \
    fl::detail::log_kind::WARN, \
    fl::fastled_file_offset(__FILE__), int(__LINE__), \
    fl::sstream() << X)

Per call site, the compiler emits:

  1. fl::sstream ctor — initializes the 64-byte inline mStr buffer (basic_string SSO + cap/size words)
  2. The operator<< chain — one call per argument (appendFormatted(long), append(const char*), etc.). Each templated overload resolves and emits an inlined ABI call.
  3. fl::fastled_file_offset(__FILE__) reference (113 B once, but the call instruction + arg setup is per-site)
  4. The log_emit call
  5. Exception landing pad metadata because sstream / basic_string dtors can throw (issue A — TBD)

Total per-call-site cost: ~200-300 B inline (verified in #2974's bloat report: each of the 8 functions in the 1-4 KB band carries 3-5 FL_WARN sites and pays ~600-1500 B of pure logging code on top of the shared log_emit 222 B callee).

There are 562+ FL_WARN/FL_ERROR/FL_INFO call sites in src/ today. Even modest per-site savings multiply.

Proposed approaches

All three preserve FASTLED_LOG_VERBOSITY=1 semantics. None disable logging.

Approach 1 — Variadic helper with internal sstream

Macro expands to a single call passing a literal format string + a parameter pack:

#define FL_WARN(...) fl::detail::log_emit_v( \
    fl::detail::log_kind::WARN, \
    fl::fastled_file_offset(__FILE__), int(__LINE__), \
    __VA_ARGS__)

// In log.cpp.hpp:
template <typename... Args>
FL_NO_INLINE void log_emit_v(log_kind kind, const char* file, int line, Args&&... args) FL_NOEXCEPT {
    fl::sstream body;
    (body << ... << args);  // C++17 fold; or recursive expand for C++11
    // ...prefix + emit, as today
}
  • Pro: sstream ctor + dtor move out of the call site. ~50 B per site for arg-pointer setup + call.
  • Con: Each instantiation of log_emit_v<Ts...> is template-uniqued by argument-type tuple. For the common shape (const char*, int) you get one copy; for (const char*, CRGB, int, vec2<int>) you get another. Risk: template-instantiation explosion could re-bloat .text if call sites use too many type combinations. Need to measure before/after.
  • Mitigation: mark the wrapper FL_NO_INLINE so each instantiation is one copy, and audit for unusual instantiations.

Approach 2 — Type-erased argument array

Convert the << chain into an array of (type_tag, void*) pairs, then loop in log_emit:

struct LogArg {
    enum Kind : fl::u8 { kCStr, kI32, kU32, kI64, kU64, kFloat, kCRGB, kCustom };
    Kind kind;
    union { const char* s; fl::i64 i; fl::u64 u; double f; const void* p; };
    // For kCustom: function pointer to a "append T to sstream" thunk
    void (*append_thunk)(fl::sstream&, const void*);
};

#define FL_WARN(...) do { \
    fl::detail::LogArg _args[] = { fl::detail::make_log_arg(__VA_ARGS__) ... }; \
    fl::detail::log_emit_args(log_kind::WARN, file, line, _args, sizeof(_args)/sizeof(_args[0])); \
} while(0)
  • Pro: Zero template combinatorics. One log_emit_args instantiation total. Per-site cost is just LogArg initialization (~16 B per arg) + array address + call.
  • Con: Requires a fold-style macro (FOR_EACH(__VA_ARGS__) with a builder per arg). Composite types (CRGB, vec2, vector, Tile2x2_u8) need an append_thunk function pointer per type — one shared thunk per type, no per-site cost.
  • Con: << chain ergonomics is lost — would need to rewrite call sites to FL_WARN("foo ", x, " bar ", y) (comma-separated) instead of FL_WARN("foo " << x << " bar " << y). This breaks 562 call sites. Could be done with a sed pass but is invasive.

Approach 3 — Printf-style variadic with __attribute__((format(printf,...)))

Pure C-style: FL_WARN_FMT("foo %d bar %s", x, str). Compiler validates format specifiers.

  • Pro: Tiny call site — lea of literal + mov args + call. ~30-50 B per site. No sstream, no temporary, no landing pad.
  • Pro: Reuses fl::printf-style snprintf into a stack buffer.
  • Con: Loses CRGB / Tile2x2_u8 / vec2 / vector / Optional / Bins / span / pair / bitset_fixed / unordered_map / flat_map operator<< overloads in strstream.h. No way to plug those in.
  • Con: Same call-site rewrite burden as approach 2.
  • Verdict: Probably only useful as a new macro (FL_WARN_FMT) for hot, format-string-friendly sites; not a wholesale replacement.

Approach 4 (hybrid, recommended) — Approach 1 with grouped overloads for common shapes

Use approach 1, but add a small overload set for the common shapes that funnel into shared out-of-line emit functions:

// Header — small inline forwarders, one per common arity:
inline void log_emit_v(log_kind k, const char* f, int l, const char* msg) FL_NOEXCEPT {
    log_emit_string(k, f, l, msg);   // out-of-line; no sstream needed
}
inline void log_emit_v(log_kind k, const char* f, int l, const char* prefix, fl::i32 n) FL_NOEXCEPT {
    log_emit_string_i32(k, f, l, prefix, n);   // out-of-line; common pattern
}
// Fall-through for everything else:
template <typename... Args>
FL_NO_INLINE void log_emit_v(log_kind k, const char* f, int l, Args&&... args) FL_NOEXCEPT { ... }
  • The string-literal-only sites (the majority of FL_WARN("[RMT] something happened") patterns) hit a non-template overload that's pure forwarding to one out-of-line emit function. ~10 B per site.
  • The (const char*, int) and (const char*, const char*) shapes also hit dedicated overloads — likely covers another 30 % of sites.
  • Everything else falls through the template path (small number of unique combinations).

This is the lowest-risk option that preserves the << X ergonomics by virtue of NOT switching syntax. It requires no call-site rewrites. The << chain is still allowed via the existing macro for backward compat; new code uses comma-separated args via a new FL_WARN_V(...) macro that piggybacks on log_emit_v. Both can coexist while migration happens.

Trade-offs / risks

  • LTO already deduplicates operator<< bodies, so the savings here are in the call-site burst (sstream ctor + arg-pointer marshalling + dtor + landing pad), not in operator<< itself. The PR will measure the per-site delta on a representative file (e.g. src/fl/channels/manager.cpp.hpp has 22 sites — a clean before/after comparison).
  • Composite formatters (CRGB, Tile2x2_u8, vec2, rect, Optional, vector, span, pair, unordered_set/map, flat_map, unsorted_map_fixed, bitset_*, audio::fft::Bins) live in src/fl/stl/strstream.h and are tied to sstream. Approaches 1 and 4 preserve them (still go through sstream internally). Approaches 2 and 3 lose them unless we register every type with a thunk.
  • Template instantiation explosion is the only real downside of approach 1/4 — we MUST measure binary size before/after, on at least:
  • Macro variadic complexity: approach 4 requires careful overload set design so unintended types don't fall through to the template path silently.
  • Layers on top of PR feat(log): centralised log_emit helper (Proposal B Option 3 of #2963) #2968 Option 3, does not replace it. log_emit(...) keeps the centralized prefix-format chain. This issue moves the user-payload-side burst out of the call site too.
  • Sequencing with sub-issue A (TBD): marking string / sstream dtors noexcept (A) eliminates landing pads independently. Doing A first probably recovers ~50 % of the savings without touching the macro. This issue (B) covers the remaining ~50 %. Land A first, re-measure, then evaluate which variant of B is worth the complexity.

Estimated savings

Component Per-site savings Sites Total (gross, pre-LTO)
sstream ctor inline ~30-50 B 562 ~17-28 KB
sstream dtor inline ~20-40 B 562 ~11-22 KB
<< chain templated thunks ~50-100 B 562 ~28-56 KB
Landing pad metadata ~100-200 B 562 covered by sibling issue A

Realistic post-LTO net savings, conservative estimate: ~150 B per site × 30+ "hot" call sites in the 1-4 KB band → ~4-5 KB on ESP32-S3 Blink. Across the broader 562-site population on bigger sketches, possibly 8-15 KB total.

This is the cross-cutting half of #2974 — it does not by itself move any individual function out of the 1-4 KB band, but it lowers the floor for every FastLED function that uses logging. Per-function fixes (issues TBD-D through TBD-I) still apply on top.

Verification plan

  • Pick a representative source file with 5+ FL_WARN sites (e.g. src/fl/channels/manager.cpp.hpp — 22 sites).
  • Compile it standalone with the current toolchain at -Os -flto, capture per-function .text sizes via bash bloat esp32s3 --filter manager.
  • Apply approach 4 prototype, re-measure.
  • Disassemble one before/after FL_WARN site with llvm-objdump -d to confirm the per-site shrink.
  • Run full ESP32-S3 Blink fbuild and compare .build/symbols/esp32s3-fbuild/report.md against the Reduce per-symbol bloat in the FastLED 1-4KB function band on ESP32-S3 (logging must stay enabled) #2974 baseline.
  • Run bash test --cpp to confirm host tests still produce expected log output.

Refs

Activity

  1. zackees commented on Aug 20, 2026

    @zackees
    MemberAuthor

    Deferred after current-master triage.

    PR #3190 (da59e86e24) substantially superseded the proposed implementation by migrating active in-tree call sites to printf-style FL_*_F forms and adding LegacyLogMacroChecker; the current Rust-backed C++ lint gate passes and prevents active legacy stream-style sites from returning. Later #3272 unified the public macro spelling while retaining the one-argument stream path for compatibility.

    This is not safe to close as measured-complete. Neither #3190 nor current master provides this issue's requested logging-enabled before/after for a representative multi-site function, call-site disassembly, or same-SHA ESP32-S3 full-Blink comparison. The current 341,048 B release bloat result uses logging-off configuration and therefore cannot validate the claimed ~200 B -> ~50 B logging-on reduction. The compatibility path still constructs fl::sstream() for single-argument/stream calls, so the original architecture question remains for downstream callers even though FastLED's active production sites avoid it.

    Restart when a reproducible FASTLED_LOG_VERBOSITY=1 bloat job/report exists. Re-baseline one 5+ call-site source function plus full ESP32-S3 Blink, preserve before/after disassembly and output-equivalence tests, and then either (a) close this as superseded by #3190 with measured evidence, or (b) prototype the remaining out-of-line/type-erased payload path and prove a net size win without template-instantiation growth.

  2. added
    deferred
    on Aug 20, 2026
  3. moved this from Triage to Done in FastLED Trackeron Sep 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    deferred

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions