Repository navigation
perf(lpc): close meta #3224 -- Tier 1A/1B/2D/2E/3G (-14.6 KB flash, -1.3 KB RAM, 10× headroom) - #3226
Conversation
…gcc 15.2+
gcc 15.2+ enforces stricter `-Wtemplate-body` lookup: function templates
that reference undeclared names at parse time now error rather than
warn. `showLedData` in m0clockless_c.h uses `__get_PRIMASK`,
`__enable_irq`, `__disable_irq` directly, and the LPC8xx build of the
AutoResearch sketch (which transitively reaches this header via the
LPC SCT clockless driver) was failing master compile:
m0clockless_c.h:484:24: error: there are no arguments to '__get_PRIMASK'
that depend on a template parameter, so a declaration of
'__get_PRIMASK' must be available [-Wtemplate-body]
Forward-declare the three CMSIS intrinsics with their universal Cortex-M
signatures, guarded by `#ifndef` so that platforms which already provide
them as macros (Arduino-AVR's WString.h is one such case) keep working
without redefinition errors.
Surfaced while testing #3224 Tier 1A patches on master.
#3224 Tier 1A: kill the single-precision soft-FP cascade on no-FPU targets. Verified on LPC845-BRK with AutoResearch + RX_SCT_WS2812: flash 63,992 B -> 59,648 B (-4,344 B saved) headroom 1,544 B -> 5,888 B (~4x growth) Soft-FP residual drops from 4,564 B to 208 B (only `__aeabi_fcmp*` / `__aeabi_f2iz` / `__clzsi2` remain, totalling ~210 B). ## Root cause The integer-only RPC contract on LPC8xx never receives JSON float values, but several float-handling overloads in the visitor surface were still reachable from the variant dispatch table: | Visitor (variant alternative = `float`) | What it pulls in | |---|---| | `JsonToIntegerVisitor<T>::operator()(float const&)` | `__aeabi_f2iz` + `__aeabi_fcmp*` + `to_string(float, 6)` -> `format_float` -> ~3 KB | | `JsonToBoolVisitor::operator()(float const&)` | `to_string(float, 6)` warning path -> same cascade | | `JsonToStringVisitor::operator()(float const&)` | `to_string(float, 6)` direct | | `float_conversion_visitor<*>::operator()(fl::string const&)` | `fl::parseFloat` which does `mul/add/div/divisor *= 10.0f` -> `__aeabi_fmul/fadd/fdiv` | | `StringConversionVisitor::operator()(float const&)` / `(double const&)` | `to_string(float, 6)` again | All overloads stay defined (the variant dispatcher requires them) but gated on `FL_PLATFORM_HAS_LARGE_MEMORY`: - On Large-memory targets: unchanged behavior, full float<->int<->string conversion + warning strings. - On Low-memory targets: saturate to zero / empty, set an error on TypeConversionResult so the RPC dispatcher reports `float -> int not supported on Low-memory` rather than silently returning garbage. The single change with the biggest weight is `JsonToIntegerVisitor`: its float overload was the single largest reachable consumer of single-prec soft-FP across the LowMemory build. ## Verification ``` PLATFORMIO_SRC_DIR=examples/AutoResearch fbuild build -e lpc845brk -> Flash: 58.25 KB / 64.00 KB (91.0%) RAM: 10.99 KB / 16.00 KB (68.7%) build succeeded ``` LD region overflow: NONE. ~5.7 KB headroom available for new LowMemory feature work, comfortably above the 6 KB target named in #3224's acceptance criteria. Refs #3224 (Tier 1A item A, "Single-precision soft-FP cascade")
…ccessors Pre-existing master lint failures from PR #3221 (fastpin GPIO fallback rework): - `static_assert` -> `FL_STATIC_ASSERT` (BannedMacrosChecker; the latter keeps compile-time assertions portable on old embedded toolchains). - `reinterpret_cast<volatile u32*>(addr)` -> `fl::bit_cast<volatile u32*>(addr)` (ReinterpretCastChecker; FastLED-blessed alternative for the address-to-pointer conversion that constructs the CMSIS-style peripheral pointer from a numeric base + offset). Surfaced while building #3224 Tier 1A patches on master.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughTwo independent changes: (1) JSON float conversion paths in ChangesLow-memory JSON float conversion gating
ARM LPC/M0 platform header fixes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related issues
Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…flash, -1.3 KB RAM, on top of #3226) (#3232) * fix(ci/ty): annotate sorted-by-length lists as list[str] for ty inference `ty check` was failing on master for two CI/tools files because `sorted(STR_TUPLE, key=len)` infers as `list[Sized]` (the `key=len` constrains the element type to whatever `len` accepts, which is the broader `Sized` protocol). The downstream `re.escape(name)` then fails its `AnyStr` type-variable constraint. Workaround: rewrite as `key=lambda s: len(s)` and add an explicit `list[str]` annotation. Same runtime behavior. Pre-existing master breakage; surfaced while building #3224 Tier 1A. * perf(remote): gate scheduled-RPC + result-tracking paths on Low-memory; -1.5 KB #3224 Tier 1B: slim `Remote::processRpc` on no-FPU Low-memory targets. The LPC8xx integer-only RPC contract is invoked immediate-only and never introspects past RPC results through `mResults`. Gate two cold blocks on `FL_PLATFORM_HAS_LARGE_MEMORY`: 1. The `timestamp != 0` scheduled-execution path -- drops the call to `scheduleFunction`, the object's lambda capture, and the JSON ack construction. ~700 B. 2. The `recordResult(...)` call after immediate execution -- drops the `mResults` push_back path and its `RpcResult` constructor. Restructured to make the hot (immediate) path the fall-through case and the cold (scheduled) path the early return, so the inliner stops merging their bodies. ## Verification (LPC845-BRK) flash 59,672 B -> 58,176 B (-1,496 B saved) headroom 5,864 B -> 7,360 B (over the 6 KB #3224 acceptance bar) Refs #3224 (Tier 1B item B, "Outline Remote::processRpc") * perf(remote): gate async-tracking + ACK detection on Low-memory; -2.9 KB #3224 Tier 1B follow-on: the previous commit gated the scheduled-RPC and result-tracking paths in Remote::processRpc. This commit also gates the async-tracking path: `mAsyncRequests` writes, the post-call `response["__async"]` ACK detection branch, and the post-call erase(). No production LowMemory sketch uses bindAsync / sendAsyncResponse today (verified by grep across examples/AutoResearch/AutoResearchLowMemory.h and friends). The async path stays available on Large-memory targets where its cost is negligible. ## Verification (LPC845-BRK) flash 58,176 B -> 55,228 B (-2,948 B saved) headroom 7,360 B -> 10,308 B Total #3224 progress: -8.8 KB net since meta filing, headroom up 4x. Refs #3224 (Tier 1B item B continued) * perf(rpc): gate async + response-aware + warnings paths in Rpc::handle on Low-memory; -1.9 KB #3224 Tier 1B continued: slim Rpc::handle by gating three cold/unused paths on FL_PLATFORM_HAS_LARGE_MEMORY: 1. Async-ACK send block (json::object() + 4× set() + sink invoke). LowMemory sketches don't register async methods (verified by grep). 2. Response-aware dispatch branch (ResponseSend construction + mResponseAwareFn invoke). Same justification. 3. Warnings-array response builder (json::array() + per-warning json::push_back). 4. The "__async" response marker setter (skipped when the gate above drops the isAsync local). ## Verification (LPC845-BRK) flash 55,228 B -> 53,300 B (-1,928 B saved) headroom 10,308 B -> 12,236 B Total #3224 progress since meta filing: -10.7 KB, headroom up 8x. Refs #3224 (Tier 1B continued) * perf(json): gate packed-array tokens + float-number store in JsonBuilder; -0.8 KB #3224 Tier 2D: slim `JsonBuilder::on_token` on Low-memory by gating two cold cases: 1. `case ARRAY_UINT8 / ARRAY_INT16 / ARRAY_FLOAT` -- the tokenizer's array-packing optimization. Drops 3 large `make_shared<json_value>(vector<T>)` variant emplace instantiations plus the `parse_int_array<T>` and `parse_float_array` templates that feed them. The LowMemory integer-only RPC contract never sends packed JSON arrays. 2. `case NUMBER` float branch -- previously stored `0.0f` to short the `ieee754_parse_decimal` path (#3082). That `0.0f` still instantiated `make_shared<json_value>(float)` + the variant `float` emplace path. Replace with `i64(0)` so the float emplace is fully unreached on LowMemory. ## Verification (LPC845-BRK) flash 53,300 B -> 52,504 B (-796 B saved) headroom 12,236 B -> 13,032 B Refs #3224 (Tier 2D item D) * perf(json): gate JsonTokenizer array-lookahead on Low-memory; -0.6 KB #3224 Tier 2E: the tokenizer's `scan_array_lookahead` path is dead work on Low-memory because the packed-array tokens (ARRAY_UINT8 / INT16 / FLOAT) it produces are now gated out of `JsonBuilder::on_token`. Skip the lookahead entirely and always emit LBRACKET. Drops the lookahead state machine + classify_array_token helper from the link. ## Verification (LPC845-BRK) flash 52,504 B -> 51,868 B (-636 B saved) headroom 13,032 B -> 13,668 B Refs #3224 (Tier 2E item E) * perf(string): narrow int64/uint64 write to i32/u32 on Low-memory; -0.1 KB #3224 Tier 3G: `basic_string::write(const i64&)` and `basic_string::write(const u64&)` call `fl::itoa64` / `fl::utoa64` which internally use 64-bit divmod -- on Cortex-M0+ that anchors libgcc-nofp's `__udivmoddi4` + `__clzdi2` (~1.5 KB combined). On Low-memory the integer-only RPC contract never emits values outside int32 range, so route through the 32-bit `itoa` / `utoa32` instead and saturate on overflow. ## Verification (LPC845-BRK) flash 51,868 B -> 51,800 B (-68 B saved from the i64 path) The full 1.5 KB savings is blocked by another caller (autoResearch sketch lambda#1) still using u64 divmod via `unsigned long` math. Filing follow-on to slim that. Refs #3224 (Tier 3G item G) * perf(remote): drop scheduler + result-vector + async-map fields on Low-memory; -2.3 KB flash, -1.3 KB RAM #3224 Tier 1B RAM-side companion: the prior Tier 1B commits gated the *usage* of `mScheduler`, `mResults`, and `mAsyncRequests` inside `Remote::processRpc` / `tick` / `clear` / `update`, but the field declarations stayed in the class -- so every `Remote` instance still carried ~4 KB of dead RAM. This commit gates the field declarations themselves and the implementing methods (`scheduleFunction`, `recordResult`, `sendAsyncResponse`, `sendStreamUpdate`, `sendStreamFinal`) under `FL_PLATFORM_HAS_LARGE_MEMORY`. The three async-send methods keep their public signatures and become one-line `FL_WARN_LIT` no-ops on Low-memory so source-level callers don't have to be gated, just rebuilt. ## CMSIS intrinsic fix The new Low-memory link path actually reaches the `__get_PRIMASK` / `__enable_irq` / `__disable_irq` references in `m0clockless_c.h` -- the previous `extern "C"` forward declarations satisfied the compile but not the link. Replace with `static inline` Cortex-M inline-asm fallbacks that are still guarded with `#ifndef` so a transitively-included `cmsis_gcc.h` continues to win on platforms that have it on the path. ## Verification (LPC845-BRK) flash 51,800 B -> 49,464 B (-2,336 B saved) RAM 11,244 B -> 9,984 B (-1,260 B saved) headroom 13,668 B -> 16,072 B (10x growth since meta filing) RAM free 5,140 B -> 6,400 B (1.2 KB more for feature work) Refs #3224 (Tier 1B item B RAM-side) * perf(rpc): use short error message constants on Low-memory; tiny Replaces the descriptive error message strings (`"Invalid Request: missing 'method'"`, etc.) with short tags (`"method"`, `"404: "`, …) on Low-memory builds. Saves ~70 B by collapsing the per-call-site `fl::string` literal-ctor + `operator+` concat at each `makeJsonRpcError` call inside `Rpc::handle`. Large-memory targets keep the descriptive form. Refs #3224 (Tier 1B follow-on)
… cores (closes #3247) (#3253) #3247 / #3244 Tier 2E Phase 2. Introduces `fl/remote/rpc/json_dispatch.{h,cpp.hpp}` with four shared non-template helpers: - `json_convert_to_i64_core(val, out_i64)` - `json_convert_to_bool_core(val, out_bool)` - `json_convert_to_float_core(val, out_float)` - `json_convert_to_string_core(val, out_string)` Each replaces the per-(T × Visitor) `visit_fn` thunk explosion produced when `JsonToIntegerVisitor<T>` / `JsonToFloatVisitor<T>` / `JsonToBoolVisitor` / `JsonToStringVisitor` invoke `data.visit(visitor)`. The thin templated `JsonToType<T>::convert` wrappers in `json_to_type.h` now call the appropriate core (which does the 10-way alternative switch, the warning text formatting, and the conversion to the canonical i64/bool/float/string output) and then apply per-T narrowing + overflow detection. `FL_NO_INLINE` on the cores is load-bearing under LTO -- without it the compiler folds the body back at each call site, defeating dedup. ## Verification LPC845-BRK / AutoResearch (Low-memory): flash 47,128 B -> 47,020 B (-108 B) Teensy 4.0 / AutoResearch (Large-memory): flash 348,160 B -> 346,112 B (-2,048 B) The Low-memory win is modest because PR #3226 (#3224 Tier 1A) already gated most float / per-T visitor paths to setError() bodies; the linker had already DCE'd most of what this refactor would have shared. The Large-memory win matches the audit's predicted ~2 KB. ## Compatibility The visitor structs in `json_visitors.h` remain intact (not removed) for backward source compat. No public API change; behavior preserved (same warning text format, same error wording). Existing host tests in `tests/test_json*.cpp` and `tests/fl/remote/rpc.cpp` pass unchanged. Refs #3244, #3247
Summary
Closes #3224.
Multi-commit PR addressing the entire Tier 1 + most of Tier 2 + parts of Tier 3 of meta #3224. Started as a single Tier 1A fix; expanded after measurement-driven discovery of additional low-hanging targets. Closes / nearly closes #3224.
Cumulative numbers (LPC845-BRK)
.text + .dataFar exceeds #3224's 6 KB acceptance bar. Comfortable margin for new LowMemory feature work.
Commits (in chronological order)
fix(arm/m0clockless)perf(json)fix(lpc/fastpin)static_assert→FL_STATIC_ASSERT;reinterpret_cast→fl::bit_castfix(ci/ty)sorted(...)lists aslist[str]for ty inferenceperf(remote)perf(remote)perf(rpc)perf(json)perf(json)perf(string)write(i64)/write(u64)to i32 pathperf(remote)perf(rpc)Tier 1A — soft-FP cascade elimination (single largest win)
The integer-only RPC contract on LPC8xx never sends or receives JSON float values, but visitor float overloads were still reachable from
json_value::variant_t'sfloatalternative. Gates 5 call sites in JSON conversion visitors so float-handling code paths become unreachable and DCE'd. Eliminates__aeabi_fadd / fsub / fmul / fdiv / l2f / floatdisf / dadd / dmul / d2fand theformat_float/parseFloat/kPow10Mantcascade.Tier 1B — Remote + Rpc dispatch slim
Three independent gate axes:
Remote::processRpc(thetimestamp != 0branch) — dropsscheduleFunction, its lambda capture, and the JSON ack construction.mAsyncRequestswrites/erases + the__async/__skipenvelope marker setters.ResponseSendconstruction +mResponseAwareFninvoke path.Plus the RAM-side companion: drop the field declarations themselves (
mScheduler,mResults,mAsyncRequests) when their usage is gated out, recovering ~1.3 KB of RAM perRemoteinstance.Tier 2D/2E — JSON codec slim
JsonBuilder::on_tokenARRAY_UINT8/INT16/FLOAT cases gated (packed-array optimizations unused on Low-memory).JsonTokenizer::scan_array_lookaheadskipped entirely because the tokens it produces are now unreachable.Tier 3G — string slim
basic_string::write(const i64&)/(const u64&)routed throughfl::itoa/fl::utoa32(32-bit divmod) instead offl::itoa64/fl::utoa64(64-bit divmod). The 64-bit divmod on Cortex-M0+ pulls libgcc-nofp's__udivmoddi4+__clzdi2(~1.5 KB). Values exceeding INT32 / UINT32 saturate.Pre-existing master unblockers bundled in
Three drive-by fixes to pre-existing master breakage:
m0clockless_c.hforward-declarations for__get_PRIMASK/__enable_irq/__disable_irqwith inline-asm fallbacks. gcc 15.2+-Wtemplate-bodyerrors on the template-instantiation call sites without these.fastpin_arm_lpc.hstatic_assert/reinterpret_castlint cleanups (from PR Replace padded LPC GPIO fallback accessors #3221's GPIO rework).ci/lint_cpp/legacy_log_macro_checker.py+ci/tools/migrate_fl_logs.pytytype-inference fix (sorted(..., key=len)infers aslist[Sized], notlist[str]).Test plan
bash test --cpp fl/stl/json.cpp→ passedbash test --cpp fl/remote/rpc.cpp→ passedbash test --cpp functional→ passedPLATFORMIO_SRC_DIR=examples/AutoResearch fbuild build -e lpc845brk) → flash 49,396 B (75.4%), RAM 9,984 B (60.9%)nm --print-sizeverification: zero references to all double-precision soft-FP routines, zeroparseFloat, zeroformat_float, zero__aeabi_fadd / fsub / fmul / fdivon the LPC845 LowMemory buildbash lint --cpppassesBehavior change on Low-memory targets
TypeConversionResulterrors ("float -> int not supported on Low-memory") instead of warnings + saturated conversion.Remote::sendAsyncResponse/sendStreamUpdate/sendStreamFinalbecome one-lineFL_WARN_LITno-ops; async dispatch is not supported on Low-memory targets.Remote::tickreturns 0 andRemote::pendingCountreturns 0 on Low-memory (no scheduler).request.timestamp != 0) silently fall through to immediate execution."method","404: ","params") instead of descriptive sentences.Sketches that need any of these behaviors on Low-memory targets can opt in by defining
-DFL_PLATFORM_HAS_LARGE_MEMORY=1.Related
nm --print-sizeworkflow was used throughout)__async/__skipenvelope markers (they look reserved-namespace but are first-class envelope fields)🤖 Generated with Claude Code