From 1647dc457d8ace9ec16964ad0dedc49873496969 Mon Sep 17 00:00:00 2001 From: Churkin Aleksey Date: Wed, 25 Nov 2026 16:09:09 +0300 Subject: [PATCH 1/5] dasLLAMA image: the layout fingerprint writes its description once layout_describe built the meta closure's description with += on a string: each append copies the whole description, and the copies stay on the string heap until a collection - 226 MB a Kokoro load, 77 MB a Pocket load. It is written into one build_string writer now: the same text, so the same fingerprint, and every image on disk stays valid. test_layout_fingerprint prints the Model closure a second time and holds the string heap within 256 KB of where it stood. --- modules/dasLLAMA/dasllama/dasllama_image.das | 17 +++++++++-------- modules/dasLLAMA/tests/test_model_image.das | 6 +++++- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/modules/dasLLAMA/dasllama/dasllama_image.das b/modules/dasLLAMA/dasllama/dasllama_image.das index 78905f2d73..e9deaca1c1 100644 --- a/modules/dasLLAMA/dasllama/dasllama_image.das +++ b/modules/dasLLAMA/dasllama/dasllama_image.das @@ -1177,20 +1177,21 @@ def count_meta_fields(var t) : int { //! name + full type name + byte size in order, recursing into struct fields and array-element //! structs — any meta-closure shape change refuses by name; IMAGE_VERSION covers behavior. def layout_fingerprint(var t) : uint64 { - var d = "" - layout_describe(t, d) + let d = build_string() $(var w) { + layout_describe(t, w) + } return hash(d) } -def private layout_describe(var t; var d : string&) { +def private layout_describe(var t; var d : StringBuilderWriter) { apply(t) $(name : string; var field) { - d += "{name}:{typeinfo typename(field)}:{typeinfo sizeof(field)};" + d |> write("{name}:{typeinfo typename(field)}:{typeinfo sizeof(field)};") static_if (typeinfo is_struct(field)) { layout_describe(field, d) - d += "^" // close the nesting so sibling boundaries stay unambiguous + d |> write("^") // close the nesting so sibling boundaries stay unambiguous } static_elif (typeinfo is_dim(field)) { layout_describe(field[0], d) // one element's shape stands for the table - d += "^" + d |> write("^") } static_elif (typeinfo is_array(field)) { layout_describe_elem(field, d) } @@ -1198,12 +1199,12 @@ def private layout_describe(var t; var d : string&) { } // an array field's ELEMENT struct also serializes element-wise — its shape is load-bearing -def private layout_describe_elem(var a : array; var d : string&) { +def private layout_describe_elem(var a : array; var d : StringBuilderWriter) { static_if (typeinfo is_struct(type)) { unsafe { //! the zeroed value: a nested carrier's initializer chain overflows the init script's stack, and only the type is read var tmp : TT layout_describe(tmp, d) - d += "^" + d |> write("^") delete tmp } } diff --git a/modules/dasLLAMA/tests/test_model_image.das b/modules/dasLLAMA/tests/test_model_image.das index d0164cf15e..cac22addf1 100644 --- a/modules/dasLLAMA/tests/test_model_image.das +++ b/modules/dasLLAMA/tests/test_model_image.das @@ -4645,7 +4645,7 @@ def test_devw_bake_tables(t : T?) { } } -[test(description = "`layout_fingerprint` is deterministic per type and moves on field reorder, retype, add, nesting and array element shape, the Model closure fingerprints nonzero, and a flipped fingerprint byte at header offset 48 declines the image load")] +[test(description = "`layout_fingerprint` is deterministic per type and moves on field reorder, retype, add, nesting and array element shape, the Model closure fingerprints nonzero with its description written once, and a flipped fingerprint byte at header offset 48 declines the image load")] def test_layout_fingerprint(t : T?) { t |> run("the fingerprint moves on any field-shape change and holds on none") @(t : T?) { if (!arm_on(t, "mechanics")) { @@ -4670,6 +4670,10 @@ def test_layout_fingerprint(t : T?) { let mfp = layout_fingerprint(m) to_log(LOG_INFO, "image fingerprint: Model meta closure = {mfp}\n") t |> success(mfp != 0ul, "the real Model closure fingerprints (no recursion trap)") + let s0 = string_heap_bytes_allocated() + t |> equal(layout_fingerprint(m), mfp, "deterministic on the real closure") + let s1 = string_heap_bytes_allocated() + t |> success(s1 <= s0 + 262144ul, "the description is written once, not copied per field ({s0} -> {s1} bytes)") delete m } t |> run("a corrupted fingerprint byte refuses the image at parse") @(t : T?) { From 6db6abd63de1e1f821865aae51ed080ad8c28fac Mon Sep 17 00:00:00 2001 From: Churkin Aleksey Date: Wed, 25 Nov 2026 21:53:17 +0300 Subject: [PATCH 2/5] dasLLAMA whisper: the load frees its staging stream_whisper_model's WhisperStaging was a plain local, so every load left the staged planes on the heap until a collection: 1.6 MB of garbage a Whisper base load. force_inscope_pod does not cover it - the staging has a user finalize - so the local is inscope by hand. The load leaves 0 KB of heap garbage. --- modules/dasLLAMA/dasllama/dasllama_whisper.das | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/dasLLAMA/dasllama/dasllama_whisper.das b/modules/dasLLAMA/dasllama/dasllama_whisper.das index 531b53d4f3..c5dc88bf7f 100644 --- a/modules/dasLLAMA/dasllama/dasllama_whisper.das +++ b/modules/dasLLAMA/dasllama/dasllama_whisper.das @@ -754,7 +754,7 @@ def private stream_whisper_model(path : string; enc_q8, dec_q8 : bool; img, tag } var wrote = false fmap(f) $(var bytes : array#) { - var st = WhisperStaging() + var inscope st = WhisperStaging() var recs : table var encJobs, decJobs : array whisper_index(bytes, int64(stat(path).size), st, recs, encJobs, decJobs) From 5f539b0627365de731fe254964480863faea2ce7 Mon Sep 17 00:00:00 2001 From: Churkin Aleksey Date: Wed, 25 Nov 2026 21:53:17 +0300 Subject: [PATCH 3/5] dasLLAMA spm: a unigram encode leaves no string behind The lattice built a fresh string for every candidate piece it looked up and dropped it, and the encode built a dummy-space copy of its input: 460 bytes of string garbage an encode of a short sentence, 18 KB a Bergamot translate. spm_piece_of is [temp_string_result], so the reclaim pass frees each lookup key; the encode reads its input as an inscope byte array (the space, then the text's bytes) and makes no string. The same mark frees the piece the vocabulary reader rewrites. test_tokenizer_unigram_encode_no_garbage holds twenty encodes to the string heap one left (+9200 bytes before). --- modules/dasLLAMA/dasllama/dasllama_spm.das | 23 ++++++++++++++++------ modules/dasLLAMA/tests/test_tokenizer.das | 19 ++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/modules/dasLLAMA/dasllama/dasllama_spm.das b/modules/dasLLAMA/dasllama/dasllama_spm.das index 267a7d2f95..30cd2d1467 100644 --- a/modules/dasLLAMA/dasllama/dasllama_spm.das +++ b/modules/dasLLAMA/dasllama/dasllama_spm.das @@ -6,7 +6,7 @@ module dasllama_spm shared public require dasllama/dasllama_lint public require daslib/fio -require daslib/array_boost // nolint:STYLE030 — temp_array is [template]; STYLE030 misses template-fn refs +require daslib/array_boost require dasllama/dasllama_gguf require dasllama/dasllama_bpe require strings @@ -332,7 +332,8 @@ def unigram_unk_score(tk : SpmTokenizer) : float { return lo - UNIGRAM_UNK_PENALTY } -def private spm_piece_of(d : array const#; i, n : int) : string { +[temp_string_result] +def private spm_piece_of(d : array | #; i, n : int) : string { return "" if (n <= 0) unsafe { return string(temp_array(addr(d[i]), n, type)) @@ -340,7 +341,7 @@ def private spm_piece_of(d : array const#; i, n : int) : string { } // the next codepoint boundary after byte position i -def private cpt_end(d : array const#; i, n : int) : int { +def private cpt_end(d : array | #; i, n : int) : int { var j = i + 1 while (j < n && (int(d[j]) & 0xC0) == 0x80) { j++ @@ -351,7 +352,7 @@ def private cpt_end(d : array const#; i, n : int) : int { // the Viterbi lattice over byte positions: best[j] the highest score reaching j, back_len / // back_id the piece that got there; ties go to the earliest candidate (the reference's strict >); // a byte piece or a reserved control piece never matches text, as in the reference's trie -def private unigram_lattice(tk : SpmTokenizer; d : array const#; unk_id : int64; reserved : array; +def private unigram_lattice(tk : SpmTokenizer; d : array | #; unk_id : int64; reserved : array; var best : array; var back_len : array; var back_id : array) { let n = length(d) let unk_score = unigram_unk_score(tk) @@ -402,8 +403,17 @@ def unigram_encode(tk : SpmTokenizer; text : string; unk_id : int64; byte_fallba if (unk_id < 0l || unk_id >= long_length(tk.vocab)) { panic("dasLLAMA spm: unigram encode with no unknown piece (id {unk_id} of {length(tk.vocab)})") } - let input = tk.add_space_prefix ? " {text}" : text - peek_data(input) $(d : array const#) { + var inscope d : array + d |> reserve(length(text) + 1) + if (tk.add_space_prefix) { + d |> push(uint8(' ')) + } + peek_data(text) $(t : array const#) { + for (b in t) { + d |> push(b) + } + } + { var inscope best : array var inscope back_len : array var inscope back_id : array @@ -421,6 +431,7 @@ def unigram_encode(tk : SpmTokenizer; text : string; unk_id : int64; byte_fallba rev_len |> push(back_len[p]) p -= back_len[p] } + ids |> reserve(length(d)) var k = length(rev) - 1 while (k >= 0) { if (rev[k] == unk_id && byte_fallback) { diff --git a/modules/dasLLAMA/tests/test_tokenizer.das b/modules/dasLLAMA/tests/test_tokenizer.das index 2991f555c7..897f72e10f 100644 --- a/modules/dasLLAMA/tests/test_tokenizer.das +++ b/modules/dasLLAMA/tests/test_tokenizer.das @@ -259,6 +259,25 @@ def test_tokenizer_spm_byte_pieces_by_name(t : T?) { } } +[test(description = "A unigram encode leaves no string behind: the lattice frees each candidate piece it looks up, so twenty encodes of a sentence keep the string heap where one left it")] +def test_tokenizer_unigram_encode_no_garbage(t : T?) { + var pieces <- ["", "", "", " ", "a", "b", " a", "ab", " ab"] + var tk <- spm_vocab(pieces) + tk.max_token_length = 3 + tk.add_space_prefix = true + let reserved : array + let text = "ab ab ba ab ab ba ab ab ba ab ab ba" + var warm <- unigram_encode(tk, text, 0l, false, reserved) + delete warm + let before = string_heap_bytes_allocated() + for (_ in range(20)) { + var ids <- unigram_encode(tk, text, 0l, false, reserved) + delete ids + } + t |> equal(before, string_heap_bytes_allocated(), "the string heap after twenty encodes") + delete tk +} + [test(description = "On the Mistral v0.3 vocab, newline and tab byte pieces resolve to 781 and 780 past the control tokens, and sample texts encode to the exact ids llama-tokenize gives and decode back")] def test_tokenizer_mistral_v03_byte_pieces(t : T?) { t |> run("Mistral v0.3: byte pieces past 768 control tokens, llama-tokenize's ids") @(t : T?) { From 0fbc2bfd7cbb6a0482d60d4354a5350d204c28cd Mon Sep 17 00:00:00 2001 From: Churkin Aleksey Date: Wed, 25 Nov 2026 21:53:17 +0300 Subject: [PATCH 4/5] tests: the optimizer's tests get a folder of their own The optimization*.das files, dead_branch_folding and the four rtti uncategorized files that drive the inliner, CSE and fast-math move from tests/language to tests/optimization with their eight helper modules. The AOT build registers the folder as the optimization suite (its files and its module helpers, both in test_aot_subset); the per-PR AOT run, the fast-math runs and the sanitizer sweep take the folder beside tests/language, so the moved tests keep every run they had. The two paths utils/mcp and the lint skip fixture name follow the move. --- ci/test_ci_matrix.py | 3 +- tests/CMakeLists.txt | 23 ++++++------- tests/aot/CMakeLists.txt | 32 ++++++++++++------- .../stale_fixtures/_fixture_lint_skip.das | 2 +- .../_inline_constant_expression_helper.das | 0 .../_inline_counter_helper.das | 0 .../_inline_generic_helper.das | 0 .../_inline_scope_helper.das | 0 .../_inline_unoptimized_scope_helper.das | 0 .../_inline_unsafe_helper.das | 0 .../_never_inline_module.das | 0 .../_optimized_body_helper.das | 0 .../dead_branch_folding.das | 0 .../optimization.das | 0 .../optimization_auto_inline.das | 0 .../optimization_auto_inline_functions.das | 0 .../optimization_cse.das | 0 .../optimization_fast_math.das | 0 .../optimization_fold_shape.das | 0 .../optimization_inline.das | 0 .../optimization_inline_operators.das | 0 .../optimization_splat_order.das | 0 ...d_disable_auto_inline_no_coverage_rtti.das | 0 ...uncategorized_disable_auto_inline_rtti.das | 0 .../uncategorized_disable_cse_rtti.das | 0 .../uncategorized_fast_math_rtti.das | 0 utils/mcp/test_tools_lint.das | 4 +-- 27 files changed, 37 insertions(+), 27 deletions(-) rename tests/{language => optimization}/_inline_constant_expression_helper.das (100%) rename tests/{language => optimization}/_inline_counter_helper.das (100%) rename tests/{language => optimization}/_inline_generic_helper.das (100%) rename tests/{language => optimization}/_inline_scope_helper.das (100%) rename tests/{language => optimization}/_inline_unoptimized_scope_helper.das (100%) rename tests/{language => optimization}/_inline_unsafe_helper.das (100%) rename tests/{language => optimization}/_never_inline_module.das (100%) rename tests/{language => optimization}/_optimized_body_helper.das (100%) rename tests/{language => optimization}/dead_branch_folding.das (100%) rename tests/{language => optimization}/optimization.das (100%) rename tests/{language => optimization}/optimization_auto_inline.das (100%) rename tests/{language => optimization}/optimization_auto_inline_functions.das (100%) rename tests/{language => optimization}/optimization_cse.das (100%) rename tests/{language => optimization}/optimization_fast_math.das (100%) rename tests/{language => optimization}/optimization_fold_shape.das (100%) rename tests/{language => optimization}/optimization_inline.das (100%) rename tests/{language => optimization}/optimization_inline_operators.das (100%) rename tests/{language => optimization}/optimization_splat_order.das (100%) rename tests/{language => optimization}/uncategorized_disable_auto_inline_no_coverage_rtti.das (100%) rename tests/{language => optimization}/uncategorized_disable_auto_inline_rtti.das (100%) rename tests/{language => optimization}/uncategorized_disable_cse_rtti.das (100%) rename tests/{language => optimization}/uncategorized_fast_math_rtti.das (100%) diff --git a/ci/test_ci_matrix.py b/ci/test_ci_matrix.py index 8d6770f240..ffc06ed994 100644 --- a/ci/test_ci_matrix.py +++ b/ci/test_ci_matrix.py @@ -262,7 +262,8 @@ def test_the_fast_math_cell_runs_the_per_pr_lane_narrowed_and_no_nightly_step(se self.assertIn(" if(DAS_FAST_MATH)\n" " set(_aot_subset_test_dirs ${_DAS_FAST_MATH_AOT_DIRS})\n", tests_cmake) self.assertIn("set(_DAS_FAST_MATH_AOT_DIRS ${PROJECT_SOURCE_DIR}/tests/language" - " ${PROJECT_SOURCE_DIR}/tests/math)\n", tests_cmake) + " ${PROJECT_SOURCE_DIR}/tests/optimization\n" + " ${PROJECT_SOURCE_DIR}/tests/math)\n", tests_cmake) with open(os.path.join(os.path.dirname(HERE), "tests", "aot", "CMakeLists.txt"), encoding="utf-8") as f: aot_cmake = f.read() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1314d47145..e1dd34519a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -18,12 +18,13 @@ # another ~1.4x night to night. # What a fast-math build sweeps: under JIT the folders whose tests have a HOST_FAST_MATH arm, -# under AOT the two of them test_aot_subset carries. +# under AOT the three of them test_aot_subset carries. set(_DAS_FAST_MATH_JIT_DIRS) -foreach(_dir flatten jit jit_tests language math spirv type_lattice) +foreach(_dir flatten jit jit_tests language math optimization spirv type_lattice) list(APPEND _DAS_FAST_MATH_JIT_DIRS ${PROJECT_SOURCE_DIR}/tests/${_dir}) endforeach() -set(_DAS_FAST_MATH_AOT_DIRS ${PROJECT_SOURCE_DIR}/tests/language ${PROJECT_SOURCE_DIR}/tests/math) +set(_DAS_FAST_MATH_AOT_DIRS ${PROJECT_SOURCE_DIR}/tests/language ${PROJECT_SOURCE_DIR}/tests/optimization + ${PROJECT_SOURCE_DIR}/tests/math) if(NOT DAS_TOOLS_DISABLED) set(DAS_TEST_TIMEOUT 1800 CACHE STRING @@ -68,12 +69,12 @@ if(NOT DAS_TOOLS_DISABLED) list(APPEND _DAS_SAN_ENV "ASAN_OPTIONS=detect_leaks=0") endif() - # A sanitizer lane sweeps tests/language only: the whole suite under asan/tsan/ubsan - # costs ~10 minutes more without proportionate coverage. A fast-math build sweeps its own - # folder list. + # A sanitizer lane sweeps tests/language and tests/optimization only: the whole suite + # under asan/tsan/ubsan costs ~10 minutes more without proportionate coverage. A fast-math + # build sweeps its own folder list. set(_DAS_JIT_TEST_DIRS ${_DAS_TEST_DIR}) if(DAS_USE_SANITIZER AND NOT DAS_USE_SANITIZER STREQUAL "none") - set(_DAS_JIT_TEST_DIRS ${_DAS_TEST_DIR}/language) + set(_DAS_JIT_TEST_DIRS ${_DAS_TEST_DIR}/language ${_DAS_TEST_DIR}/optimization) elseif(DAS_FAST_MATH) set(_DAS_JIT_TEST_DIRS ${_DAS_FAST_MATH_JIT_DIRS}) endif() @@ -169,11 +170,11 @@ if(TARGET test_aot) ) endif() -# Fast AOT run over tests/language (and tests/math in a fast-math build), against the subset -# binary that per-PR CI already builds as part of ALL. The build lane runs it; its own result -# cache serves it until the subset binary changes. +# Fast AOT run over tests/language and tests/optimization (and tests/math in a fast-math build), +# against the subset binary that per-PR CI already builds as part of ALL. The build lane runs it; +# its own result cache serves it until the subset binary changes. if(TARGET test_aot_subset) - set(_aot_subset_test_dirs ${PROJECT_SOURCE_DIR}/tests/language) + set(_aot_subset_test_dirs ${PROJECT_SOURCE_DIR}/tests/language ${PROJECT_SOURCE_DIR}/tests/optimization) if(DAS_FAST_MATH) set(_aot_subset_test_dirs ${_DAS_FAST_MATH_AOT_DIRS}) endif() diff --git a/tests/aot/CMakeLists.txt b/tests/aot/CMakeLists.txt index a3c46f11e2..f71f0370c0 100644 --- a/tests/aot/CMakeLists.txt +++ b/tests/aot/CMakeLists.txt @@ -367,6 +367,19 @@ FILE(GLOB AOT_TYPEMACRO_FILES RELATIVE ${PROJECT_SOURCE_DIR} CONFIGURE_DEPENDS " list(FILTER AOT_TYPEMACRO_FILES EXCLUDE REGEX "/_") SET(AOT_TYPEMACRO_MODULE_FILES tests/typemacro/_template_struct_instance_mod.das) +FILE(GLOB AOT_OPTIMIZATION_FILES RELATIVE ${PROJECT_SOURCE_DIR} CONFIGURE_DEPENDS "tests/optimization/*.das") +list(FILTER AOT_OPTIMIZATION_FILES EXCLUDE REGEX "/_") +SET(AOT_OPTIMIZATION_MODULE_FILES + tests/optimization/_inline_constant_expression_helper.das + tests/optimization/_inline_counter_helper.das + tests/optimization/_inline_generic_helper.das + tests/optimization/_inline_scope_helper.das + tests/optimization/_inline_unoptimized_scope_helper.das + tests/optimization/_inline_unsafe_helper.das + tests/optimization/_never_inline_module.das + tests/optimization/_optimized_body_helper.das +) + FILE(GLOB AOT_LANGUAGE_FILES RELATIVE ${PROJECT_SOURCE_DIR} CONFIGURE_DEPENDS "tests/language/*.das") # Exclude module files (they are compiled via DAS_AOT_LIB below) list(FILTER AOT_LANGUAGE_FILES EXCLUDE REGEX "/_") @@ -413,19 +426,11 @@ SET(AOT_LANGUAGE_MODULE_FILES tests/language/_distinct_fixture.das tests/language/_glob.das tests/language/_helper_foo.das - tests/language/_inline_constant_expression_helper.das - tests/language/_inline_counter_helper.das - tests/language/_inline_generic_helper.das - tests/language/_inline_scope_helper.das - tests/language/_inline_unoptimized_scope_helper.das - tests/language/_inline_unsafe_helper.das tests/language/_invoke_cmres_global_helper.das tests/language/_lambda_vis_inner.das tests/language/_lambda_vis_mid.das - tests/language/_never_inline_module.das tests/language/_operators_derived.das tests/language/_operators_parent.das - tests/language/_optimized_body_helper.das tests/language/_private_property_helper.das tests/language/_string_clone_init_helper.das tests/language/_struct_alias_facade.das @@ -457,7 +462,7 @@ set(DAS_AOT_SUITES jobque json jsonrpc language linq lint long_array_table loops lpipe lsp macro_boost macro_call match math mcp md_boost module_cache module_tests network option promote quote reader_macro regex rtti safe_addr soa spoof strings stbimage table_packed template - tests type_lattice type_traits typemacro uri with_boost delegate) + tests type_lattice type_traits typemacro uri with_boost delegate optimization) foreach(_s IN LISTS DAS_AOT_SUITES) string(TOUPPER ${_s} _u) # suites with an irregular dir / a filter / a curated list define AOT__FILES above; @@ -483,7 +488,7 @@ foreach(_s IN LISTS DAS_AOT_SUITES) list(APPEND TEST_AOT_ALL_DAS ${AOT_${_u}_FILES}) endforeach() -set(DAS_AOT_MODULE_SUITES daslib dasgltf dastest decs glsl language linq macro_boost math quote stbimage typemacro) +set(DAS_AOT_MODULE_SUITES daslib dasgltf dastest decs glsl language linq macro_boost math optimization quote stbimage typemacro) foreach(_s IN LISTS DAS_AOT_MODULE_SUITES) string(TOUPPER ${_s} _u) add_custom_target(test_aot_${_s}_modules) @@ -623,20 +628,23 @@ DAS_AOT_PCH(test_aot) # test binary that measures correctness, not performance. ### AOT subset target — the per-PR CI gate -# tests/language only (+ dastest/testing.das and the language fixture modules; a fast-math -# build adds tests/math). +# tests/language and tests/optimization (+ dastest/testing.das and their fixture modules; a +# fast-math build adds tests/math). # Part of the default build on every lane, Debug included: a fast compile+link # gate (~230 TUs, no LTO). The full suite builds and runs on the nightly cron. add_executable(test_aot_subset ${DAS_DASCRIPT_MAIN_SRC} ${TESTING_AOT_GENERATED_SRC} ${LANGUAGE_AOT_GENERATED_SRC} ${LANGUAGE_MODULES_AOT_GENERATED_SRC} + ${OPTIMIZATION_AOT_GENERATED_SRC} + ${OPTIMIZATION_MODULES_AOT_GENERATED_SRC} ${SUBSET_DASLIB_MODULES_AOT_GENERATED_SRC} ) TARGET_LINK_LIBRARIES(test_aot_subset libDaScriptAot ${SRC_LIBRARIES} ${DAS_MODULES_LIBS}) ADD_DEPENDENCIES(test_aot_subset libDaScriptAot test_aot_testing test_aot_language test_aot_language_modules + test_aot_optimization test_aot_optimization_modules test_aot_subset_daslib_modules ) target_include_directories(test_aot_subset PRIVATE ${TEST_AOT_INCLUDE_DIRS}) diff --git a/tests/lint/stale_fixtures/_fixture_lint_skip.das b/tests/lint/stale_fixtures/_fixture_lint_skip.das index 27b4a2256e..3bfe863c4b 100644 --- a/tests/lint/stale_fixtures/_fixture_lint_skip.das +++ b/tests/lint/stale_fixtures/_fixture_lint_skip.das @@ -2,7 +2,7 @@ options gen2 // lint-skip-file: subject conflicts with lint policies (fixture) // The deliberate finding below must never be reported - the directive // above opts the whole file out (canonical user: -// tests/language/dead_branch_folding.das). +// tests/optimization/dead_branch_folding.das). def dead_store_bait { var x = 1 diff --git a/tests/language/_inline_constant_expression_helper.das b/tests/optimization/_inline_constant_expression_helper.das similarity index 100% rename from tests/language/_inline_constant_expression_helper.das rename to tests/optimization/_inline_constant_expression_helper.das diff --git a/tests/language/_inline_counter_helper.das b/tests/optimization/_inline_counter_helper.das similarity index 100% rename from tests/language/_inline_counter_helper.das rename to tests/optimization/_inline_counter_helper.das diff --git a/tests/language/_inline_generic_helper.das b/tests/optimization/_inline_generic_helper.das similarity index 100% rename from tests/language/_inline_generic_helper.das rename to tests/optimization/_inline_generic_helper.das diff --git a/tests/language/_inline_scope_helper.das b/tests/optimization/_inline_scope_helper.das similarity index 100% rename from tests/language/_inline_scope_helper.das rename to tests/optimization/_inline_scope_helper.das diff --git a/tests/language/_inline_unoptimized_scope_helper.das b/tests/optimization/_inline_unoptimized_scope_helper.das similarity index 100% rename from tests/language/_inline_unoptimized_scope_helper.das rename to tests/optimization/_inline_unoptimized_scope_helper.das diff --git a/tests/language/_inline_unsafe_helper.das b/tests/optimization/_inline_unsafe_helper.das similarity index 100% rename from tests/language/_inline_unsafe_helper.das rename to tests/optimization/_inline_unsafe_helper.das diff --git a/tests/language/_never_inline_module.das b/tests/optimization/_never_inline_module.das similarity index 100% rename from tests/language/_never_inline_module.das rename to tests/optimization/_never_inline_module.das diff --git a/tests/language/_optimized_body_helper.das b/tests/optimization/_optimized_body_helper.das similarity index 100% rename from tests/language/_optimized_body_helper.das rename to tests/optimization/_optimized_body_helper.das diff --git a/tests/language/dead_branch_folding.das b/tests/optimization/dead_branch_folding.das similarity index 100% rename from tests/language/dead_branch_folding.das rename to tests/optimization/dead_branch_folding.das diff --git a/tests/language/optimization.das b/tests/optimization/optimization.das similarity index 100% rename from tests/language/optimization.das rename to tests/optimization/optimization.das diff --git a/tests/language/optimization_auto_inline.das b/tests/optimization/optimization_auto_inline.das similarity index 100% rename from tests/language/optimization_auto_inline.das rename to tests/optimization/optimization_auto_inline.das diff --git a/tests/language/optimization_auto_inline_functions.das b/tests/optimization/optimization_auto_inline_functions.das similarity index 100% rename from tests/language/optimization_auto_inline_functions.das rename to tests/optimization/optimization_auto_inline_functions.das diff --git a/tests/language/optimization_cse.das b/tests/optimization/optimization_cse.das similarity index 100% rename from tests/language/optimization_cse.das rename to tests/optimization/optimization_cse.das diff --git a/tests/language/optimization_fast_math.das b/tests/optimization/optimization_fast_math.das similarity index 100% rename from tests/language/optimization_fast_math.das rename to tests/optimization/optimization_fast_math.das diff --git a/tests/language/optimization_fold_shape.das b/tests/optimization/optimization_fold_shape.das similarity index 100% rename from tests/language/optimization_fold_shape.das rename to tests/optimization/optimization_fold_shape.das diff --git a/tests/language/optimization_inline.das b/tests/optimization/optimization_inline.das similarity index 100% rename from tests/language/optimization_inline.das rename to tests/optimization/optimization_inline.das diff --git a/tests/language/optimization_inline_operators.das b/tests/optimization/optimization_inline_operators.das similarity index 100% rename from tests/language/optimization_inline_operators.das rename to tests/optimization/optimization_inline_operators.das diff --git a/tests/language/optimization_splat_order.das b/tests/optimization/optimization_splat_order.das similarity index 100% rename from tests/language/optimization_splat_order.das rename to tests/optimization/optimization_splat_order.das diff --git a/tests/language/uncategorized_disable_auto_inline_no_coverage_rtti.das b/tests/optimization/uncategorized_disable_auto_inline_no_coverage_rtti.das similarity index 100% rename from tests/language/uncategorized_disable_auto_inline_no_coverage_rtti.das rename to tests/optimization/uncategorized_disable_auto_inline_no_coverage_rtti.das diff --git a/tests/language/uncategorized_disable_auto_inline_rtti.das b/tests/optimization/uncategorized_disable_auto_inline_rtti.das similarity index 100% rename from tests/language/uncategorized_disable_auto_inline_rtti.das rename to tests/optimization/uncategorized_disable_auto_inline_rtti.das diff --git a/tests/language/uncategorized_disable_cse_rtti.das b/tests/optimization/uncategorized_disable_cse_rtti.das similarity index 100% rename from tests/language/uncategorized_disable_cse_rtti.das rename to tests/optimization/uncategorized_disable_cse_rtti.das diff --git a/tests/language/uncategorized_fast_math_rtti.das b/tests/optimization/uncategorized_fast_math_rtti.das similarity index 100% rename from tests/language/uncategorized_fast_math_rtti.das rename to tests/optimization/uncategorized_fast_math_rtti.das diff --git a/utils/mcp/test_tools_lint.das b/utils/mcp/test_tools_lint.das index 2d2b7730b3..bccec681e9 100644 --- a/utils/mcp/test_tools_lint.das +++ b/utils/mcp/test_tools_lint.das @@ -209,8 +209,8 @@ def test_lint_skip_expect(t : T?) { t |> run("a `lint-skip-file` header skips instead of hard-failing on policy-conflicted files") <| @(t : T?) { var text : string var is_error = false - let ok = parse_result(do_lint("{get_das_root()}/tests/language/dead_branch_folding.das"), - text, is_error) + let fixture = "{get_das_root()}/tests/optimization/dead_branch_folding.das" + let ok = parse_result(do_lint(fixture), text, is_error) t |> success(ok, "skip result is a valid envelope") t |> success(!is_error, "skip is not an error") t |> success(find(text, "SKIP") >= 0, "should report SKIP: {text}") From 11c552a558ff1b6be2a9591dfa7613aae7c2cbbd Mon Sep 17 00:00:00 2001 From: Churkin Aleksey Date: Wed, 25 Nov 2026 21:53:18 +0300 Subject: [PATCH 5/5] compiler: sink a pure local into the branch that reads it optimizationSink (ast_sink.cpp) moves a one-variable let into the if right after it when only one arm reads the variable and nothing after the if does. The common case is an inlined check: the inliner binds the message argument to a local ahead of the body's if, so a passing check still built its message; sunk, it builds it only when it fails. The initializer and the condition must both be droppable: no side effect and no raise. A reference, inscope or collected local, a move out of storage and an arm that shadows the name stay where they are. The pass runs in the optimizer loop after dead stores. The policy disable_sink turns it off; AST serializer version 289. tests/optimization/optimization_sink.das: 11 tests, interpreted and JIT; 4 fail under -policy disable_sink=true. Full suite: no change in the failure set against the baseline. 1M passing checks: 125-147 ms -> 4 ms interpreted, 91-97 ms -> <1 ms JIT; benchmarks/core+micro and the dasLLAMA loads unchanged. --- CMakeLists.txt | 1 + doc/source/reference/language/options.rst | 5 + ...ructure_annotation-rtti-CodeOfPolicies.rst | 1 + include/daScript/ast/ast_serializer.h | 2 +- include/daScript/daScriptC.h | 3 +- include/daScript/simulate/code_of_policies.h | 1 + src/ast/ARCHITECTURE_EFFECTS.md | 26 +++ src/ast/ast_optimize.cpp | 4 + src/ast/ast_sink.cpp | 128 +++++++++++++ src/ast/ast_sink.h | 7 + src/builtin/module_builtin_ast_serialize.cpp | 2 +- src/builtin/module_builtin_rtti.cpp | 1 + src/misc/daScriptC.cpp | 1 + tests/optimization/optimization_sink.das | 168 ++++++++++++++++++ 14 files changed, 347 insertions(+), 3 deletions(-) create mode 100644 src/ast/ast_sink.cpp create mode 100644 src/ast/ast_sink.h create mode 100644 tests/optimization/optimization_sink.das diff --git a/CMakeLists.txt b/CMakeLists.txt index e648d2a43a..48626e854e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1353,6 +1353,7 @@ SET(LIBDASCRIPT_COMPILER_SRC src/ast/ast_escape_analysis.cpp src/ast/ast_cfg.cpp src/ast/ast_dse.cpp + src/ast/ast_sink.cpp src/ast/ast_cse.cpp src/ast/ast_devirtualize.cpp src/ast/ast_inline.cpp diff --git a/doc/source/reference/language/options.rst b/doc/source/reference/language/options.rst index 07fc000acc..357f6dcb1e 100644 --- a/doc/source/reference/language/options.rst +++ b/doc/source/reference/language/options.rst @@ -196,6 +196,11 @@ Optimization - bool - false - Disables the fastcall optimization. + * - ``disable_sink`` + - bool + - false + - Disables the sink pass, which moves a local with a pure initializer into the one ``if`` arm + that reads it, so an inlined check builds its message only when the check fails. * - ``max_fast_call_depth`` - int - 0 diff --git a/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst b/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst index 430095923f..ec1612582c 100644 --- a/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst +++ b/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst @@ -71,6 +71,7 @@ Keeps the ``unsafe { }`` scope in the AST after inference, which ``foldUnsafe`` Allows float optimizations with major bit differences (x*0, x-x, reciprocal division, NaN-compare flips, reassociation); also stamps JIT fast-math flags. Doubles stay bit-exact unless enabled. Disables the dead-store-elimination optimizer pass. Host-side counterpart of ``options disable_dse`` (the option overrides the policy). Disables the common-subexpression-elimination optimizer pass. Host-side counterpart of ``options disable_cse`` (the option overrides the policy). +Disables the sink pass, which moves a local with a pure initializer into the one ``if`` arm that reads it. Host-side counterpart of ``options disable_sink`` (the option overrides the policy). Disables ``[inline]`` splicing - annotated calls stay regular calls. The declaration-level contract checks (body shape, recursion through the inline graph, taking the address) still run; call-site splice checks do not apply, since nothing splices. Host-side counterpart of ``options disable_inline`` (the option overrides the policy). Disables automatic inlining: block-literal call sites stay regular calls and invoke-of-literal sites stay invokes. ``[inline]`` splicing is unaffected. Host-side counterpart of ``options disable_auto_inline`` (the option overrides the policy). Heuristic best-effort inlining of plain calls and operator sites (default ON, optimized builds only): small same-module non-generic callees splice, silently declining anything unspliceable. Cross-module inlining stays the explicit ``[inline]`` contract. Host-side counterpart of ``options auto_inline_functions`` (the option overrides the policy). ``disable_auto_inline`` overrides. diff --git a/include/daScript/ast/ast_serializer.h b/include/daScript/ast/ast_serializer.h index 3f0d0fd5ca..b04bbd601e 100644 --- a/include/daScript/ast/ast_serializer.h +++ b/include/daScript/ast/ast_serializer.h @@ -361,7 +361,7 @@ namespace das { AstSerializer & serializeModule ( Module & module, bool already_exists ); static constexpr uint32_t getVersion () { - return 288; // 288: a function records the [no_capture_string] contract + return 289; // 289: the policies record disable_sink } void serializeProgram ( ProgramPtr program, ModuleGroup & libGroup ) noexcept; diff --git a/include/daScript/daScriptC.h b/include/daScript/daScriptC.h index cbf8233514..8e360cf65c 100644 --- a/include/daScript/daScriptC.h +++ b/include/daScript/daScriptC.h @@ -821,7 +821,8 @@ typedef enum das_bool_policy { DAS_POLICY_AUTO_INLINE_FUNCTIONS, // Heuristic best-effort inlining of plain calls and operator sites of small same-module [inline]-shaped functions (default ON; silent declines; optimized builds only; cross-module inlining stays the explicit [inline] contract) DAS_POLICY_DISABLE_TEMP_STRING_RECLAIM, // Disable the temp-string reclaim pass (fresh-string call results riding the 1-slot dispose queue) DAS_POLICY_JIT_ENABLED, // Enable JIT compilation of [jit] functions. The flag alone is not enough: the host must also register the "just_in_time" extra module (see das_fileaccess_add_extra_module) so the LLVM JIT backend is compiled in - DAS_POLICY_JIT_DLL_MODE // With JIT: cache generated code as per-script DLLs under .cache/daslang/ in the working directory (default: on). Off = codegen in-memory every run, no cache writes. The cache path needs a DLL build of daslang; a static-linked host always codegens in-memory regardless of this flag + DAS_POLICY_JIT_DLL_MODE, // With JIT: cache generated code as per-script DLLs under .cache/daslang/ in the working directory (default: on). Off = codegen in-memory every run, no cache writes. The cache path needs a DLL build of daslang; a static-linked host always codegens in-memory regardless of this flag + DAS_POLICY_DISABLE_SINK // Disable the pass that sinks a pure local into the one `if` arm reading it } das_bool_policy; // Integer policy fields (stack size, heap limits). diff --git a/include/daScript/simulate/code_of_policies.h b/include/daScript/simulate/code_of_policies.h index 5e26d519b5..5e5fb50ae7 100644 --- a/include/daScript/simulate/code_of_policies.h +++ b/include/daScript/simulate/code_of_policies.h @@ -115,6 +115,7 @@ namespace das { /*option*/ bool fast_math = false; // allow VALUE-SAFE float optimizations with bit differences (reassociation, FMA contraction, signed-zero laxity); inf/NaN semantics are preserved — no rcp division, no nan-compare flips (JIT stamps reassoc|nsz|contract only). doubles stay bit-exact unless this is on /*option*/ bool disable_dse = false; // disable the dead-store-elimination pass /*option*/ bool disable_cse = false; // disable the common-subexpression-elimination pass + /*option*/ bool disable_sink = false; // disable the pass that sinks a pure local into the one `if` arm reading it /*option*/ bool disable_inline = false; // disable the [inline] function inliner (calls stay regular calls; declaration-level contract checks - shape, recursion, @@ - still lint) /*option*/ bool disable_auto_inline = false; // disable automatic inlining of block-literal call sites and invoke-of-literal devirtualization ([inline] splicing is unaffected) /*option*/ bool auto_inline_functions = true; // heuristic best-effort inlining of plain calls and operator sites of small same-module [inline]-shaped functions (default ON; silent declines; optimized builds only; disable_auto_inline overrides) diff --git a/src/ast/ARCHITECTURE_EFFECTS.md b/src/ast/ARCHITECTURE_EFFECTS.md index 279e9ab6e2..a67a928e67 100644 --- a/src/ast/ARCHITECTURE_EFFECTS.md +++ b/src/ast/ARCHITECTURE_EFFECTS.md @@ -74,3 +74,29 @@ a null pointer is undefined behavior, not a raise); `ExprAsVariant`, `ExprAssert (its target is unknown) always raise. Only a pass that deletes an evaluation asks, and only through `droppable`, which wants `noSideEffects` and no `mayRaise` together. CSE does not: it reuses the first evaluation, which still raises. + +## Sinking a pure local into the branch that reads it {#sink-pure-let} + +`optimizationSink` (`ast_sink.cpp`) moves a `let` of one variable into the `if` right after it, when +that `if` reads the variable in one arm only and nothing after the `if` reads it. The local is then +computed only on the path that uses it. The common case is an inlined check: the inliner binds the +message argument to a local ahead of the body's `if`, so a check that passes still builds its +message; once sunk, it builds it only when it fails. + +Moving an evaluation later, and onto one path, is the same question as deleting it on the others, so +the pass asks `droppable` of the initializer: no side effect, and no raise, since a raise that +happens today on every path must not vanish on the paths that no longer evaluate it. The `if` +condition must be `droppable` too: the initializer now runs after it, and a condition that writes +what the initializer reads would change its value. A reference local, an `inscope` or collected +local (its cleanup sits in the block's final list) and a move out of storage (the move zeroes the +source at a different time) stay where they are. No arm can declare the moved local's name: infer +refuses a local that shadows another, and the optimizer's own locals carry unique names. `options +disable_sink` turns the pass off. + +The pass is one visitor. A block's pre-visit finds its let-if pairs and registers each `if`'s arms, +which are blocks themselves; the walk counts every use of a candidate's variable, and the uses inside +each of its arms; and the block's post-visit moves a let whose uses all sit in one arm - none in the +condition, the other arm or after the `if`. A local lives in its own block, so by the post-visit +every use of it has been counted. It runs no side-effect walk of its own: it +reads the flags that walk left at the start of dead-store elimination, the pass right before it. +A node built since then is never `droppable`, so a stale flag can only keep a let in place. diff --git a/src/ast/ast_optimize.cpp b/src/ast/ast_optimize.cpp index 42904032a8..754da60535 100644 --- a/src/ast/ast_optimize.cpp +++ b/src/ast/ast_optimize.cpp @@ -4,6 +4,7 @@ #include "daScript/ast/ast.h" #include "daScript/ast/ast_expressions.h" #include "daScript/ast/ast_visitor.h" +#include "ast_sink.h" namespace das { @@ -45,6 +46,9 @@ namespace das { last = program->optimizationDeadStores(optimizationRound); if ( program->failed() ) break; noteChange(last); if ( log ) logs << "DEAD STORES:" << (last ? "optimized" : "nothing") << "\n"; if ( logPass ) logs << *program; + last = optimizationSink(program, optimizationRound); if ( program->failed() ) break; noteChange(last); + if ( log ) logs << "SINK:" << (last ? "optimized" : "nothing") << "\n"; + if ( logPass ) logs << *program; // this is here again for a reason last = program->optimizationUnused(logs, optimizationRound); if ( program->failed() ) break; noteChange(last); if ( log ) logs << "REMOVE UNUSED:" << (last ? "optimized" : "nothing") << "\n"; diff --git a/src/ast/ast_sink.cpp b/src/ast/ast_sink.cpp new file mode 100644 index 0000000000..a6ed05bb66 --- /dev/null +++ b/src/ast/ast_sink.cpp @@ -0,0 +1,128 @@ +#include "daScript/misc/platform.h" + +#include "daScript/ast/ast.h" +#include "daScript/ast/ast_visitor.h" +#include "daScript/ast/ast_expressions.h" + +#include "ast_effects.h" +#include "ast_sink.h" + +namespace das { + + // src/ast/ARCHITECTURE_EFFECTS.md#sink-pure-let + + namespace { + + struct SinkCandidate { + ExprBlock * ifTrue = nullptr; + ExprBlock * ifFalse = nullptr; + int total = 0; + int inTrue = 0; + int inFalse = 0; + }; + + struct SinkArm { + Variable * var = nullptr; + bool isTrue = false; + }; + + bool sinkableLet ( Expression * stmt ) { + if ( !stmt->rtti_isLet() ) return false; + auto let = static_cast(stmt); + if ( let->variables.size()!=1 ) return false; + auto v = let->variables[0]; + if ( !v->init || !v->type || v->type->ref ) return false; + if ( v->inScope || v->pod_delete ) return false; + if ( v->init_via_move && (v->init->type==nullptr || v->init->type->isRef()) ) return false; + return droppable(v->init); + } + + ExprBlock * armBlock ( Expression * e ) { + return ( e && e->rtti_isBlock() ) ? static_cast(e) : nullptr; + } + + class SinkPureLets : public PassVisitor { + public: + using PassVisitor::PassVisitor; + using PassVisitor::visit; + using PassVisitor::preVisit; + protected: + das_hash_map candidates; + das_hash_map arms; + vector open; + virtual bool canVisitStructure ( Structure * ) override { return false; } + virtual bool canVisitStructureFieldInit ( Structure * ) override { return false; } + virtual bool canVisitArgumentInit ( Function *, const VariablePtr &, Expression * ) override { return false; } + virtual bool canVisitQuoteSubexpression ( ExprQuote * ) override { return false; } + virtual bool canVisitGlobalVariable ( Variable * ) override { return false; } + virtual bool canVisitEnumeration ( Enumeration * ) override { return false; } + virtual void preVisit ( Function * fun ) override { + PassVisitor::preVisit(fun); + candidates.clear(); + arms.clear(); + open.clear(); + } + static pair pairedLet ( ExprBlock * block, size_t i ) { + auto & list = block->list; + if ( i+1>=list.size() || !sinkableLet(list[i]) || !list[i+1]->rtti_isIfThenElse() ) return {nullptr, nullptr}; + return {static_cast(list[i])->variables[0], static_cast(list[i+1])}; + } + virtual void preVisit ( ExprBlock * block ) override { + PassVisitor::preVisit(block); + auto arm = arms.find(block); + if ( arm!=arms.end() ) open.push_back(arm->second); + for ( size_t i=0; ilist.size(); ++i ) { + auto [var, ite] = pairedLet(block, i); + if ( !var || ite->isStatic || !droppable(ite->cond) ) continue; + auto & c = candidates[var]; + c.ifTrue = armBlock(ite->if_true); + c.ifFalse = armBlock(ite->if_false); + if ( c.ifTrue ) arms[c.ifTrue] = SinkArm{var, true}; + if ( c.ifFalse ) arms[c.ifFalse] = SinkArm{var, false}; + } + } + virtual void preVisit ( ExprVar * expr ) override { + PassVisitor::preVisit(expr); + auto it = candidates.find(expr->variable); + if ( it==candidates.end() ) return; + auto & c = it->second; + c.total ++; + for ( auto & a : open ) { + if ( a.var!=expr->variable ) continue; + if ( a.isTrue ) c.inTrue ++; + else c.inFalse ++; + } + } + ExprBlock * targetArm ( Variable * v ) { + auto it = candidates.find(v); + if ( it==candidates.end() ) return nullptr; + auto c = it->second; + candidates.erase(it); + if ( c.total==c.inTrue && c.inTrue ) return c.ifTrue; + if ( c.total==c.inFalse && c.inFalse ) return c.ifFalse; + return nullptr; + } + virtual ExpressionPtr visit ( ExprBlock * block ) override { + auto & list = block->list; + for ( size_t i=0; ilist.insert(arm->list.begin(), list[i]); + list.erase(list.begin() + i); + reportFolding(); + } + if ( arms.erase(block) ) open.pop_back(); + return PassVisitor::visit(block); + } + }; + } + + bool optimizationSink ( Program * program, int32_t round ) { + if ( program->options.getBoolOption("disable_sink", program->policies.disable_sink) ) return false; + SinkPureLets pass(round); + program->visit(pass); + return pass.didAnything(); + } +} diff --git a/src/ast/ast_sink.h b/src/ast/ast_sink.h new file mode 100644 index 0000000000..017747c049 --- /dev/null +++ b/src/ast/ast_sink.h @@ -0,0 +1,7 @@ +#pragma once + +#include "daScript/ast/ast.h" + +namespace das { + bool optimizationSink ( Program * program, int32_t round ); +} diff --git a/src/builtin/module_builtin_ast_serialize.cpp b/src/builtin/module_builtin_ast_serialize.cpp index 710d76e39c..41c9649076 100644 --- a/src/builtin/module_builtin_ast_serialize.cpp +++ b/src/builtin/module_builtin_ast_serialize.cpp @@ -3110,7 +3110,7 @@ namespace das { X(strict_smart_pointers) X(no_init) X(strict_unsafe_delete) X(no_members_functions_in_struct) \ X(no_local_class_members) X(no_unsafe_uninitialized_structures) X(default_init_containers) \ X(strict_properties) X(no_writing_to_nameless) X(no_optimizations) X(no_fold_unsafe) X(fast_math) X(disable_dse) \ - X(disable_cse) X(disable_temp_string_reclaim) X(disable_inline) X(disable_auto_inline) \ + X(disable_cse) X(disable_sink) X(disable_temp_string_reclaim) X(disable_inline) X(disable_auto_inline) \ X(auto_inline_functions) X(auto_inline_cost) X(disable_run) X(no_infer_time_folding) \ X(fail_on_no_aot) X(fail_on_lack_of_aot_export) X(no_fast_call) X(max_fast_call_depth) X(fusion) X(scoped_stack_allocator) \ X(force_inscope_pod) X(log_inscope_pod) X(debugger) X(profiler) X(jit_enabled) \ diff --git a/src/builtin/module_builtin_rtti.cpp b/src/builtin/module_builtin_rtti.cpp index e657b2dd92..de3666abf6 100644 --- a/src/builtin/module_builtin_rtti.cpp +++ b/src/builtin/module_builtin_rtti.cpp @@ -1042,6 +1042,7 @@ namespace das { addField("fast_math"); addField("disable_dse"); addField("disable_cse"); + addField("disable_sink"); addField("disable_inline"); addField("disable_auto_inline"); addField("auto_inline_functions"); diff --git a/src/misc/daScriptC.cpp b/src/misc/daScriptC.cpp index c139070dd4..e735d3c711 100644 --- a/src/misc/daScriptC.cpp +++ b/src/misc/daScriptC.cpp @@ -938,6 +938,7 @@ int das_policies_set_bool ( das_policies * policies, das_bool_policy flag, int v case DAS_POLICY_NO_INFER_TIME_FOLDING: p->no_infer_time_folding = v; break; case DAS_POLICY_FAST_MATH: p->fast_math = v; break; case DAS_POLICY_DISABLE_DSE: p->disable_dse = v; break; + case DAS_POLICY_DISABLE_SINK: p->disable_sink = v; break; case DAS_POLICY_DISABLE_CSE: p->disable_cse = v; break; case DAS_POLICY_DISABLE_INLINE: p->disable_inline = v; break; case DAS_POLICY_DISABLE_AUTO_INLINE: p->disable_auto_inline = v; break; diff --git a/tests/optimization/optimization_sink.das b/tests/optimization/optimization_sink.das new file mode 100644 index 0000000000..10585a9676 --- /dev/null +++ b/tests/optimization/optimization_sink.das @@ -0,0 +1,168 @@ +options gen2 +options rtti +options no_coverage +options disable_auto_inline // this file pins sink shapes; auto-splicing would rewrite them + +require daslib/ast +require daslib/rtti +require daslib/ast_boost +require dastest/testing_boost public +require strings +require daslib/strings_boost +require _optimized_body_helper + +var g_count = 0 + +def bump() : int { + g_count ++ + return g_count +} + +struct Header { + width : int + name : string +} + +[inline] +def expect_or_panic(ok : bool; what : string) { + if (!ok) { + panic("check: {what}") + } +} + +[export] +def target_sink_message(x : int) : int { + let message = "item {x} is negative" + if (x < 0) { + panic(message) + } + return x +} + +[export] +def target_sink_inlined_check(x : int) : int { + expect_or_panic(x >= 0, "item {x} is negative") + return x +} + +[export] +def target_sink_field(h : Header) : int { + expect_or_panic(h.width % 32 == 0, "width {h.width} of '{h.name}' is off the 32 lattice") + return h.width +} + +[export] +def target_keep_effect(x : int) : int { + let message = "item {bump()} is negative" + if (x < 0) { + panic(message) + } + return x +} + +[export] +def target_keep_raising(a : array; x : int) : int { + let message = "item {a[x]} is negative" + if (x < 0) { + panic(message) + } + return x +} + +[export] +def target_keep_effect_cond(x : int) : int { + let message = "item {x} is negative" + if (bump() < 0) { + panic(message) + } + return x +} + +[export] +def target_keep_both_arms(x : int) : string { + let message = "item {x}" + if (x < 0) { + return "negative {message}" + } else { + return "positive {message}" + } +} + +[export] +def target_keep_used_after(x : int) : string { + let message = "item {x}" + if (x < 0) { + panic(message) + } + return message +} + +//! the local ending in `name` is declared in the body's first `if` +def private let_inside_if(body, name : string) : bool { + let at_if = find(body, "if (") + let at_let = find(body, "{name}:") + return at_if >= 0 && at_let > at_if +} + +[test(description = "a pure local read only in one branch of the `if` that follows it moves into that branch: a message, an inlined check's message and one that reads a struct field")] +def test_sink_moves(t : T?) { + ast_gc_guard() { + t |> run("a message read only on the failure path moves in") @(t : T?) { + let b = body_of(t, "target_sink_message") + t |> success(let_inside_if(b, "message"), "sunk: {b}") + } + t |> run("an inlined check builds its message inside the failure branch") @(t : T?) { + let b = body_of(t, "target_sink_inlined_check") + t |> success(let_inside_if(b, "arg_what"), "sunk: {b}") + } + t |> run("a message that reads a struct field moves in") @(t : T?) { + let b = body_of(t, "target_sink_field") + t |> success(let_inside_if(b, "arg_what"), "sunk: {b}") + } + } +} + +[test(description = "a local stays in front of the `if` when its initializer has an effect or may raise, when the condition has an effect, and when it is read in both arms or after the `if`")] +def test_sink_keeps(t : T?) { + ast_gc_guard() { + t |> run("an initializer with an effect stays") @(t : T?) { + let b = body_of(t, "target_keep_effect") + t |> success(!let_inside_if(b, "message"), "kept: {b}") + } + t |> run("an initializer that may raise stays") @(t : T?) { + let b = body_of(t, "target_keep_raising") + t |> success(!let_inside_if(b, "message"), "kept: {b}") + } + t |> run("a condition with an effect keeps the local in front of it") @(t : T?) { + let b = body_of(t, "target_keep_effect_cond") + t |> success(!let_inside_if(b, "message"), "kept: {b}") + } + t |> run("a local read in both arms stays") @(t : T?) { + let b = body_of(t, "target_keep_both_arms") + t |> success(!let_inside_if(b, "message"), "kept: {b}") + } + t |> run("a local read after the `if` stays") @(t : T?) { + let b = body_of(t, "target_keep_used_after") + t |> success(!let_inside_if(b, "message"), "kept: {b}") + } + } +} + +[test(description = "functions the sink pass rewrote return the same values, keep every call with an effect, and a thousand passing checks build no message")] +def test_sink_behavior(t : T?) { + t |> equal(target_sink_message(5), 5) + t |> equal(target_sink_inlined_check(7), 7) + t |> equal(target_sink_field(Header(width = 64, name = "base")), 64) + t |> equal(target_keep_both_arms(-2), "negative item -2") + t |> equal(target_keep_both_arms(3), "positive item 3") + t |> equal(target_keep_used_after(4), "item 4") + g_count = 0 + target_keep_effect(1) + target_keep_effect_cond(1) + t |> equal(g_count, 2, "both effects ran though their messages are never used") + let s0 = string_heap_bytes_allocated() + for (i in range(1000)) { + target_sink_inlined_check(i) + } + t |> equal(string_heap_bytes_allocated(), s0, "no message built for a passing check") +}