From 2496655485fa10892b4c9b5c01f80b3e0b6501de Mon Sep 17 00:00:00 2001 From: Boris Batkin Date: Fri, 27 Nov 2026 18:31:11 -0800 Subject: [PATCH 1/3] fusion: an if over a compare stays unfused under the debugger The debugger's if node reports a step at the condition and at the arm it takes. The compare twin reports neither, and the fusion replaced the debugger's node with it, so a stepping session passed over the if. The fusion point now makes no twin for a context that has the debugger on. Co-Authored-By: Claude Fable 5.2 --- src/simulate/ARCHITECTURE.md | 4 ++++ src/simulate/simulate_fusion_if.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/simulate/ARCHITECTURE.md b/src/simulate/ARCHITECTURE.md index c35ccbfa13..945aacb1e8 100644 --- a/src/simulate/ARCHITECTURE.md +++ b/src/simulate/ARCHITECTURE.md @@ -98,3 +98,7 @@ not make one. Both arms of the `ThenElse` twin carry `DAS_NO_MERGE`: without it clang merges the two calls into one indirect jump, and the node loses the conditional branch it was made to keep. + +Under the debugger the `if` keeps its own node (`SimNodeDebug_IfThenElse`, `SimNodeDebug_IfThen`), +which reports a step at the condition and at the arm it takes. A twin reports neither, so the +fusion point makes none for a context with `debugger` set. diff --git a/src/simulate/simulate_fusion_if.cpp b/src/simulate/simulate_fusion_if.cpp index 3f8266dfae..e6da6f610e 100644 --- a/src/simulate/simulate_fusion_if.cpp +++ b/src/simulate/simulate_fusion_if.cpp @@ -148,9 +148,11 @@ namespace das { IMPLEMENT_OP1_WORKHORSE_FUSION_POINT(IfNotZeroThen); + // src/simulate/ARCHITECTURE.md#if-over-compare struct FusionPoint_IfCmp final : FusionPoint { virtual SimNode * fuse ( const SimNodeInfoLookup & info, SimNode * node, Context * context ) const override { + if ( context->debugger ) return node; auto ifNode = static_cast(node); for ( auto op : { "Equ", "NotEqu", "LessEqu", "GtEqu", "Gt", "Less" } ) { if ( isFusedOp2(info, ifNode->cond, op) ) { From d8320fdaaba7d8fe155896f2de5386548dbae314 Mon Sep 17 00:00:00 2001 From: Boris Batkin Date: Fri, 27 Nov 2026 18:31:12 -0800 Subject: [PATCH 2/3] inline, sink: small loops unroll, a read-once local forwards In the interpreter a short loop pays its setup and a node a pass, and a spliced callee leaves locals that are read once. Four rewrites remove that cost. The inliner unrolls a for loop whose passes are known at compile time (a constant range, an array literal of constants, a fixed array) while passes times body statements fits loop_unroll_cost, 8 by default. The loops are planned on the walk that plans the call sites. for [unroll] lifts the limit and for [unroll_disable] keeps one loop. An array literal given to a parameter the body reads once, as a loop source, becomes that loop's source: a fixed array on the stack and no heap array. A callee body that ends in its one return splices with no result local and no scope block. The sink pass replaces a pure local read once in the next statement with its initializer; disable_forward keeps such locals. Nothing with an effect may sit between the two. A function that carries an annotation, and a generated one, keep their loops and locals: a macro may read that body after the optimizer. The shader fixtures set loop_unroll_cost = 0. CodeOfPolicies gains loop_unroll_cost and disable_forward after its last bound field, and dll_search_paths moves behind them. Serializer 291, DAS_POLICIES_VERSION 7, LLVM_JIT_CODEGEN_VERSION 0xCB. Co-Authored-By: Claude Fable 5.2 --- doc/source/reference/embedding/c_api.rst | 8 + doc/source/reference/language/options.rst | 13 + ...ructure_annotation-rtti-CodeOfPolicies.rst | 2 + include/daScript/ast/ast_serializer.h | 2 +- include/daScript/daScriptC.h | 6 +- include/daScript/simulate/code_of_policies.h | 8 +- modules/dasLLVM/daslib/llvm_jit_plan.das | 2 +- modules/dasLLVM/daslib/llvm_jit_run.das | 2 +- modules/dasLLVM/tests/_debug_info_root.das | 5 +- skills/internal/tests_in_repo.md | 11 + src/ast/ARCHITECTURE_EFFECTS.md | 45 ++ src/ast/ARCHITECTURE_INLINE.md | 75 +++ src/ast/ARCHITECTURE_LOOP_SOURCE.md | 11 +- src/ast/ast_effects.cpp | 16 + src/ast/ast_effects.h | 2 + src/ast/ast_generate_typed.h | 15 + src/ast/ast_infer_type.cpp | 8 - src/ast/ast_inline.cpp | 287 +++++++-- src/ast/ast_inscope_pod.cpp | 9 + src/ast/ast_inscope_pod.h | 1 + src/ast/ast_sink.cpp | 127 +++- src/builtin/module_builtin_ast_serialize.cpp | 2 +- src/builtin/module_builtin_rtti.cpp | 2 + src/misc/daScriptC.cpp | 2 + tests-cpp/small/test_policies_canary.cpp | 13 + tests/aot/CMakeLists.txt | 1 + tests/ast_match/test_comprehensions.das | 104 --- .../test_local_function_post_inference.das | 116 ++++ tests/cuda/_cuda_common.das | 1 + tests/gc/test_stackwalk.das | 8 +- tests/msl/_msl_common.das | 1 + tests/optimization/_inline_generic_helper.das | 8 + .../_inline_unoptimized_scope_helper.das | 10 + .../optimization/_loop_unroll_off_helper.das | 14 + tests/optimization/_optimized_body_helper.das | 27 + .../optimization_auto_inline_functions.das | 15 + tests/optimization/optimization_inline.das | 596 +++++++++++++++++- tests/optimization/optimization_sink.das | 174 ++++- ...uncategorized_disable_auto_inline_rtti.das | 21 + tests/spirv/_spirv_common.das | 1 + utils/mcp/subtools/compile_check.das | 2 + utils/mcp/tools/common.das | 11 +- 42 files changed, 1556 insertions(+), 228 deletions(-) create mode 100644 tests/ast_match/test_local_function_post_inference.das create mode 100644 tests/optimization/_loop_unroll_off_helper.das diff --git a/doc/source/reference/embedding/c_api.rst b/doc/source/reference/embedding/c_api.rst index 077b344b5b..07b496cbd2 100644 --- a/doc/source/reference/embedding/c_api.rst +++ b/doc/source/reference/embedding/c_api.rst @@ -352,6 +352,14 @@ Compilation policies - Initial heap size hint * - ``DAS_POLICY_STRING_HEAP_SIZE_HINT`` - Initial string heap size hint + * - ``DAS_POLICY_AUTO_INLINE_COST`` + - Node budget of a callee body the automatic inliner splices (default 32) + * - ``DAS_POLICY_MAX_UNRESERVED_SIZE`` + - A growing array resize past this byte size with no prior reserve panics + (default 64 MB) + * - ``DAS_POLICY_LOOP_UNROLL_COST`` + - A ``for`` loop of known passes unrolls when passes times body statements fits + this (default 8, 0 = never) See :ref:`tutorial_integration_c_sandbox`. diff --git a/doc/source/reference/language/options.rst b/doc/source/reference/language/options.rst index 357f6dcb1e..0d2d412827 100644 --- a/doc/source/reference/language/options.rst +++ b/doc/source/reference/language/options.rst @@ -201,6 +201,19 @@ Optimization - 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. + * - ``disable_forward`` + - bool + - false + - Keeps a local with a pure initializer that is read once, in the statement right after it. + Otherwise the read takes the initializer and the local goes away. + * - ``loop_unroll_cost`` + - int + - 8 + - Budget for unrolling a ``for`` loop whose passes are known at compile time (a constant + range, an array literal of constants, a fixed array): the loop unrolls when passes times + body statements fits the budget. 0 turns it off. ``for [unroll]`` lifts the limit for one + loop and ``for [unroll_disable]`` keeps one loop. It runs where automatic inlining runs: + an optimized build with no debugger and ``disable_auto_inline`` off. * - ``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 ec1612582c..5718041a5f 100644 --- a/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst +++ b/doc/source/stdlib/handmade/structure_annotation-rtti-CodeOfPolicies.rst @@ -117,3 +117,5 @@ Keeps the used-function set and the function and variable indices alive after th A compile under ``no_optimizations`` promotes the shared modules it requires into the process, as an optimizing compile does, so a later compile in the process reuses them; for a process that compiles many programs under one policy set and runs none of them (the lint). Off by default. Interpreter only: caps how deep framed calls to named functions may nest, panicking past the cap instead of exhausting the native stack; 0 leaves them unchecked. Host-side counterpart of ``options max_framed_call_depth`` (the option overrides the policy). Compiles the required modules on this many threads, each module once the modules it requires are done; 1 compiles them one after another, 0 uses the job queue's thread count. +Budget for unrolling a ``for`` loop whose passes are known at compile time - a constant range, an array literal of constants, a fixed array: the loop unrolls when passes times body statements fits this (default 8, so a one-statement body unrolls up to 8 passes). 0 turns it off; ``for [unroll]`` lifts the limit and ``for [unroll_disable]`` keeps one loop. It runs where automatic inlining runs: an optimized build with no debugger and ``disable_auto_inline`` off. Host-side counterpart of ``options loop_unroll_cost``. +Keeps a local with a pure initializer that is read once, in the statement right after it; otherwise the read takes the initializer and the local goes away. Host-side counterpart of ``options disable_forward`` (the option overrides the policy). diff --git a/include/daScript/ast/ast_serializer.h b/include/daScript/ast/ast_serializer.h index 526f737058..3932fb2e64 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 290; // 290: an inlined argument that reads a global substitutes + return 291; // 291: small constant loops unroll, a read-once local forwards } void serializeProgram ( ProgramPtr program, ModuleGroup & libGroup ) noexcept; diff --git a/include/daScript/daScriptC.h b/include/daScript/daScriptC.h index 8e360cf65c..5bd4996ed5 100644 --- a/include/daScript/daScriptC.h +++ b/include/daScript/daScriptC.h @@ -822,7 +822,8 @@ typedef enum das_bool_policy { 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_DISABLE_SINK // Disable the pass that sinks a pure local into the one `if` arm reading it + DAS_POLICY_DISABLE_SINK, // Disable the pass that sinks a pure local into the one `if` arm reading it + DAS_POLICY_DISABLE_FORWARD // Keep a pure local that is read once in the next statement } das_bool_policy; // Integer policy fields (stack size, heap limits). @@ -833,7 +834,8 @@ typedef enum das_int_policy { DAS_POLICY_HEAP_SIZE_HINT, // Initial heap size hint in bytes (uint32) DAS_POLICY_STRING_HEAP_SIZE_HINT, // Initial string heap size hint in bytes (uint32) DAS_POLICY_AUTO_INLINE_COST, // auto_inline_functions node budget (int32, default 32) - DAS_POLICY_MAX_UNRESERVED_SIZE // a growing array resize past this byte size without a prior reserve panics (uint64, default 64 MB) + DAS_POLICY_MAX_UNRESERVED_SIZE, // a growing array resize past this byte size without a prior reserve panics (uint64, default 64 MB) + DAS_POLICY_LOOP_UNROLL_COST // a loop of known passes unrolls when passes times body statements fits this (int32, default 8, 0 = never) } das_int_policy; // Create a new policies object with default values. diff --git a/include/daScript/simulate/code_of_policies.h b/include/daScript/simulate/code_of_policies.h index 5e5fb50ae7..0e6e9bf120 100644 --- a/include/daScript/simulate/code_of_policies.h +++ b/include/daScript/simulate/code_of_policies.h @@ -7,7 +7,7 @@ namespace das { // bump when CodeOfPolicies changes layout or meaning without changing size — a field // reorder/repurpose, or an insert that lands in a padding pocket (sizeof can't see those) - #define DAS_POLICIES_VERSION 6 + #define DAS_POLICIES_VERSION 7 // per-binary linkage for the ABI-stamp functions: at -O0 gcc/clang emit them as weak // default-visibility symbols, and the dynamic linker would bind every binary to the FIRST @@ -168,8 +168,6 @@ namespace das { int32_t jit_size_level = 0u; // Opt level for LLVM for binary size string jit_path_to_shared_lib; // Path to libDaScript. Optional, we'll try to find it in _das_root_/lib/ if not provided. string jit_path_to_linker; // Path to linker. Optional, we'll use lld-link from LLVM on Windows (MSVC), clang on mingw, c++ otherwise. - // dll loading - vector dll_search_paths; // additional search paths for dll loading // one-liners /*option*/ bool temp_table_lint_warning = false; bool module_cache = false; // a script's compile_file runs under the default module cache @@ -179,6 +177,10 @@ namespace das { /*option*/ uint32_t max_framed_call_depth = 0; // interpreter only; 0 = unchecked. /*option*/ bool promote_folded_int_constants = true; int32_t compile_threads = 1; // src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-dag + /*option*/ int32_t loop_unroll_cost = 8; // a loop of known passes unrolls when passes times body statements fits this; 0 = never + /*option*/ bool disable_forward = false; // keep a pure local that is read once in the next statement + // dll loading + vector dll_search_paths; // additional search paths for dll loading // the abi_stamp truth (a member so the NSDMI above can call it - complete-class context). // Low byte 0 keeps a pre-stamp libDaScript reading this word seeing aot == false - diff --git a/modules/dasLLVM/daslib/llvm_jit_plan.das b/modules/dasLLVM/daslib/llvm_jit_plan.das index 535c7e5840..24d5ebc56a 100644 --- a/modules/dasLLVM/daslib/llvm_jit_plan.das +++ b/modules/dasLLVM/daslib/llvm_jit_plan.das @@ -33,7 +33,7 @@ require jit // llvm_macro.das, llvm_jit_common.das, runtime helper ABI, default // target triple). Cache filenames fold this in, so a bump makes every // previously written DLL miss the cache on the next run and get GC'd. -let public LLVM_JIT_CODEGEN_VERSION : uint64 = 0xD2ul // the low-bit row-major and grid emitters +let public LLVM_JIT_CODEGEN_VERSION : uint64 = 0xD3ul // CodeOfPolicies: dll_search_paths is last let public JIT_FNV_PRIME : uint64 = 1099511628211ul diff --git a/modules/dasLLVM/daslib/llvm_jit_run.das b/modules/dasLLVM/daslib/llvm_jit_run.das index 9ce91ac47d..357b3c30f7 100644 --- a/modules/dasLLVM/daslib/llvm_jit_run.das +++ b/modules/dasLLVM/daslib/llvm_jit_run.das @@ -41,7 +41,7 @@ var LINK_WHOLE_LIB = false // when true, standalone exe links against the whole // Read by tests-cpp/small/test_jit_emitter_pin.cpp: FNV-1a64 of the emitter sources // (normalized to LF; file list in the test) -let LLVM_JIT_EMITTER_HASH : uint64 = 0xbe533500785f7574ul +let LLVM_JIT_EMITTER_HASH : uint64 = 0x3b8acc46668d7846ul [arch(at = "../ARCHITECTURE_FAST_MATH.md#never-fast-math")] def private apply_fast_math_to_module(m : LLVMOpaqueModule?) { diff --git a/modules/dasLLVM/tests/_debug_info_root.das b/modules/dasLLVM/tests/_debug_info_root.das index a9175c3d65..028405b842 100644 --- a/modules/dasLLVM/tests/_debug_info_root.das +++ b/modules/dasLLVM/tests/_debug_info_root.das @@ -1,4 +1,5 @@ options gen2 +options disable_forward // the debug-info test names every local of `hot` // child fixture of llvm_jit_debug_info.das: one function covering every DWARF shape the rail // describes - scalars, a struct argument, an enum, a string, a vector local, a nested block, @@ -22,9 +23,7 @@ enum Mode { var g_calls = 0 -def private invoke_block(blk : block<(a : int) : int>) { - return invoke(blk, 3) -} +def private invoke_block(blk : block<(a : int) : int>) => invoke(blk, 3) [export] def hot(n : int; scale : float; p : Point; m : Mode; tag : string) : int { diff --git a/skills/internal/tests_in_repo.md b/skills/internal/tests_in_repo.md index ed1567c8a9..e11c8cd39c 100644 --- a/skills/internal/tests_in_repo.md +++ b/skills/internal/tests_in_repo.md @@ -101,6 +101,17 @@ Two more ways a structural anchor vanishes or hides, neither stopped by `[never_ `for_each_function("")`, and drop the `(` from body-text checks on calls to it - the call site spells the mangled name too. +**A probe of the loop unroll or the local forward sits on an anchor whose only annotation is +`[export]`.** `[export]` keeps the anchor in the module in place of `[never_inline]`; any other +annotation - `[never_inline]` and `[test]` among them - turns both rewrites off in that function +(`src/ast/ARCHITECTURE_EFFECTS.md#macro-owned-shape`). The unroll copies the body once per pass of +a `for` over a constant range, an array literal of constants or a fixed array, when passes times +body statements is at most `loop_unroll_cost` (8 by default). The forward takes a `let` whose +initializer has no side effect and whose one read sits in the next statement, puts the initializer +in place of the read, and drops the `let`. A loop a test needs kept is written +`for [unroll_disable]`; a `let` a test needs kept sits in a file with `options disable_forward`, +with a comment on that line saying which test needs it. + ## Shared fixtures and the hyphen trap Shared test helpers go in `_common.das` module files (e.g. `tests/linq/_common.das`). A diff --git a/src/ast/ARCHITECTURE_EFFECTS.md b/src/ast/ARCHITECTURE_EFFECTS.md index a67a928e67..85e51c7059 100644 --- a/src/ast/ARCHITECTURE_EFFECTS.md +++ b/src/ast/ARCHITECTURE_EFFECTS.md @@ -100,3 +100,48 @@ condition, the other arm or after the `if`. A local lives in its own block, so b 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. + +## Forwarding a pure local read once {#forward-read-once-let} + +The sink visitor also replaces the single read of a local with the local's initializer and drops +the `let`, when the read is in the statement right after it: `let t = a * 3; g += t` becomes +`g += a * 3`. The store into the local and its stack slot are gone. A spliced body leaves many +such locals: an argument bound to a local, a result read once. + +`forwardableLet` asks what the sink asks of the `let` - one variable, no reference, no cleanup, +a `droppable` initializer - and also that the initializer is neither a move nor a clone and is a +value of the local's own type. The variable is read once in the whole function, as a value. + +The initializer moves from in front of the statement to the place of the read, so nothing with +an effect may run between the two. `evaluatesAfterPureSiblings` checks each step of the path +from the statement down to the read. The step passes under these parents, and under no other: + +- a `return`, the condition of an `if`, the sources of a `for`, the initializer of a + one-variable `let`; +- a read of a reference, a cast, a pointer dereference, a field, a one-operand operator; +- a two-operand operator other than `&&` and `||`, an index, a call's arguments, the elements + of a string builder - when every other operand of that parent is `droppable`. + +Every other operand, not only the ones in front: the order a call evaluates its arguments in is +not defined. `&&`, `||`, `??` and a safe index evaluate an operand on some paths only, and +moving an evaluation onto one path is the sink's rewrite, with the conditions that section +gives. + +The pass reads the flags the sink reads and builds none. A function whose shape a macro owns +keeps its locals (`ARCHITECTURE_EFFECTS.md#macro-owned-shape`). `options disable_forward` turns +the forward off and leaves the sink on; `options disable_sink` turns the whole pass off. + +## A function whose shape a macro owns {#macro-owned-shape} + +`hasMacroOwnedShape` is true of a function that carries an annotation other than `export` and +`unused_argument`, and of a generated function that is neither a lambda nor a local function. A +macro may read such a body after the optimizer ran: a shader backend lowers an entry point, +`[flatten]` matches the `let`s of the twin it generated. Forwarding a local and unrolling a loop +(`ARCHITECTURE_INLINE.md#loop-unroll`) keep the values and change the statements, which is what +such a macro reads, so both leave these functions as written. + +The test is per function. A function a macro reaches only through a call - a helper a kernel +calls, a method beside the annotated one - carries no mark. A file of such functions opts out +by option: the GPU kernel sources of dasLLAMA set `options loop_unroll_cost = 0` and +`options disable_forward`, and the shader emitter fixtures under `tests` set the first. They +keep the sink on: it shaped those kernels before either rewrite existed. diff --git a/src/ast/ARCHITECTURE_INLINE.md b/src/ast/ARCHITECTURE_INLINE.md index abb862d277..1395abddf0 100644 --- a/src/ast/ARCHITECTURE_INLINE.md +++ b/src/ast/ARCHITECTURE_INLINE.md @@ -96,3 +96,78 @@ has no observable effects and no later argument has an effect, and binds a local `isReorderSafe` is the one walk behind both tests - may this expression move, does this argument have an effect - and its `stableGlobals` argument says whether a global read counts as stable. + +## Unrolling a loop of known passes {#loop-unroll} + +The patch pass replaces a `for` loop with one copy of its body for each pass, when the passes are +known at compile time and few. In the interpreter a short loop pays its setup and one loop node +a pass; the copies pay neither, and a constant in place of the loop variable folds. + +`InlineCollect` plans every loop on the walk that plans the call sites, so the pass has no +visitor of its own. `InlinePatch::unrollLoop` runs after the function's call sites are spliced, +an inner loop ahead of the loop that holds it. A loop a splice brings in is planned by the next +round. + +The loop has one source and one variable. `loopPassValues` gives the value of each pass: + +- a constant range, of any of the four range types - a typed constant a pass; +- a stack array literal whose elements are all constants - the elements; +- a fixed-array variable - `a[i]` with a constant index, a reference to the element. + +`loop_unroll_cost` (`CodeOfPolicies`, `options loop_unroll_cost`, 8 by default) is the largest +product of passes and body statements, counted over every block of the body. So a body of one +statement unrolls up to 8 passes and a body of two up to 4. A loop of one pass always unrolls, +and a loop of no passes goes away. `for [unroll]` lifts the limit to 256 passes and +`for [unroll_disable]` keeps the loop. The option at 0 turns the rewrite off, and it runs only +where the best-effort inline tier runs: an optimized build with no debugger. + +The loop stays when its body has a `finally` or an annotation, or holds a `break` or `continue` +of this loop, a `goto`, a label, `try`, `yield`, `assume`, a generator, or a lambda, a local +function or a block literal that captures. A `break` of a loop inside the body does not keep +it. With constants for values the loop also stays when the body writes the loop variable, takes +its address or passes it by reference: a constant has no storage. A function whose shape a macro owns (`ARCHITECTURE_EFFECTS.md#macro-owned-shape`) and +an instance of another module's generic keep their loops. + +Each pass is a clone of the body with its locals renamed under a prefix of its own and the loop +variable substituted, built as a splice builds a callee body. The passes go into the block in +place of the loop with no scope block around them; the renaming is what lets them share one. + +## A literal argument that becomes the loop source {#inline-loop-source-argument} + +`f([1, 2, 3, 4])` into `def f(a : array) { for (x in a) ... }` splices as a loop over the +literal itself: a fixed array on the stack, as `for (x in [1, 2, 3, 4])` is +(`ARCHITECTURE_LOOP_SOURCE.md#stack-loop-literal`). No heap array is built, and the loop is one +the unroll reads. + +`stackLiteralForLoopSource` takes the argument when the body reads the parameter exactly once, +as the source of a `for` loop that is not inside another loop. `ParamReadScan` records that read +(`readAsLoopSource`) and counts loop depth from the loop's body, so a source is not under its +own loop. The argument is an array literal `stackLoopLiteral` accepts, or a literal that is on +the stack already. + +The literal is then evaluated at the loop header, after every statement the body has in front +of the loop. An element that is not a constant must be safe to move (`isReorderSafe`). When the +callee has observable effects, or an argument after this one has an effect, a read of a global +is not safe to move, and the element may read only locals nothing else can reach +(`argReadsOnlyPrivateLocals`). A splice that needs a scope of its own binds the array to a +local as before. + +The loop variable is typed against the parameter, so it is constant when the parameter is. The +literal is not, and no inference runs after a splice: `InlineBodyRewriter` gives the variable +the constness of the literal. AOT writes the variable's type out, and a mismatch there does not +compile. + +## A body that ends in its `return` {#inline-trailing-return} + +A callee body of several statements whose only `return` is its last statement splices flat: +the statements in front of the `return` go in front of the caller's statement, and the returned +expression takes the place of the call. `trailingReturn` finds the shape. Any other body with +statements goes into a scope block and stores its result in a local the caller reads; that +local and block cost nodes, and they hide the returned expression from the folds that follow. + +The shape needs two statements or more, no `finally`, a last statement that returns a value +without a move, and no other `return` and no label in front of it. The site must not store its +result in place and the body must need no scope of its own. The callee is a function: an +invoked block literal keeps the block form. So does a callee that uses `unsafe`: its statements +need the generated wrapper (`ARCHITECTURE_INLINE.md#inline-unsafe-expression-graft`), and a +flat splice has no one node to put under it. diff --git a/src/ast/ARCHITECTURE_LOOP_SOURCE.md b/src/ast/ARCHITECTURE_LOOP_SOURCE.md index b181f32006..1fd3195627 100644 --- a/src/ast/ARCHITECTURE_LOOP_SOURCE.md +++ b/src/ast/ARCHITECTURE_LOOP_SOURCE.md @@ -54,13 +54,14 @@ call and not its arguments. ## An array literal as a loop source (`ast_infer_type.cpp`) {#stack-loop-literal} `for (x in [a, b, c])` iterates a fixed array on the stack. A gen2 array literal is -`to_array_move` over a make-array node built on the heap; where one is a loop source, inference -(`stackLoopLiteral`) drops the call and leaves the node, which then builds `T[N]` as -`fixed_array(a, b, c)` does. No policy asks for it: the literal is a temporary nothing else names, -so it cannot outlive the loop. It stays a heap array when its elements own heap, which a stack +`to_array_move` over a make-array node built on the heap; where one is a loop source that +`stackLoopLiteral` accepts, inference (`visitForSource`) drops the call and leaves the node, +which then builds `T[N]` as `fixed_array(a, b, c)` does. No policy asks for it: the literal is +a temporary nothing else names, so it cannot outlive the loop. It stays a heap array when its elements own heap, which a stack array has no collect to free, and past 1024 bytes, which would otherwise come out of the function's stack. A generator takes the same rewrite, and the lowering of a loop that yields -keeps the fixed array in the generator's frame. +keeps the fixed array in the generator's frame. The test lives in `ast_inscope_pod.cpp`; the +inliner asks it of a literal argument too (`ARCHITECTURE_INLINE.md#inline-loop-source-argument`). ## A stack array literal under a call argument (`ast_inscope_pod.cpp`, `ast_allocate_stack.cpp`) {#stack-array-argument} diff --git a/src/ast/ast_effects.cpp b/src/ast/ast_effects.cpp index 94a33ec3c7..dddc062928 100644 --- a/src/ast/ast_effects.cpp +++ b/src/ast/ast_effects.cpp @@ -28,4 +28,20 @@ namespace das { bool droppable ( Expression * expr ) { return expr && expr->noSideEffects && !expr->mayRaise; } + + const Annotation * macroAnnotation ( const Function * fn ) { + for ( auto & ann : fn->annotations ) { + if ( !ann->annotation ) continue; + auto & name = ann->annotation->name; + if ( name=="export" || name=="unused_argument" ) continue; + return &*ann->annotation; + } + return nullptr; + } + + // src/ast/ARCHITECTURE_EFFECTS.md#macro-owned-shape + bool hasMacroOwnedShape ( const Function * fn ) { + if ( fn->generated && !fn->lambda && !fn->localFunction ) return true; + return macroAnnotation(fn)!=nullptr; + } } diff --git a/src/ast/ast_effects.h b/src/ast/ast_effects.h index 827f5a364c..02e1af86ac 100644 --- a/src/ast/ast_effects.h +++ b/src/ast/ast_effects.h @@ -6,6 +6,8 @@ namespace das { bool nodeRaises ( Expression * expr ); bool callRaises ( Function * fn ); bool droppable ( Expression * expr ); + const Annotation * macroAnnotation ( const Function * fn ); + bool hasMacroOwnedShape ( const Function * fn ); // a global of a frozen (already compiled) module is read-only: module jobs that require it // must not stamp its flags. src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers inline bool isFrozenGlobal ( const Variable * var ) { diff --git a/src/ast/ast_generate_typed.h b/src/ast/ast_generate_typed.h index e89ea10281..252898f88e 100644 --- a/src/ast/ast_generate_typed.h +++ b/src/ast/ast_generate_typed.h @@ -2,6 +2,7 @@ #include "daScript/ast/ast.h" #include "daScript/ast/ast_expressions.h" +#include "daScript/ast/ast_visitor.h" namespace das { @@ -25,4 +26,18 @@ namespace das { ExprIfThenElse * makeIf ( const LineInfo & at, Expression * cond, Expression * ifTrue, Expression * ifFalse ); ExprCopy * makeCopy ( const LineInfo & at, Expression * left, Expression * right ); ExprMove * makeMove ( const LineInfo & at, Expression * left, Expression * right ); + + // replace one specific node (by identity) inside a statement + class ReplaceNode : public Visitor { + public: + ReplaceNode ( Expression * w, const ExpressionPtr & r ) : what(w), with(r) {} + Expression * what = nullptr; + ExpressionPtr with = nullptr; + bool done = false; + protected: + virtual ExpressionPtr visitExpression ( Expression * expr ) override { + if ( expr==what ) { done = true; return with; } + return Visitor::visitExpression(expr); + } + }; } diff --git a/src/ast/ast_infer_type.cpp b/src/ast/ast_infer_type.cpp index be426a86c1..35bc2b5a7c 100644 --- a/src/ast/ast_infer_type.cpp +++ b/src/ast/ast_infer_type.cpp @@ -5474,14 +5474,6 @@ namespace das { that->isForLoopSource = true; markNoDiscard(that); } - // src/ast/ARCHITECTURE_LOOP_SOURCE.md#stack-loop-literal - static ExprMakeArray *stackLoopLiteral(Expression *source) { - const uint64_t maxStackLiteralBytes = 1024; - auto mka = heapArrayLiteral(source); - if (!mka || literalElementsOwnHeap(mka)) return nullptr; - auto bytes = uint64_t(mka->values.size()) * mka->recordType->getSizeOf64(); - return bytes <= maxStackLiteralBytes ? mka : nullptr; - } ExpressionPtr InferTypes::visitForSource(ExprFor *expr, Expression *that, bool last) { if (auto mka = stackLoopLiteral(that)) { mka->makeArrayOnHeap = false; diff --git a/src/ast/ast_inline.cpp b/src/ast/ast_inline.cpp index b4173eb470..8f542bfc69 100644 --- a/src/ast/ast_inline.cpp +++ b/src/ast/ast_inline.cpp @@ -4,7 +4,9 @@ #include "daScript/ast/ast_visitor.h" #include "daScript/ast/ast_const_visitor.h" #include "daScript/ast/ast_expressions.h" +#include "ast_effects.h" #include "ast_generate_typed.h" +#include "ast_inscope_pod.h" namespace das { @@ -165,6 +167,7 @@ namespace das { das_hash_set readAsRefArg; // handed onward to a REF parameter - needs real storage, not a value das_hash_set readAsPlace; das_hash_set readAsValue; + das_hash_set readAsLoopSource; }; class ParamReadScan : public ConstVisitor { @@ -177,8 +180,9 @@ namespace das { ParamReadStats & stats; int loopDepth = 0; virtual bool canVisitQuoteSubexpression ( const ExprQuote * ) override { return false; } - virtual void preVisit ( const ExprFor * expr ) override { ConstVisitor::preVisit(expr); loopDepth ++; } - virtual void visit ( const ExprFor * expr ) override { loopDepth --; ConstVisitor::visit(expr); } + // src/ast/ARCHITECTURE_INLINE.md#inline-loop-source-argument + virtual void preVisitForBody ( const ExprFor * expr, const Expression * body ) override { ConstVisitor::preVisitForBody(expr, body); loopDepth ++; } + virtual void visit ( const ExprFor * expr ) override { if ( expr->body ) loopDepth --; ConstVisitor::visit(expr); } virtual void preVisit ( const ExprWhile * expr ) override { ConstVisitor::preVisit(expr); loopDepth ++; } virtual void visit ( const ExprWhile * expr ) override { loopDepth --; ConstVisitor::visit(expr); } // a block literal's body may run any number of times - reads inside count as under-loop @@ -203,6 +207,7 @@ namespace das { if ( expr->variable && params.find(expr->variable)!=params.end() ) { stats.readCount[expr->variable] ++; if ( loopDepth ) stats.readUnderLoop.insert(expr->variable); + if ( expr->isForLoopSource ) stats.readAsLoopSource.insert(expr->variable); if ( expr->r2v || underR2V.find(expr)!=underR2V.end() || derefBase.find(expr)!=derefBase.end() ) { stats.readAsValue.insert(expr->variable); } else if ( !expr->type || !expr->type->isRefType() ) { @@ -620,8 +625,15 @@ namespace das { if ( rit != rename.end() ) var->name = rit->second; } } + // src/ast/ARCHITECTURE_INLINE.md#inline-loop-source-argument virtual ExpressionPtr visit ( ExprFor * expr ) override { popDeclFrame(); + for ( size_t i=0, is=das::min(expr->iteratorVariables.size(), expr->sources.size()); i!=is; ++i ) { + auto & var = expr->iteratorVariables[i]; + auto & source = expr->sources[i]; + var->loop_source = source; + if ( source->rtti_isMakeArray() && source->type && var->type ) var->type->constant = source->type->constant; + } return Visitor::visit(expr); } virtual void preVisit ( ExprBlock * block ) override { @@ -684,20 +696,6 @@ namespace das { } }; - // replace one specific node (by identity) inside a statement - class ReplaceNode : public Visitor { - public: - ReplaceNode ( Expression * w, const ExpressionPtr & r ) : what(w), with(r) {} - Expression * what = nullptr; - ExpressionPtr with = nullptr; - bool done = false; - protected: - virtual ExpressionPtr visitExpression ( Expression * expr ) override { - if ( expr==what ) { done = true; return with; } - return Visitor::visitExpression(expr); - } - }; - // ----- statement anchors (same scheme as the CSE prescan) ----- // where a splice inserts its manufactured statements (arg/result temps, the body) @@ -723,14 +721,9 @@ namespace das { // annotations other than inert markers may carry call-site semantics (verifyCall, // transform, per-call codegen) that splicing the call away would bypass bool isAnnotated ( Function * fn, string & why ) { - for ( auto & ann : fn->annotations ) { - if ( !ann->annotation ) continue; - auto & nm = ann->annotation->name; - if ( nm=="export" || nm=="unused_argument" ) continue; - why = "annotated function [" + nm + "]"; - return true; - } - return false; + auto annotation = macroAnnotation(fn); + if ( annotation ) why = "annotated function [" + annotation->name + "]"; + return annotation!=nullptr; } // ----- auto-inline budget (heuristic plain-call candidacy) ----- @@ -739,6 +732,7 @@ namespace das { int nodes = 0; bool hasLoop = false; int64_t stackBytes = 0; // sum of local let sizes - the frame the body owns + int statements = 0; }; BodyCost bodyCost ( Expression * body ) { @@ -746,6 +740,7 @@ namespace das { lookupExpressions(body, [&](const Expression * e) { bc.nodes ++; if ( e->rtti_isFor() || e->rtti_isWhile() ) bc.hasLoop = true; + if ( e->rtti_isBlock() ) bc.statements += int(static_cast(e)->list.size()); if ( e->rtti_isLet() ) { auto let = static_cast(e); for ( auto & v : let->variables ) { @@ -767,6 +762,7 @@ namespace das { bool blockLiterals = false; // block-literal call sites + invoke-block sites bool functions = false; // heuristic tier over plain calls (auto_inline_functions) int budget = 32; // heuristic node budget (auto_inline_cost) + int unrollBudget = 0; Module * thisModule = nullptr; // heuristic tier is same-module-only das_hash_map * budgetCache = nullptr; das_hash_set * budgetExempt = nullptr; // private, referenced exactly once: moves, not duplicates @@ -817,11 +813,77 @@ namespace das { return nullptr; } + struct PlannedLoop { + ExprFor * loop = nullptr; + ExprBlock * block = nullptr; + }; + + constexpr uint64_t UNROLL_ANNOTATION_MAX_PASSES = 256; + + template + bool rangePassValues ( const LineInfo & at, vec4f bounds, Type valueType, uint64_t maxPasses, vector & values ) { + auto r = cast::to(bounds); + if ( r.from >= r.to ) return true; + uint64_t count = uint64_t(r.to) - uint64_t(r.from); + if ( count > maxPasses ) return false; + for ( uint64_t i=0; i!=count; ++i ) { + auto type = new TypeDecl(valueType, at); + type->constant = true; + values.push_back(makeTypedConst(at, type, cast::from(ValueT(uint64_t(r.from) + i)))); + } + return true; + } + + // src/ast/ARCHITECTURE_INLINE.md#loop-unroll + bool loopPassValues ( ExprFor * loop, uint64_t maxPasses, vector & values, bool & constantValues ) { + if ( loop->sources.size()!=1 || loop->iteratorVariables.size()!=1 ) return false; + Expression * src = loop->sources[0]; + Variable * var = loop->iteratorVariables[0]; + if ( !src->type || !var->type ) return false; + constantValues = true; + if ( src->rtti_isConstant() ) { + vec4f bounds = static_cast(src)->value; + switch ( src->type->baseType ) { + case Type::tRange: return rangePassValues(src->at, bounds, Type::tInt, maxPasses, values); + case Type::tURange: return rangePassValues(src->at, bounds, Type::tUInt, maxPasses, values); + case Type::tRange64: return rangePassValues(src->at, bounds, Type::tInt64, maxPasses, values); + case Type::tURange64: return rangePassValues(src->at, bounds, Type::tUInt64, maxPasses, values); + default: return false; + } + } + if ( !src->type->isFixedArray() || src->type->fixedDim<0 || uint64_t(src->type->fixedDim)>maxPasses ) return false; + if ( src->rtti_isMakeArray() && !src->rtti_isMakeTuple() ) { + auto literal = static_cast(src); + if ( literal->makeArrayOnHeap ) return false; + for ( auto & value : literal->values ) { + if ( !value->rtti_isConstant() ) return false; + } + values.assign(literal->values.begin(), literal->values.end()); + return true; + } + if ( src->rtti_isVar() ) { + constantValues = false; + for ( int32_t i=0, is=src->type->fixedDim; i!=is; ++i ) { + auto indexType = new TypeDecl(Type::tInt, src->at); + indexType->constant = true; + auto array = cloneTyped(src); + array->isForLoopSource = false; + auto element = new ExprAt(src->at, array, makeTypedConst(src->at, indexType, cast::from(i))); + element->type = new TypeDecl(*var->type); + element->type->ref = true; + values.push_back(element); + } + return true; + } + return false; + } + // collects splice sites, each tagged with its (block, index) statement anchor class InlineCollect : public Visitor { public: InlineCollect ( const AutoInlineCfg & cfg, TextWriter * log = nullptr ) : cfg(cfg), logs(log) {} vector sites; // in visit order: within a block, increasing index + vector loops; protected: const AutoInlineCfg & cfg; TextWriter * logs = nullptr; // log_optimization sink; a degraded [inline] contract must be visible @@ -848,6 +910,11 @@ namespace das { Visitor::preVisitBlockExpression(block, expr); if ( !blockStack.empty() && blockStack.back().block==block ) blockStack.back().index++; } + // src/ast/ARCHITECTURE_INLINE.md#loop-unroll + virtual ExpressionPtr visit ( ExprFor * expr ) override { + if ( cfg.unrollBudget>0 && !blockStack.empty() ) loops.push_back(PlannedLoop{expr, blockStack.back().block}); + return Visitor::visit(expr); + } void plan ( Expression * expr, SiteKind kind ) { if ( auto callee = callLikeFunc(expr) ) { if ( moduleNeverInlines(callee) ) { // stays a plain call @@ -1195,6 +1262,31 @@ namespace das { return false; } + // src/ast/ARCHITECTURE_INLINE.md#inline-loop-source-argument + ExprMakeArray * stackLiteralForLoopSource ( Expression * arg, Variable * param, const ParamReadStats & stats, + const SiteArgs & sa, bool stableGlobals ) { + auto literal = stackLoopLiteral(arg); + bool onHeap = literal!=nullptr; + if ( !literal && arg->rtti_isMakeArray() && !arg->rtti_isMakeTuple() ) literal = static_cast(arg); + if ( !literal || !literal->makeType || (!onHeap && literal->makeArrayOnHeap) ) return nullptr; + auto reads = stats.readCount.find(param); + if ( reads==stats.readCount.end() || reads->second!=1 ) return nullptr; + if ( !stats.readAsLoopSource.count(param) || stats.readUnderLoop.count(param) ) return nullptr; + for ( auto & value : literal->values ) { + if ( value->rtti_isConstant() ) continue; + if ( !isReorderSafe(value, stableGlobals) ) return nullptr; + if ( !stableGlobals && !argReadsOnlyPrivateLocals(value, sa) ) return nullptr; + } + auto stack = static_cast(cloneTyped(literal)); + stack->isCallArgument = false; + stack->isForLoopSource = true; + if ( onHeap ) { + stack->makeArrayOnHeap = false; + stack->type = makeFixedArrayTypeDecl(int32_t(stack->values.size()), new TypeDecl(*stack->makeType)); + } + return stack; + } + bool exprContains ( Expression * root, Expression * what ) { if ( root==what ) return true; vector> kids; @@ -1703,6 +1795,18 @@ namespace das { } }; + // src/ast/ARCHITECTURE_INLINE.md#inline-trailing-return + ExprReturn * trailingReturn ( ExprBlock * body ) { + auto & list = body->list; + if ( list.size()<2 || !body->finalList.empty() || !list.back()->rtti_isReturn() ) return nullptr; + auto ret = static_cast(list.back()); + if ( !ret->subexpr || ret->moveSemantics ) return nullptr; + for ( size_t i=0, is=list.size()-1; i!=is; ++i ) { + if ( list[i]->rtti_isLabel() || ReturnStoreRewrite::stmtHasReturn(list[i]) ) return nullptr; + } + return ret; + } + } // anonymous namespace // ----- the [inline] shape contract ----- @@ -1931,6 +2035,7 @@ namespace das { int inlinedAuto = 0; // auto block-literal call sites int invokeBlocks = 0; // invoke-of-literal sites int declined = 0; // best-effort sites the pass passed on + int unrolled = 0; das_hash_map statsCache; das_hash_map shapeCache; das_hash_map> autoOkCache; @@ -2124,56 +2229,111 @@ namespace das { bool tryLowerCallPosition ( const PlannedSite & site, const SpliceSubject & subj, CallerSpliceState & state, int anchorIndex ); void spliceStatements ( Function * caller, const PlannedSite & site, const SpliceSubject & subj, - const SpliceInputs & in, ArgPlan & plan, CallerSpliceState & state, int anchorIndex, bool exprBody ); + const SpliceInputs & in, ArgPlan & plan, CallerSpliceState & state, int anchorIndex, bool exprBody, bool flatBody ); bool classifyArguments ( Function * caller, const PlannedSite & site, const SpliceSubject & subj, const SpliceInputs & in, ArgPlan & plan ); void processSite ( Function * caller, const PlannedSite & site, CallerSpliceState & state ); + void unrollLoop ( const PlannedLoop & site, int unrollBudget ); void processFunction ( Function * caller ); void reportUnsplicedCalls ( Function * caller ); }; + // src/ast/ARCHITECTURE_EFFECTS.md#macro-owned-shape AutoInlineCfg InlinePatch::callerAutoCfg ( Function * caller ) { AutoInlineCfg callerCfg = moduleAutoCfg; - if ( !callerCfg.functions ) return callerCfg; + if ( !callerCfg.functions && !callerCfg.unrollBudget ) return callerCfg; string why; - if ( isAnnotated(caller, why) ) { // like [template] or [some_fancy_macro] - callerCfg.functions = false; - } else if ( caller->fromGeneric && originOf(caller)->module - && originOf(caller)->module != program->thisModule.get() ) { + bool foreignInstance = caller->fromGeneric && originOf(caller)->module + && originOf(caller)->module != program->thisModule.get(); + if ( hasMacroOwnedShape(caller) ) callerCfg.unrollBudget = 0; + if ( isAnnotated(caller, why) || foreignInstance ) { // like [template] or [some_fancy_macro] callerCfg.functions = false; - } else if ( bodyCost(caller->body).stackBytes > AUTO_INLINE_CALLER_FRAME_BYTES ) { - callerCfg.functions = false; - } else if ( callerOnCallCycle(caller) ) { // recursive or recursive-ish + callerCfg.unrollBudget = 0; + } else if ( callerCfg.functions && (bodyCost(caller->body).stackBytes > AUTO_INLINE_CALLER_FRAME_BYTES + || callerOnCallCycle(caller)) ) { // recursive or recursive-ish callerCfg.functions = false; } return callerCfg; } + // src/ast/ARCHITECTURE_INLINE.md#loop-unroll + void InlinePatch::unrollLoop ( const PlannedLoop & site, int unrollBudget ) { + auto loop = site.loop; + auto & list = site.block->list; + auto slot = find(list.begin(), list.end(), loop); + if ( slot==list.end() ||!loop->body || !loop->body->rtti_isBlock() ) return; + auto body = static_cast(loop->body); + if ( !body->finalList.empty() || !body->annotations.empty() ) return; + if ( loop->annotations.getBoolOption("unroll_disable", false) ) return; + uint64_t maxPasses = UNROLL_ANNOTATION_MAX_PASSES; + if ( !loop->annotations.getBoolOption("unroll", false) ) { + maxPasses = das::max(uint64_t(unrollBudget) / uint64_t(das::max(bodyCost(body).statements, 1)), uint64_t(1)); + } + vector values; + bool constantValues; + if ( !loopPassValues(loop, maxPasses, values, constantValues) ) return; + CanInlineScan shape(true); + body->visit(shape); + if ( shape.bad ) return; + Variable * var = loop->iteratorVariables[0]; + if ( constantValues ) { + ParamReadStats stats; + ParamReadScan scan(loop->iteratorVariables, stats); + body->visit(scan); + if ( stats.readAsPlace.count(var) || stats.readAsRefArg.count(var) ) return; + } + auto & inlineId = program->thisModule->inlineTempIndex; + vector unrolledStatements; + for ( auto & value : values ) { + das_hash_map rename; + das_hash_set canShadowArgs; + LocalNameCollect names(rename, canShadowArgs, INLINE_TEMP_PREFIX + to_string(inlineId) + "_l_"); + body->visit(names); + if ( !canShadowArgs.empty() ) return; + das_hash_map paramSub; + paramSub[var].substitute = value; + InlineBodyRewriter rewriter(paramSub, rename, loop->at, false); + auto pass = static_cast(cloneTyped(body)->visit(rewriter)); + unrolledStatements.insert(unrolledStatements.end(), pass->list.begin(), pass->list.end()); + inlineId ++; + } + if ( logOpt && logs ) *logs << "UNROLL " << values.size() << " pass(es) at " << loop->at.describe() << "\n"; + slot = list.erase(slot); + list.insert(slot, unrolledStatements.begin(), unrolledStatements.end()); + unrolled ++; + changed = true; + } + void InlinePatch::processFunction ( Function * caller ) { if ( moduleNeverInlines(caller) ) return; // the instance body is that module's code: leave it alone AutoInlineCfg callerCfg = callerAutoCfg(caller); InlineCollect collect(callerCfg, logOpt ? logs : nullptr); caller->body->visit(collect); - if ( collect.sites.empty() ) return; - CallerSpliceState state; - if ( moduleAutoCfg.blockLiterals ) { - BlockBindingScan bscan; - caller->body->visit(bscan); - for ( auto & kv : bscan.binding ) { - if ( bscan.disq.find(kv.first)==bscan.disq.end() ) state.bindings[kv.first] = kv.second; + if ( collect.sites.empty() && collect.loops.empty() ) return; + bool changedBefore = changed; + changed = false; + if ( !collect.sites.empty() ) { + CallerSpliceState state; + if ( moduleAutoCfg.blockLiterals ) { + BlockBindingScan bscan; + caller->body->visit(bscan); + for ( auto & kv : bscan.binding ) { + if ( bscan.disq.find(kv.first)==bscan.disq.end() ) state.bindings[kv.first] = kv.second; + } } - } - { - DeclNameCollect dnc(state.callerDeclNames); - caller->body->visit(dnc); - for ( auto & arg : caller->arguments ) { - state.callerDeclNames.insert(arg->name); - if ( !arg->aka.empty() ) state.callerDeclNames.insert(arg->aka); + { + DeclNameCollect dnc(state.callerDeclNames); + caller->body->visit(dnc); + for ( auto & arg : caller->arguments ) { + state.callerDeclNames.insert(arg->name); + if ( !arg->aka.empty() ) state.callerDeclNames.insert(arg->aka); + } + } + for ( auto & site : collect.sites ) { + processSite(caller, site, state); } } - bool changedBefore = changed; - changed = false; - for ( auto & site : collect.sites ) { - processSite(caller, site, state); + for ( auto & site : collect.loops ) { + unrollLoop(site, callerCfg.unrollBudget); } if ( changed ) splicedCallers.insert(caller); changed |= changedBefore; @@ -2441,6 +2601,13 @@ namespace das { } else { if ( !makeArgTemp(cloneTyped(arg), false, false, true) ) return false; } + } else if ( auto stack = needScope ? nullptr : stackLiteralForLoopSource(argLeaf, param, stats, sa, + writeFree && !effectsAfter[ai]) ) { + sub.substitute = stack; + if ( logOpt && logs ) { + *logs << "LOOP-SOURCE-LITERAL " << subjName << " argument " << param->name + << " at " << callLike->at.describe() << "\n"; + } } else if ( arg->type && (arg->type->ref || rootsInVar(argLeaf)) ) { // lvalue chain: bind a reference once, like the call did auto init = cloneTyped(arg); init->alwaysSafe = true; // generated binding to real storage @@ -2780,7 +2947,7 @@ namespace das { // every declinable check runs BEFORE the prefix hoist mutates the statement - a // later decline would orphan the _pre reads (30838, or a segfault in access flags) void InlinePatch::spliceStatements ( Function * caller, const PlannedSite & site, const SpliceSubject & subj, - const SpliceInputs & in, ArgPlan & plan, CallerSpliceState & state, int anchorIndex, bool exprBody ) { + const SpliceInputs & in, ArgPlan & plan, CallerSpliceState & state, int anchorIndex, bool exprBody, bool flatBody ) { auto callLike = site.callLike; Function * calleeFn = subj.fn; // null for InvokeBlock const string & subjName = subj.name; @@ -2888,6 +3055,14 @@ namespace das { callReplacement = underCalleeUnsafe(calleeFn, cloned->visit(rewriter), callLike->at); } for ( auto & t : temps ) splice.push_back(t); + } else if ( flatBody ) { + for ( auto & t : temps ) splice.push_back(t); + auto bodyClone = static_cast(cloneTyped(in.body, &plan.boundParams)); + bodyClone->visit(stamp); + auto flat = static_cast(bodyClone->visit(rewriter)); + callReplacement = static_cast(flat->list.back())->subexpr; + splice.insert(splice.end(), flat->list.begin(), flat->list.end()-1); + if ( logOpt && logs ) *logs << "FLAT-RETURN " << subjName << " at " << callLike->at.describe() << "\n"; } else { auto bodyClone = static_cast(cloneTyped(in.body, &plan.boundParams)); if ( calleeFn ) bodyClone->visit(stamp); @@ -3023,7 +3198,9 @@ namespace das { return; } if ( tryLowerCallPosition(site, subj, state, anchorIndex) ) return; - spliceStatements(caller, site, subj, in, plan, state, anchorIndex, exprBody); + bool flatBody = !exprBody && !storesInPlace && !in.needScope + && calleeFn && !calleeFn->hasUnsafe && trailingReturn(in.body); + spliceStatements(caller, site, subj, in, plan, state, anchorIndex, exprBody, flatBody); } // DFS postorder over the splice graph inside this module, [inline] functions @@ -3299,6 +3476,7 @@ namespace das { autoCfg.blockLiterals = autoEnabled; autoCfg.functions = autoFns; autoCfg.budget = options.getIntOption("auto_inline_cost", policies.auto_inline_cost); + autoCfg.unrollBudget = autoEnabled ? options.getIntOption("loop_unroll_cost", policies.loop_unroll_cost) : 0; autoCfg.thisModule = thisModule.get(); autoCfg.budgetCache = &budgetCache; autoCfg.budgetExempt = &budgetExempt; @@ -3399,6 +3577,9 @@ namespace das { << " auto + " << patch.invokeBlocks << " invoke-block site(s), " << patch.declined << " declined in module " << thisModule->name << "\n"; } + if ( patch.logOpt && patch.logs && patch.unrolled ) { + *patch.logs << "UNROLL: " << patch.unrolled << " loop(s) in module " << thisModule->name << "\n"; + } return patch.changed; } diff --git a/src/ast/ast_inscope_pod.cpp b/src/ast/ast_inscope_pod.cpp index 1624757f1c..5c1c8a34a7 100644 --- a/src/ast/ast_inscope_pod.cpp +++ b/src/ast/ast_inscope_pod.cpp @@ -49,6 +49,15 @@ namespace das { return !elemT || !( elemT->isPointer() || elemT->isNoHeapType() ); } + // src/ast/ARCHITECTURE_LOOP_SOURCE.md#stack-loop-literal + ExprMakeArray * stackLoopLiteral ( Expression * source ) { + const uint64_t maxStackLiteralBytes = 1024; + auto mka = heapArrayLiteral(source); + if ( !mka || literalElementsOwnHeap(mka) ) return nullptr; + auto bytes = uint64_t(mka->values.size()) * mka->recordType->getSizeOf64(); + return bytes <= maxStackLiteralBytes ? mka : nullptr; + } + static bool canHoldArray ( const TypeDeclPtr & type ) { if ( type->ref || type->isPointer() || type->isGoodIteratorType() || type->isGoodLambdaType() || type->isGoodBlockType() ) return true; if ( type->isGoodArrayType() || type->isGoodTableType() ) { diff --git a/src/ast/ast_inscope_pod.h b/src/ast/ast_inscope_pod.h index ef2e041ff1..32859bc424 100644 --- a/src/ast/ast_inscope_pod.h +++ b/src/ast/ast_inscope_pod.h @@ -10,5 +10,6 @@ namespace das { string inScopePodSite ( const Function * func ); ExprMakeArray * heapArrayLiteral ( Expression * expr ); bool literalElementsOwnHeap ( const ExprMakeArray * literal ); + ExprMakeArray * stackLoopLiteral ( Expression * source ); } diff --git a/src/ast/ast_sink.cpp b/src/ast/ast_sink.cpp index a6ed05bb66..9a4cea4dff 100644 --- a/src/ast/ast_sink.cpp +++ b/src/ast/ast_sink.cpp @@ -5,6 +5,7 @@ #include "daScript/ast/ast_expressions.h" #include "ast_effects.h" +#include "ast_generate_typed.h" #include "ast_sink.h" namespace das { @@ -41,15 +42,93 @@ namespace das { return ( e && e->rtti_isBlock() ) ? static_cast(e) : nullptr; } + struct ForwardCandidate { + Expression * nextStatement = nullptr; + ExprVar * read = nullptr; + int total = 0; + bool forwardable = false; + }; + + bool siblingsArePure ( const vector & operands, Expression * child ) { + bool found = false; + for ( auto & operand : operands ) { + if ( operand==child ) found = true; + else if ( !droppable(operand) ) return false; + } + return found; + } + + // src/ast/ARCHITECTURE_EFFECTS.md#forward-read-once-let + bool evaluatesAfterPureSiblings ( Expression * parent, Expression * child ) { + if ( parent->rtti_isNullCoalescing() || parent->rtti_isSafeAt() ) return false; + if ( parent->rtti_isR2V() ) return static_cast(parent)->subexpr==child; + if ( parent->rtti_isCast() ) return static_cast(parent)->subexpr==child; + if ( parent->rtti_isPtr2Ref() ) return static_cast(parent)->subexpr==child; + if ( parent->rtti_isReturn() ) return static_cast(parent)->subexpr==child; + if ( parent->rtti_isOp1() ) return static_cast(parent)->subexpr==child; + if ( parent->rtti_isField() ) return static_cast(parent)->value==child; + if ( parent->rtti_isOp2() ) { + auto op = static_cast(parent); + if ( op->op=="&&" || op->op=="||" ) return false; + return siblingsArePure({op->left, op->right}, child); + } + if ( parent->rtti_isAt() ) { + auto at = static_cast(parent); + return siblingsArePure({at->subexpr, at->index}, child); + } + if ( parent->rtti_isCall() ) return siblingsArePure(static_cast(parent)->arguments, child); + if ( parent->rtti_isStringBuilder() ) { + return siblingsArePure(static_cast(parent)->elements, child); + } + if ( parent->rtti_isFor() ) return siblingsArePure(static_cast(parent)->sources, child); + if ( parent->rtti_isLet() ) { + auto let = static_cast(parent); + return let->variables.size()==1 && let->variables[0]->init==child; + } + if ( parent->rtti_isIfThenElse() ) return static_cast(parent)->cond==child; + return false; + } + + // src/ast/ARCHITECTURE_EFFECTS.md#forward-read-once-let + bool forwardableLet ( Expression * stmt ) { + if ( !sinkableLet(stmt) ) return false; + auto v = static_cast(stmt)->variables[0]; + if ( v->init_via_move || v->init_via_clone || !v->init->type || v->init->type->ref ) return false; + return v->type->isSameType(*v->init->type, RefMatters::no, ConstMatters::no, TemporaryMatters::no); + } + class SinkPureLets : public PassVisitor { public: using PassVisitor::PassVisitor; using PassVisitor::visit; using PassVisitor::preVisit; + TextWriter * logs = nullptr; + bool forwardEnabled = true; protected: das_hash_map candidates; das_hash_map arms; vector open; + das_hash_map forwards; + vector path; + bool forwarding = false; + virtual void preVisitExpression ( Expression * expr ) override { + PassVisitor::preVisitExpression(expr); + path.push_back(expr); + } + virtual ExpressionPtr visitExpression ( Expression * expr ) override { + path.pop_back(); + return PassVisitor::visitExpression(expr); + } + // src/ast/ARCHITECTURE_EFFECTS.md#forward-read-once-let + bool evaluatesAfterPureSiblingsFrom ( Expression * statement ) const { + size_t depth = path.size(); + while ( depth>0 && path[depth-1]!=statement ) depth --; + if ( depth==0 ) return false; + for ( size_t i=depth-1; i+1 pairedLet ( ExprBlock * block, size_t i ) { auto & list = block->list; @@ -71,6 +153,10 @@ namespace das { PassVisitor::preVisit(block); auto arm = arms.find(block); if ( arm!=arms.end() ) open.push_back(arm->second); + for ( size_t i=0; forwarding && i+1list.size(); ++i ) { + if ( !forwardableLet(block->list[i]) ) continue; + forwards[static_cast(block->list[i])->variables[0]].nextStatement = block->list[i+1]; + } for ( size_t i=0; ilist.size(); ++i ) { auto [var, ite] = pairedLet(block, i); if ( !var || ite->isStatic || !droppable(ite->cond) ) continue; @@ -83,6 +169,13 @@ namespace das { } virtual void preVisit ( ExprVar * expr ) override { PassVisitor::preVisit(expr); + auto fwd = forwards.find(expr->variable); + if ( fwd!=forwards.end() ) { + auto & f = fwd->second; + f.total ++; + f.read = expr; + f.forwardable = expr->r2v && !expr->write && evaluatesAfterPureSiblingsFrom(f.nextStatement); + } auto it = candidates.find(expr->variable); if ( it==candidates.end() ) return; auto & c = it->second; @@ -102,16 +195,36 @@ namespace das { if ( c.total==c.inFalse && c.inFalse ) return c.ifFalse; return nullptr; } + // src/ast/ARCHITECTURE_EFFECTS.md#forward-read-once-let + bool forwardLet ( ExprBlock * block, size_t i ) { + auto & list = block->list; + if ( i+1>=list.size() || !list[i]->rtti_isLet() ) return false; + auto let = static_cast(list[i]); + if ( let->variables.size()!=1 ) return false; + auto it = forwards.find(let->variables[0]); + if ( it==forwards.end() ) return false; + auto f = it->second; + forwards.erase(it); + if ( f.total!=1 || !f.forwardable || f.nextStatement!=list[i+1] ) return false; + ReplaceNode replace(f.read, let->variables[0]->init); + list[i+1] = list[i+1]->visit(replace); + if ( !replace.done ) return false; + if ( logs ) *logs << "FORWARD " << let->variables[0]->name << " at " << let->at.describe() << "\n"; + list.erase(list.begin() + i); + return true; + } 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(); + auto arm = var ? targetArm(var) : nullptr; + if ( arm ) { + arm->list.insert(arm->list.begin(), list[i]); + list.erase(list.begin() + i); + reportFolding(); + } else if ( forwardLet(block, i) ) { + reportFolding(); + } } if ( arms.erase(block) ) open.pop_back(); return PassVisitor::visit(block); @@ -122,6 +235,8 @@ namespace das { bool optimizationSink ( Program * program, int32_t round ) { if ( program->options.getBoolOption("disable_sink", program->policies.disable_sink) ) return false; SinkPureLets pass(round); + pass.forwardEnabled = !program->options.getBoolOption("disable_forward", program->policies.disable_forward); + if ( program->options.getBoolOption("log_optimization", program->policies.log_optimization) ) pass.logs = program->compileLog; program->visit(pass); return pass.didAnything(); } diff --git a/src/builtin/module_builtin_ast_serialize.cpp b/src/builtin/module_builtin_ast_serialize.cpp index f00cda2aef..df9449f88b 100644 --- a/src/builtin/module_builtin_ast_serialize.cpp +++ b/src/builtin/module_builtin_ast_serialize.cpp @@ -3111,7 +3111,7 @@ namespace das { 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_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(auto_inline_functions) X(auto_inline_cost) X(loop_unroll_cost) X(disable_forward) 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) \ X(jit_jit_all_functions) X(jit_debug_info) X(jit_opt_level) X(jit_size_level) X(jit_dll_mode) \ diff --git a/src/builtin/module_builtin_rtti.cpp b/src/builtin/module_builtin_rtti.cpp index d500555c54..2a62524d5d 100644 --- a/src/builtin/module_builtin_rtti.cpp +++ b/src/builtin/module_builtin_rtti.cpp @@ -1091,6 +1091,8 @@ namespace das { addField("max_framed_call_depth"); addField("keep_symbol_tables"); addField("compile_threads"); + addField("loop_unroll_cost"); + addField("disable_forward"); } virtual bool isLocal() const override { return true; } }; diff --git a/src/misc/daScriptC.cpp b/src/misc/daScriptC.cpp index f4a67c0ecf..979b4d11af 100644 --- a/src/misc/daScriptC.cpp +++ b/src/misc/daScriptC.cpp @@ -939,6 +939,7 @@ int das_policies_set_bool ( das_policies * policies, das_bool_policy flag, int v 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_FORWARD: p->disable_forward = 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; @@ -971,6 +972,7 @@ int das_policies_set_int ( das_policies * policies, das_int_policy field, int64_ case DAS_POLICY_MAX_UNRESERVED_SIZE: if ( value < 0 ) DAS_FATAL_ERROR("DAS_POLICY_MAX_UNRESERVED_SIZE must not be negative (%lld)\n", (long long)value); p->max_unreserved_size = uint64_t(value); break; + case DAS_POLICY_LOOP_UNROLL_COST: p->loop_unroll_cost = checked_i32(value, "DAS_POLICY_LOOP_UNROLL_COST"); break; default: return 0; } return 1; diff --git a/tests-cpp/small/test_policies_canary.cpp b/tests-cpp/small/test_policies_canary.cpp index 26f9276934..f1d4244eca 100644 --- a/tests-cpp/small/test_policies_canary.cpp +++ b/tests-cpp/small/test_policies_canary.cpp @@ -1,5 +1,6 @@ #include #include "daScript/daScript.h" +#include "daScript/daScriptC.h" using namespace das; @@ -26,3 +27,15 @@ TEST_CASE("CodeOfPolicies ABI canary") { bad.abi_stamp = good.abi_stamp ^ (4u << 8); // sizeof drift (one field added/removed) CHECK_FALSE(checkCodeOfPoliciesStamp(bad)); } + +TEST_CASE("the loop unroll and forward policies reach CodeOfPolicies through the C API") { + das_policies * pol = das_policies_make(); + auto policies = (CodeOfPolicies *) pol; + CHECK_EQ(policies->loop_unroll_cost, 8); + REQUIRE(das_policies_set_int(pol, DAS_POLICY_LOOP_UNROLL_COST, 0) == 1); + CHECK_EQ(policies->loop_unroll_cost, 0); + CHECK_FALSE(policies->disable_forward); + REQUIRE(das_policies_set_bool(pol, DAS_POLICY_DISABLE_FORWARD, 1) == 1); + CHECK(policies->disable_forward); + das_policies_release(pol); +} diff --git a/tests/aot/CMakeLists.txt b/tests/aot/CMakeLists.txt index 10c99c6177..930af05343 100644 --- a/tests/aot/CMakeLists.txt +++ b/tests/aot/CMakeLists.txt @@ -376,6 +376,7 @@ SET(AOT_OPTIMIZATION_MODULE_FILES tests/optimization/_inline_scope_helper.das tests/optimization/_inline_unoptimized_scope_helper.das tests/optimization/_inline_unsafe_helper.das + tests/optimization/_loop_unroll_off_helper.das tests/optimization/_never_inline_module.das tests/optimization/_optimized_body_helper.das ) diff --git a/tests/ast_match/test_comprehensions.das b/tests/ast_match/test_comprehensions.das index 97136a2a3a..7943c575a0 100644 --- a/tests/ast_match/test_comprehensions.das +++ b/tests/ast_match/test_comprehensions.das @@ -255,110 +255,6 @@ def test_local_function_not_lambda(t : T?) { } } -// ── Post-inference local function matching (ExprAddr fallback) ────────── - -[export] -def target_with_local_fn() { - let f = @@(x : int) { return x + 1; } - feint("{f}") -} - -[export] -def target_with_local_fn_wrong() { - let f = @@(x : int) { return x - 1; } - feint("{f}") -} - -[test(description = "a local function pattern matches the inferred form, an address-of expression, in a compiled function")] -def test_local_fn_post_inference(t : T?) { - ast_gc_guard() { - var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) - t |> success(func != null, "should find target_with_local_fn") - if (func == null) { - return - } - let r = qmatch_function(func) $() { - let f = @@(x : int) { return x + 1; } - feint("{f}") - } - t |> success(r.matched, "should match post-inference local function via ExprAddr") - } -} - -[test(description = "a local function pattern with a different body fails against the inferred form")] -def test_local_fn_post_inference_wrong_body(t : T?) { - ast_gc_guard() { - var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) - if (func == null) { - return - } - let r = qmatch_function(func) $() { - let f = @@(x : int) { return x - 1; } - feint("{f}") - } - t |> success(!r.matched, "wrong body in local function should fail") - } -} - -[test(description = "a $e capture binds the body statement of an inferred local function")] -def test_local_fn_capture_body(t : T?) { - ast_gc_guard() { - var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) - if (func == null) { - return - } - var body_expr : ExpressionPtr - let r = qmatch_function(func) $() { - let f = @@(x : int) { $e(body_expr); } - feint("{f}") - } - t |> success(r.matched, "should match with $e capture on local fn body") - if (r.matched) { - t |> equal(body_expr.__rtti, "ExprReturn") - } - } -} - -[export] -def target_with_local_fn_two_args() { - let f = @@(a : int; b : float) { return float(a) + b; } - feint("{f}") -} - -[test(description = "a local function pattern with two arguments matches the inferred form")] -def test_local_fn_match_two_args(t : T?) { - ast_gc_guard() { - var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn_two_args) - if (func == null) { - return - } - let r = qmatch_function(func) $() { - let f = @@(a : int; b : float) { return float(a) + b; } - feint("{f}") - } - t |> success(r.matched, "should match local fn with two args") - } -} - -[test(description = "an $i capture binds the name of the let variable holding an inferred local function")] -def test_local_fn_capture_var_name(t : T?) { - ast_gc_guard() { - var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) - if (func == null) { - return - } - var vname : string - let r = qmatch_function(func) $() { - let $i(vname) = @@(x : int) { return x + 1; } - feint("{f}") - } - t |> success(r.matched, "should match with $i capture on let variable name") - if (r.matched) { - t |> equal(vname, "f") - } - } -} - // ── Post-inference comprehension matching (ExprInvoke fallback) ───────── [export] diff --git a/tests/ast_match/test_local_function_post_inference.das b/tests/ast_match/test_local_function_post_inference.das new file mode 100644 index 0000000000..7dd75eeacd --- /dev/null +++ b/tests/ast_match/test_local_function_post_inference.das @@ -0,0 +1,116 @@ +options gen2 +options indenting = 4 +options rtti +options no_coverage +options disable_forward // each target pins a `let` that is read once +options _cyclomatic_complexity = 0 // qmatch patterns expand into matcher code + +require daslib/ast +require daslib/rtti +require daslib/ast_match +require daslib/ast_boost +require daslib/templates_boost +require dastest/testing_boost public + +[export] +def target_with_local_fn() { + let f = @@(x : int) { return x + 1; } + feint("{f}") +} + +[export] +def target_with_local_fn_wrong() { + let f = @@(x : int) { return x - 1; } + feint("{f}") +} + +[test(description = "a local function pattern matches the inferred form, an address-of expression, in a compiled function")] +def test_local_fn_post_inference(t : T?) { + ast_gc_guard() { + var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) + t |> success(func != null, "should find target_with_local_fn") + if (func == null) { + return + } + let r = qmatch_function(func) $() { + let f = @@(x : int) { return x + 1; } + feint("{f}") + } + t |> success(r.matched, "should match post-inference local function via ExprAddr") + } +} + +[test(description = "a local function pattern with a different body fails against the inferred form")] +def test_local_fn_post_inference_wrong_body(t : T?) { + ast_gc_guard() { + var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) + if (func == null) { + return + } + let r = qmatch_function(func) $() { + let f = @@(x : int) { return x - 1; } + feint("{f}") + } + t |> success(!r.matched, "wrong body in local function should fail") + } +} + +[test(description = "a $e capture binds the body statement of an inferred local function")] +def test_local_fn_capture_body(t : T?) { + ast_gc_guard() { + var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) + if (func == null) { + return + } + var body_expr : ExpressionPtr + let r = qmatch_function(func) $() { + let f = @@(x : int) { $e(body_expr); } + feint("{f}") + } + t |> success(r.matched, "should match with $e capture on local fn body") + if (r.matched) { + t |> equal(body_expr.__rtti, "ExprReturn") + } + } +} + +[export] +def target_with_local_fn_two_args() { + let f = @@(a : int; b : float) { return float(a) + b; } + feint("{f}") +} + +[test(description = "a local function pattern with two arguments matches the inferred form")] +def test_local_fn_match_two_args(t : T?) { + ast_gc_guard() { + var func = find_module_function_via_rtti(compiling_module(), + @@target_with_local_fn_two_args) + if (func == null) { + return + } + let r = qmatch_function(func) $() { + let f = @@(a : int; b : float) { return float(a) + b; } + feint("{f}") + } + t |> success(r.matched, "should match local fn with two args") + } +} + +[test(description = "an $i capture binds the name of the let variable holding an inferred local function")] +def test_local_fn_capture_var_name(t : T?) { + ast_gc_guard() { + var func = find_module_function_via_rtti(compiling_module(), @@target_with_local_fn) + if (func == null) { + return + } + var vname : string + let r = qmatch_function(func) $() { + let $i(vname) = @@(x : int) { return x + 1; } + feint("{f}") + } + t |> success(r.matched, "should match with $i capture on let variable name") + if (r.matched) { + t |> equal(vname, "f") + } + } +} diff --git a/tests/cuda/_cuda_common.das b/tests/cuda/_cuda_common.das index 7721cecda5..39da5c9774 100644 --- a/tests/cuda/_cuda_common.das +++ b/tests/cuda/_cuda_common.das @@ -1,5 +1,6 @@ options gen2 options indenting = 4 +options loop_unroll_cost = 0 // this fixture pins emitted loop text; unrolling would rewrite it // Shared fixture for the dasCUDA emitter suite (the tests/msl/_msl_common shape): the // [cuda_kernel] classes whose emitted text the shape, compile-gate, census and oracle tests diff --git a/tests/gc/test_stackwalk.das b/tests/gc/test_stackwalk.das index 75482a3d2d..0fa8329aca 100644 --- a/tests/gc/test_stackwalk.das +++ b/tests/gc/test_stackwalk.das @@ -164,16 +164,18 @@ def test_stackwalk_interval_fields(t : T?) { // an invoked block literal splices through the InvokeBlock tier, // whose manufactured scope wrapper holds the argument temps; a // one-source-line invoke gives that wrapper a degenerate range, and -// the temps must still gate live at parks inside the body +// the temps must still gate live at parks inside the body. the +// body reads its argument twice: a temp read once is forwarded +// into its reader [test(description = "the argument temp of a one-line invoked block literal is live at a park inside the body")] def test_stackwalk_invoke_block(t : T?) { t |> run("arg temp of a one-line invoked block is live at a body park") @(t : T?) { var w = new CollectingWalker() let seed = length(w.frames) + 7 - let r = invoke($(blkarg : string) : int { let n = walk_len(w, blkarg); return n + 1; }, + let r = invoke($(blkarg : string) : int { return walk_len(w, blkarg) + length(blkarg); }, "arg_{seed}") - t |> equal(r, length("arg_7") + 1) + t |> equal(r, length("arg_7") * 2) t |> success(has_live_local(w, "blkarg"), "the block argument temp must be live in the walk") unsafe { diff --git a/tests/msl/_msl_common.das b/tests/msl/_msl_common.das index 0a0bfa6c25..dccd6a56b6 100644 --- a/tests/msl/_msl_common.das +++ b/tests/msl/_msl_common.das @@ -1,5 +1,6 @@ options gen2 options indenting = 4 +options loop_unroll_cost = 0 // this fixture pins emitted loop text; unrolling would rewrite it // Shared fixture for the dasMetal MSL test suite (mirrors tests/spirv/_spirv_common.das): the // [metal_kernel] fixture classes whose emitted text the shape, golden, and census tests read, diff --git a/tests/optimization/_inline_generic_helper.das b/tests/optimization/_inline_generic_helper.das index e0d27ada3b..a39d232f13 100644 --- a/tests/optimization/_inline_generic_helper.das +++ b/tests/optimization/_inline_generic_helper.das @@ -41,3 +41,11 @@ def with_auto_inline_visibility_private_mid( invoke(blk, value) } } + +def public gloop_sum(a : auto(TT)) : TT { + var s = a + for (i in range(4)) { + s += TT(i) + } + return s +} diff --git a/tests/optimization/_inline_unoptimized_scope_helper.das b/tests/optimization/_inline_unoptimized_scope_helper.das index 65abdba86f..b85882489e 100644 --- a/tests/optimization/_inline_unoptimized_scope_helper.das +++ b/tests/optimization/_inline_unoptimized_scope_helper.das @@ -13,3 +13,13 @@ def scoped_unoptimized_value() : int { } return value } + +var public g_unoptimized_seed = 1 + +def public unoptimized_loop_sum() : int { + var s = g_unoptimized_seed + for (i in range(4)) { + s += i + } + return s +} diff --git a/tests/optimization/_loop_unroll_off_helper.das b/tests/optimization/_loop_unroll_off_helper.das new file mode 100644 index 0000000000..a850b59d32 --- /dev/null +++ b/tests/optimization/_loop_unroll_off_helper.das @@ -0,0 +1,14 @@ +options gen2 +options loop_unroll_cost = 0 + +module _loop_unroll_off_helper public + +var public g_unroll_off = 1 + +def public unroll_off_sum() : int { + var s = g_unroll_off + for (i in range(4)) { + s += i + } + return s +} diff --git a/tests/optimization/_optimized_body_helper.das b/tests/optimization/_optimized_body_helper.das index f977bfbd8b..07dd8fcdb9 100644 --- a/tests/optimization/_optimized_body_helper.das +++ b/tests/optimization/_optimized_body_helper.das @@ -2,6 +2,8 @@ options gen2 module _optimized_body_helper public +require daslib/ast +require daslib/rtti require daslib/ast_boost require dastest/testing_boost require strings @@ -20,3 +22,28 @@ def public body_of(t : T?; nm : string) : string { let clean <- [for (ln in split(body, "\n")); ln; where find(ln, "coverage(") < 0] return join(clean, "\n") } + +def public body_of_module(t : T?; mod, nm : string) : string { + //! the optimized body of function `nm` of required module `mod` + var body = "" + find_module(this_program(), mod) |> for_each_function(nm) $(func) { + if (empty(body)) { + body = "{describe(func.body)}" + } + } + t |> success(!empty(body), "function {nm} of module {mod} found") + return body +} + +def public instance_body_of(t : T?; nm : string) : string { + //! the body of the generic instance whose name holds `nm` + var body = "" + compiling_module() |> for_each_function("") $(func) { + if (empty(body) && find("{func.name}", nm) >= 0) { + body = "{describe(func.body)}" + } + } + t |> success(!empty(body), "instance not found") + let clean <- [for (ln in split(body, "\n")); ln; where find(ln, "coverage(") < 0] + return join(clean, "\n") +} diff --git a/tests/optimization/optimization_auto_inline_functions.das b/tests/optimization/optimization_auto_inline_functions.das index 8be58484d7..9720940628 100644 --- a/tests/optimization/optimization_auto_inline_functions.das +++ b/tests/optimization/optimization_auto_inline_functions.das @@ -831,3 +831,18 @@ def test_auto_inline_writable_ref_args_behavior(t : T?) { delete o } } + +var g_loop_seed = 1 + +[export] +def target_foreign_generic_loop() : int => gloop_sum(g_loop_seed) + +[test(description = "a loop of known passes in an instance of another module's generic stays a loop")] +def test_foreign_generic_instance_keeps_its_loop(t : T?) { + ast_gc_guard() { + let b = instance_body_of(t, "gloop_sum") + t |> success(has(b, "for ("), "kept: {b}") + } + g_loop_seed = 1 + t |> equal(target_foreign_generic_loop(), 7) +} diff --git a/tests/optimization/optimization_inline.das b/tests/optimization/optimization_inline.das index 59b5e6217b..6d39efaea9 100644 --- a/tests/optimization/optimization_inline.das +++ b/tests/optimization/optimization_inline.das @@ -1,6 +1,7 @@ options gen2 options rtti options no_coverage +options disable_forward // this file pins inliner shapes; forwarding would rewrite them require daslib/ast require daslib/rtti @@ -12,8 +13,9 @@ require _optimized_body_helper require _inline_counter_helper require _never_inline_module require _inline_scope_helper -require _inline_unoptimized_scope_helper // nolint:STYLE030 call inlined +require _inline_unoptimized_scope_helper require _inline_unsafe_helper +require _loop_unroll_off_helper // structural FIRED proof + behavioral safety net for [inline] splicing // (src/ast/ast_inline.cpp): every direct call to an [inline] function is replaced @@ -561,19 +563,6 @@ def target_canon() : int { } } -// a generic instance carries a mangled name (origin`name`hash) the exact-name -// for_each_function lookup misses - match by substring instead -def instance_body_of(t : T?; nm : string) : string { - var body = "" - compiling_module() |> for_each_function("") $(func) { - if (empty(body) && find("{func.name}", nm) >= 0) { - body = "{describe(func.body)}" - } - } - t |> success(!empty(body), "instance not found") - let clean <- [for (ln in split(body, "\n")); ln; where !(ln |> has("coverage("))] - return join(clean, "\n") -} [test(description = "calls into a never_inline module stay calls in every inline tier while the pass stays live elsewhere, and the module's neverInline flag is rtti-visible")] def test_never_inline_module(t : T?) { @@ -598,12 +587,7 @@ def test_never_inline_module(t : T?) { t |> success(!has(b, "nvm_step("), "[inline] splice fired: {b}") } t |> run("the pass skips the module's own bodies") @(t : T?) { - var body = "" - find_module(this_program(), "_never_inline_module") |> for_each_function("nvm_chain") $(func) { - if (empty(body)) { - body = "{describe(func.body)}" - } - } + let body = body_of_module(t, "_never_inline_module", "nvm_chain") t |> success(has(body, "nvm_add("), "internal [inline] call survives: {body}") } t |> run("flagged-origin instance skips return canonicalization") @(t : T?) { @@ -1318,3 +1302,575 @@ def test_inline_global_read_argument(t : T?) { t |> equal(target_global_read_for_writing_callee(), 6, "read before the callee wrote it") t |> equal(g_scale, 100) } + +var g_unroll = 1 + +def unroll_bump() : int { + g_unroll ++ + return g_unroll +} + +[export] +def target_unroll_range() : int { + var s = g_unroll + for (i in range(4)) { + s += i + } + return s +} + +[export] +def target_unroll_literal() : int { + var s = g_unroll + for (x in [10, 20, 30, 40]) { + s += x + } + return s +} + +[export] +def target_unroll_fixed_array(a : int[4]) : int { + var s = g_unroll + for (x in a) { + s += x + } + return s +} + +[export] +def target_unroll_writes_fixed_array(var a : int[3]) { + for (x in a) { + x += g_unroll + } +} + +[export] +def target_unroll_no_pass() : int { + var s = g_unroll + for (i in range(0)) { + s += i + } + return s +} + +[export] +def target_unroll_one_pass() : int { + var s = g_unroll + for (i in range(1)) { + s += i + s *= 3 + s-- + s += g_unroll + s *= 5 + s -= 2 + s += g_unroll + s *= 7 + s -= 3 + } + return s +} + +[export] +def target_unroll_two_statements() : int { + var s = g_unroll + for (i in range(4)) { + s += i + s *= 2 + } + return s +} + +[export] +def target_unroll_nested() : int { + var s = g_unroll + for (i in range(2)) { + for (j in range(2)) { + s += i * 10 + j + } + } + return s +} + +[export] +def target_unroll_urange() : int { + var s = g_unroll + for (i in urange(0u, 4u)) { + s += int(i) + } + return s +} + +[export] +def target_unroll_range64() : int { + var s = g_unroll + for (i in range64(0l, 4l)) { + s += int(i) + } + return s +} + +[export] +def target_unroll_urange64() : int { + var s = g_unroll + for (i in urange64(0ul, 4ul)) { + s += int(i) + } + return s +} + +[export] +def target_unroll_annotation() : int { + var s = g_unroll + for [unroll] (i in range(9)) { + s += i + } + return s +} + +[export] +def target_unroll_keep_over_budget() : int { + var s = g_unroll + for (i in range(5)) { + s += i + s *= 2 + } + return s +} + +[export] +def target_unroll_keep_one_statement_over_budget() : int { + var s = g_unroll + for (i in range(9)) { + s += i + } + return s +} + +[export] +def target_unroll_keep_disabled() : int { + var s = g_unroll + for [unroll_disable] (i in range(4)) { + s += i + } + return s +} + +[export] +def target_unroll_keep_break() : int { + var s = g_unroll + for (i in range(2)) { + break if (s > 100) + s += i + } + return s +} + +[export] +def target_unroll_keep_unknown_count(n : int) : int { + var s = g_unroll + for (i in range(n)) { + s += i + } + return s +} + +[export] +def target_unroll_keep_finally() : int { + var s = g_unroll + for (i in range(3)) { + s += i + } finally { + s *= 2 + } + return s +} + +[export, never_inline] +def reference_loop_with_finally() : int { + var s = g_unroll + for (i in range(3)) { + s += i + } finally { + s *= 2 + } + return s +} + +[export] +def target_unroll_keep_two_sources() : int { + var s = g_unroll + for (i, x in range(3), [10, 20, 30]) { + s += i * x + } + return s +} + +[export] +def target_unroll_keep_written_variable() : int { + var s = g_unroll + for (x in [1, 2, 3]) { + x *= 2 + s += x + } + return s +} + +[never_inline] +def unroll_peek(a : int&) : int => a + g_unroll + +[export] +def target_unroll_keep_reference_argument() : int { + var s = g_unroll + for (x in [1, 2, 3]) { + s += unroll_peek(x) + } + return s +} + +[export, never_inline] +def target_unroll_keep_annotated() : int { + var s = g_unroll + for (i in range(4)) { + s += i + } + return s +} + +[inline] +def sum_all(a : array) : int { + var s = 0 + for (x in a) { + s += x + } + return s +} + +[inline] +def sum_and_length(a : array) : int { + var s = length(a) + for (x in a) { + s += x + } + return s +} + +[inline] +def sum_twice(a : array; n : int) : int { + var s = 0 + for (_ in range(n)) { + for (x in a) { + s += x + } + } + return s +} + +[inline] +def write_then_sum(var n : int&; a : array) : int { + n = 100 + var s = 0 + for (x in a) { + s += x + } + return s +} + +[inline] +def first_plus_one(a : array) : int => a[0] + 1 + +[export] +def target_literal_source_keep_callee_write() : int { + var k = g_unroll + return write_then_sum(k, [k, 2]) +} + +[export] +def target_literal_argument_indexed() : int { + return first_plus_one([g_unroll, 2]) +} + +[export] +def target_literal_source() : int { + return sum_all([g_unroll, 2, 3, 4]) +} + +[export] +def target_literal_source_constants() : int { + return sum_all([1, 2, 3, 4]) + g_unroll +} + +[export] +def target_literal_source_keep_two_reads() : int { + return sum_and_length([g_unroll, 2, 3, 4]) +} + +[export] +def target_literal_source_keep_under_loop(n : int) : int { + return sum_twice([g_unroll, 2, 3, 4], n) +} + +[export] +def target_literal_source_keep_effect() : int { + return sum_all([unroll_bump(), 2, 3, 4]) +} + +[inline] +def scaled_sum(a, b : int) : int { + var s = a * 2 + s += b + return s + g_unroll +} + +[inline] +def scaled_sum_early(a, b : int) : int { + if (a < 0) return 0 + var s = a * 2 + s += b + return s + g_unroll +} + +[inline] +def scaled_sum_unsafe(a, b : int) : int { + var s = a * 2 + var p = unsafe(addr(s)) + *p += b + return s + g_unroll +} + +[export] +def target_trailing_return(x : int) : int { + return scaled_sum(x, 3) * 5 +} + +[export] +def target_trailing_return_keep_early(x : int) : int { + return scaled_sum_early(x, 3) * 5 +} + +[export] +def target_trailing_return_keep_unsafe(x : int) : int { + return scaled_sum_unsafe(x, 3) * 5 +} + +def has_loop(body : string) : bool => has(body, "for (") || has(body, "for [") + +[test(description = "a for loop over a constant range, an array literal of constants or a fixed array becomes one copy of its body a pass while passes times body statements fits loop_unroll_cost; a loop of one pass or under [unroll] always does, and a loop of no passes goes away")] +def test_loop_unroll_fired(t : T?) { + ast_gc_guard() { + t |> run("four passes of one statement over a constant range") @(t : T?) { + let b = body_of(t, "target_unroll_range") + t |> success(!has_loop(b), "unrolled: {b}") + t |> equal(count_of(b, "s +="), 4, "one copy a pass: {b}") + } + t |> run("an array literal of constants") @(t : T?) { + let b = body_of(t, "target_unroll_literal") + t |> success(!has_loop(b), "unrolled: {b}") + t |> success(has(b, "40"), "the last element is its own pass: {b}") + } + t |> run("a fixed array reads its elements by index") @(t : T?) { + let b = body_of(t, "target_unroll_fixed_array") + t |> success(!has_loop(b) && has(b, "a[3]"), "unrolled: {b}") + } + t |> run("a body that writes the elements of a fixed array") @(t : T?) { + let b = body_of(t, "target_unroll_writes_fixed_array") + t |> success(!has_loop(b) && has(b, "a[2]"), "unrolled: {b}") + } + t |> run("a loop of no passes goes away") @(t : T?) { + let b = body_of(t, "target_unroll_no_pass") + t |> success(!has_loop(b) && !has(b, "s +="), "no loop and no body: {b}") + } + t |> run("a loop of one pass unrolls whatever its body costs") @(t : T?) { + let b = body_of(t, "target_unroll_one_pass") + t |> success(!has_loop(b), "unrolled: {b}") + } + t |> run("four passes of two statements is the budget of 8") @(t : T?) { + let b = body_of(t, "target_unroll_two_statements") + t |> success(!has_loop(b), "unrolled: {b}") + t |> equal(count_of(b, "s *="), 4, "one copy a pass: {b}") + } + t |> run("an inner loop unrolls first, then the loop that holds it") @(t : T?) { + let b = body_of(t, "target_unroll_nested") + t |> success(!has_loop(b), "both unrolled: {b}") + t |> equal(count_of(b, "s +="), 4, "two by two passes: {b}") + } + t |> run("urange, range64 and urange64 sources") @(t : T?) { + for (name in ["target_unroll_urange", "target_unroll_range64", + "target_unroll_urange64"]) { + let b = body_of(t, name) + t |> success(!has_loop(b), "{name} unrolled: {b}") + t |> equal(count_of(b, "s +="), 4, "{name}, one copy a pass: {b}") + } + } + t |> run("[unroll] lifts the budget") @(t : T?) { + let b = body_of(t, "target_unroll_annotation") + t |> success(!has_loop(b), "unrolled: {b}") + t |> equal(count_of(b, "s +="), 9, "one copy a pass: {b}") + } + } +} + +[test(description = "a loop stays a loop when passes times statements is over the budget, under [unroll_disable], with a break or a finally in its body, with two sources, with a pass count not known at compile time, when the body writes a constant value or passes it by reference, in a function that carries an annotation, in a module with loop_unroll_cost = 0, and in a module compiled with optimize = false")] +def test_loop_unroll_keeps(t : T?) { + ast_gc_guard() { + t |> run("five passes of two statements is over the budget") @(t : T?) { + let b = body_of(t, "target_unroll_keep_over_budget") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("nine passes of one statement is over the budget") @(t : T?) { + let b = body_of(t, "target_unroll_keep_one_statement_over_budget") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("[unroll_disable] keeps the loop") @(t : T?) { + let b = body_of(t, "target_unroll_keep_disabled") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a body with a break") @(t : T?) { + let b = body_of(t, "target_unroll_keep_break") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a pass count the compiler does not know") @(t : T?) { + let b = body_of(t, "target_unroll_keep_unknown_count") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a body with a finally") @(t : T?) { + let b = body_of(t, "target_unroll_keep_finally") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("two sources") @(t : T?) { + let b = body_of(t, "target_unroll_keep_two_sources") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a body that writes the loop variable of a literal") @(t : T?) { + let b = body_of(t, "target_unroll_keep_written_variable") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a body that passes the loop variable of a literal by reference") @(t : T?) { + let b = body_of(t, "target_unroll_keep_reference_argument") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a function that carries an annotation") @(t : T?) { + let b = body_of(t, "target_unroll_keep_annotated") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a module with loop_unroll_cost = 0") @(t : T?) { + let b = body_of_module(t, "_loop_unroll_off_helper", "unroll_off_sum") + t |> success(has_loop(b), "kept: {b}") + } + t |> run("a module compiled with optimize = false") @(t : T?) { + let b = body_of_module(t, "_inline_unoptimized_scope_helper", "unoptimized_loop_sum") + t |> success(has_loop(b), "kept: {b}") + } + } +} + +[test(description = "unrolled loops and the loops that stayed compute what the loops computed, and an unrolled loop over a fixed array writes its elements")] +def test_loop_unroll_behavior(t : T?) { + g_unroll = 1 + t |> equal(target_unroll_range(), 7) + t |> equal(target_unroll_literal(), 101) + t |> equal(target_unroll_fixed_array(fixed_array(1, 2, 3, 4)), 11) + var cells = fixed_array(10, 20, 30) + target_unroll_writes_fixed_array(cells) + t |> equal(cells[0] + cells[1] + cells[2], 63) + t |> equal(target_unroll_no_pass(), 1) + t |> equal(target_unroll_one_pass(), 95) + t |> equal(target_unroll_two_statements(), 38) + t |> equal(target_unroll_nested(), 23) + t |> equal(target_unroll_annotation(), 37) + t |> equal(target_unroll_urange(), 7) + t |> equal(target_unroll_range64(), 7) + t |> equal(target_unroll_urange64(), 7) + t |> equal(target_unroll_keep_finally(), reference_loop_with_finally(), + "the finally still runs") + t |> equal(target_unroll_keep_two_sources(), 81) + t |> equal(target_unroll_keep_written_variable(), 13) + t |> equal(target_unroll_keep_over_budget(), 84) + t |> equal(target_unroll_keep_one_statement_over_budget(), 37) + t |> equal(target_unroll_keep_disabled(), 7) + t |> equal(target_unroll_keep_break(), 2) + t |> equal(target_unroll_keep_unknown_count(5), 11) + t |> equal(target_unroll_keep_reference_argument(), 10) + t |> equal(target_unroll_keep_annotated(), 7) + t |> equal(unroll_off_sum(), 7) + t |> equal(unoptimized_loop_sum(), 7) +} + +[test(description = "an array literal given to a parameter the body reads once, as a loop source, becomes that loop's source with no array local, and unrolls when its elements are constants; a parameter read twice or under another loop, an element with an effect, and an element the callee writes first bind the array")] +def test_inline_literal_loop_source(t : T?) { + ast_gc_guard() { + t |> run("the literal is the loop source") @(t : T?) { + let b = body_of(t, "target_literal_source") + t |> success(!has(b, "_arg_a") && has_loop(b), "no array local: {b}") + } + t |> run("a literal of constants unrolls") @(t : T?) { + let b = body_of(t, "target_literal_source_constants") + t |> success(!has(b, "_arg_a") && !has_loop(b), "no array local and no loop: {b}") + } + t |> run("a parameter read twice binds the array") @(t : T?) { + let b = body_of(t, "target_literal_source_keep_two_reads") + t |> success(has(b, "_arg_a"), "array local: {b}") + } + t |> run("a loop source under another loop binds the array") @(t : T?) { + let b = body_of(t, "target_literal_source_keep_under_loop") + t |> success(has(b, "_arg_a"), "array local: {b}") + } + t |> run("an element with an effect binds the array") @(t : T?) { + let b = body_of(t, "target_literal_source_keep_effect") + t |> success(has(b, "_arg_a"), "array local: {b}") + } + t |> run("an element the callee writes before the loop binds the array") @(t : T?) { + let b = body_of(t, "target_literal_source_keep_callee_write") + t |> success(has(b, "_arg_a"), "array local: {b}") + } + } + g_unroll = 1 + t |> equal(target_literal_source_keep_callee_write(), 3, + "the literal read k before the callee wrote it") + t |> equal(target_literal_argument_indexed(), 2, + "a parameter read once by index keeps its array") + t |> equal(target_literal_source(), 10) + t |> equal(target_literal_source_constants(), 11) + t |> equal(target_literal_source_keep_two_reads(), 14) + t |> equal(target_literal_source_keep_under_loop(2), 20) + t |> equal(target_literal_source_keep_effect(), 11) + t |> equal(g_unroll, 2, "the element's effect ran once") +} + +[test(description = "a callee body of several statements that ends in its one return splices with no result local: its statements go in front and the returned expression replaces the call; a body with an early return or an unsafe block keeps its result local")] +def test_inline_trailing_return(t : T?) { + ast_gc_guard() { + t |> run("the returned expression replaces the call") @(t : T?) { + let b = body_of(t, "target_trailing_return") + t |> success(!has(b, "scaled_sum(") && !has(b, "_res:"), "no result local: {b}") + } + t |> run("an early return keeps the result local") @(t : T?) { + let b = body_of(t, "target_trailing_return_keep_early") + t |> success(!has(b, "scaled_sum_early(") && has(b, "_res:"), "result local: {b}") + } + t |> run("an unsafe body keeps the result local") @(t : T?) { + let b = body_of(t, "target_trailing_return_keep_unsafe") + t |> success(!has(b, "scaled_sum_unsafe(") && has(b, "_res:"), "result local: {b}") + } + } + g_unroll = 1 + t |> equal(target_trailing_return(4), 60) + t |> equal(target_trailing_return_keep_early(4), 60) + t |> equal(target_trailing_return_keep_early(-4), 0) + t |> equal(target_trailing_return_keep_unsafe(4), 60) +} + +[export] +def target_forward_off_keeps_local(a : int) : int { + let tripled = a * 3 + g_unroll + return tripled + 1 +} + +[test(description = "under options disable_forward a pure local read once in the next statement stays a local")] +def test_disable_forward_keeps_a_read_once_local(t : T?) { + ast_gc_guard() { + let b = body_of(t, "target_forward_off_keeps_local") + t |> success(has(b, "tripled"), "kept: {b}") + } + g_unroll = 1 + t |> equal(target_forward_off_keeps_local(2), 8) +} diff --git a/tests/optimization/optimization_sink.das b/tests/optimization/optimization_sink.das index 10585a9676..0ab1aa9617 100644 --- a/tests/optimization/optimization_sink.das +++ b/tests/optimization/optimization_sink.das @@ -97,27 +97,106 @@ def target_keep_used_after(x : int) : string { return message } -//! the local ending in `name` is declared in the body's first `if` -def private let_inside_if(body, name : string) : bool { +[export] +def target_forward_statement(x : int) : int { + let tripled = x * 3 + g_count += tripled + return g_count +} + +[export] +def target_forward_return(a, b : int) : int { + let product = a * b + 1 + return product +} + +[export] +def target_forward_condition(a, b : int) : int { + let bigger = a > b + if (bigger) { + g_count ++ + } + return g_count +} + +[export] +def target_forward_chain(a : int) : int { + let first = a + 1 + let second = first * 2 + return second +} + +[export] +def target_forward_keep_two_reads(a : int) : int { + let tripled = a * 3 + return tripled + tripled +} + +[export] +def target_forward_keep_effect_first() : int { + let tripled = g_count * 3 + return bump() + tripled +} + +[export] +def target_forward_keep_conditional(a, b : int) : bool { + let over = a * 3 > b + return a > 0 && over +} + +[export] +def target_forward_keep_raising(arr : array; i : int) : int { + let item = arr[i] + return item + 1 +} + +struct Extent { + w : int + h : int +} + +struct Panel { + size : Extent +} + +[export] +def target_forward_keep_struct_copy(p : Panel) : int { + let copied = p.size + return copied.w + 1 +} + +[export, never_inline] +def target_forward_keep_annotated(a : int) : int { + let tripled = a * 3 + return tripled + 1 +} + +def private built_inside_if(body, text : string) : bool { + let at_if = find(body, "if (") + return at_if >= 0 && find(body, text) > at_if +} + +//! the local ending in `name` is declared outside the first `if` +def private let_before_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 + return at_let >= 0 && (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")] +[test(description = "a pure local read only in one branch of the `if` that follows it is built inside 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 |> success(built_inside_if(b, "is negative"), "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 |> success(built_inside_if(b, "is negative"), "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}") + t |> success(built_inside_if(b, "is off the 32 lattice"), "sunk: {b}") } } } @@ -127,23 +206,23 @@ 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 |> success(let_before_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 |> success(let_before_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 |> success(let_before_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 |> success(let_before_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}") + t |> success(let_before_if(b, "message"), "kept: {b}") } } } @@ -166,3 +245,74 @@ def test_sink_behavior(t : T?) { } t |> equal(string_heap_bytes_allocated(), s0, "no message built for a passing check") } + +[test(description = "a pure local read once in the statement that follows it gives way to its initializer: under a plain statement, a `return`, an `if` condition, and through a chain of two locals")] +def test_forward_replaces(t : T?) { + ast_gc_guard() { + t |> run("a read in the next statement takes the initializer") @(t : T?) { + let b = body_of(t, "target_forward_statement") + t |> success(find(b, "tripled") < 0, "forwarded: {b}") + } + t |> run("a returned local is the returned expression") @(t : T?) { + let b = body_of(t, "target_forward_return") + t |> success(find(b, "product") < 0, "forwarded: {b}") + } + t |> run("a local read in the condition of the next `if` moves into it") @(t : T?) { + let b = body_of(t, "target_forward_condition") + t |> success(find(b, "bigger") < 0, "forwarded: {b}") + } + t |> run("a local that feeds the next local goes with it") @(t : T?) { + let b = body_of(t, "target_forward_chain") + t |> success(find(b, "first") < 0 && find(b, "second") < 0, "forwarded: {b}") + } + } +} + +[test(description = "a local stays when it is read twice, when a call with an effect runs before the read, when the read is under `&&`, when its initializer may raise, when it is a struct copied out of a field, and in a function that carries an annotation")] +def test_forward_keeps(t : T?) { + ast_gc_guard() { + t |> run("a local read twice stays") @(t : T?) { + let b = body_of(t, "target_forward_keep_two_reads") + t |> success(find(b, "tripled:") >= 0, "kept: {b}") + } + t |> run("a call with an effect in front of the read keeps the local") @(t : T?) { + let b = body_of(t, "target_forward_keep_effect_first") + t |> success(find(b, "tripled:") >= 0, "kept: {b}") + } + t |> run("a read on the right of `&&` keeps the local") @(t : T?) { + let b = body_of(t, "target_forward_keep_conditional") + t |> success(find(b, "over:") >= 0, "kept: {b}") + } + t |> run("an initializer that may raise stays") @(t : T?) { + let b = body_of(t, "target_forward_keep_raising") + t |> success(find(b, "item:") >= 0, "kept: {b}") + } + t |> run("a struct copied out of a field stays a local") @(t : T?) { + let b = body_of(t, "target_forward_keep_struct_copy") + t |> success(find(b, "copied:") >= 0, "kept: {b}") + } + t |> run("a function that carries an annotation keeps its locals") @(t : T?) { + let b = body_of(t, "target_forward_keep_annotated") + t |> success(find(b, "tripled:") >= 0, "kept: {b}") + } + } +} + +[test(description = "functions whose read-once local was forwarded, and the ones that kept it, return the same values and run each effect once")] +def test_forward_behavior(t : T?) { + g_count = 0 + t |> equal(target_forward_statement(2), 6) + t |> equal(target_forward_return(3, 4), 13) + t |> equal(target_forward_condition(5, 2), 7) + t |> equal(target_forward_condition(1, 2), 7) + t |> equal(target_forward_chain(4), 10) + t |> equal(target_forward_keep_two_reads(2), 12) + g_count = 2 + t |> equal(target_forward_keep_effect_first(), 9, "the local is read before the bump") + t |> success(target_forward_keep_conditional(2, 5)) + t |> success(!target_forward_keep_conditional(-1, -9)) + let arr <- [10, 20, 30] + t |> equal(target_forward_keep_raising(arr, 1), 21) + t |> equal(target_forward_keep_struct_copy(Panel(size = Extent(w = 4, h = 5))), 5) + t |> equal(target_forward_keep_annotated(2), 7) +} diff --git a/tests/optimization/uncategorized_disable_auto_inline_rtti.das b/tests/optimization/uncategorized_disable_auto_inline_rtti.das index fb32c8fb15..8023061143 100644 --- a/tests/optimization/uncategorized_disable_auto_inline_rtti.das +++ b/tests/optimization/uncategorized_disable_auto_inline_rtti.das @@ -445,3 +445,24 @@ def test_dead_stores_behavior(t : T?) { t |> equal(s.pos.x, 80) } } + +var g_loop_seed = 1 + +[export] +def target_loop_without_auto_inline() : int { + var s = g_loop_seed + for (i in range(4)) { + s += i + } + return s +} + +[test(description = "a loop of known passes stays a loop under options disable_auto_inline")] +def test_loop_stays_without_auto_inline(t : T?) { + ast_gc_guard() { + let b = body_of(t, "target_loop_without_auto_inline") + t |> success(has(b, "for ("), "kept: {b}") + } + g_loop_seed = 1 + t |> equal(target_loop_without_auto_inline(), 7) +} diff --git a/tests/spirv/_spirv_common.das b/tests/spirv/_spirv_common.das index 4bf56584e2..a072a4425a 100644 --- a/tests/spirv/_spirv_common.das +++ b/tests/spirv/_spirv_common.das @@ -1,5 +1,6 @@ options gen2 options indenting = 4 +options loop_unroll_cost = 0 // this fixture pins emitted loop shape; unrolling would rewrite it options no_unused_block_arguments = false options no_unused_function_arguments = false diff --git a/utils/mcp/subtools/compile_check.das b/utils/mcp/subtools/compile_check.das index 2bc4d001db..168045eed1 100644 --- a/utils/mcp/subtools/compile_check.das +++ b/utils/mcp/subtools/compile_check.das @@ -47,6 +47,8 @@ def private compile_check_single_json(file : string; project : string = "") : Co cop.threadlock_context = true cop.ignore_shared_modules = true cop.auto_inline_functions = false // diagnostics describe the SOURCE (matches tools/common.das) + cop.loop_unroll_cost = 0 + cop.disable_forward = true compile_file(file, access, unsafe(addr(mg)), cop) $(ok; program; issues) { if (!ok) { result.errors = string(issues) diff --git a/utils/mcp/tools/common.das b/utils/mcp/tools/common.das index 05ee07987c..b335849f62 100644 --- a/utils/mcp/tools/common.das +++ b/utils/mcp/tools/common.das @@ -183,9 +183,7 @@ def compile_and_simulate_ctx(file : string; project : string = ""; blk : block<( var had_error = false using() $(var mg : ModuleGroup) { using() $(var cop : CodeOfPolicies) { - cop.threadlock_context = true - cop.ignore_shared_modules = true - cop.auto_inline_functions = false // introspection describes the SOURCE - splices rewrite bodies/references + setup_introspection_policies(cop, false, false) cop.keep_symbol_tables = true // blk reads is_used / function_index compile_file(file, access, unsafe(addr(mg)), cop) $(ok; program; issues) { if (!ok) { @@ -239,12 +237,15 @@ def compile_program(file : string; _export_all : bool; _no_opt : bool; project : return make_tool_result(result, had_error) } -// policies every introspection compile shares. auto_inline_functions stays off because these -// tools describe the SOURCE and splices rewrite bodies and references. +// policies every introspection compile shares. auto_inline_functions, +// the loop unroll and the local forward stay off: these tools +// describe the SOURCE, and all three rewrite it. def private setup_introspection_policies(var cop : CodeOfPolicies; _export_all, _no_opt : bool) : void { cop.threadlock_context = true cop.ignore_shared_modules = true cop.auto_inline_functions = false + cop.loop_unroll_cost = 0 + cop.disable_forward = true if (_export_all) { cop.export_all = true } From 39472e7bb74f9cb33f4cd81c26a014545deb8741 Mon Sep 17 00:00:00 2001 From: Boris Batkin Date: Fri, 27 Nov 2026 18:31:12 -0800 Subject: [PATCH 3/3] dasLLAMA: kernel sources turn loop unroll and the forward off A kernel body is lowered by a shader emitter and never runs in the interpreter, so unrolling its loops and forwarding its locals buys no time and only changes the code the emitter writes. The annotation gate does not reach a helper method or a free function a kernel calls, so each file that holds kernel code sets loop_unroll_cost = 0 and disable_forward: the 26 files with kernel entry points, the shared kernel bodies, the GPU math helpers and the Metal subgroup helpers. The sink pass stays on in them, as it is on master. Co-Authored-By: Claude Fable 5.2 --- modules/dasLLAMA/benchmarks/attn/bench_metal_pf_fused_attn.das | 2 ++ modules/dasLLAMA/benchmarks/attn/bench_metal_sq_attn.das | 2 ++ modules/dasLLAMA/benchmarks/ew/bench_metal_gk_rows.das | 2 ++ modules/dasLLAMA/benchmarks/matmul/bench_metal_gemm_kernels.das | 2 ++ modules/dasLLAMA/benchmarks/matmul/bench_metal_gemv_kernels.das | 2 ++ modules/dasLLAMA/benchmarks/matmul/bench_metal_kq_mm_lab.das | 2 ++ modules/dasLLAMA/benchmarks/matmul/bench_metal_moe_lab.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_asr.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_blocks.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_dflash.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_front.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_rows.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_cuda_classes_tts.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_gpu_kernels_common.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_gpu_kernels_discrete.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_gpu_math.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_classes_tts.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_dflash.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_gemm.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_kernels.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_nmt.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_prefill.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_metal_rail.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_vulkan_classes.das | 2 ++ modules/dasLLAMA/dasllama/dasllama_vulkan_classes_dflash.das | 2 ++ modules/dasLLAMA/harness/vk_gemm_probe.das | 2 ++ modules/dasLLAMA/harness/vk_gemv_probe.das | 2 ++ modules/dasLLAMA/harness/vk_gk_rows_probe.das | 2 ++ modules/dasLLAMA/performance/coopmat_mulmm_port.das | 2 ++ 30 files changed, 60 insertions(+) diff --git a/modules/dasLLAMA/benchmarks/attn/bench_metal_pf_fused_attn.das b/modules/dasLLAMA/benchmarks/attn/bench_metal_pf_fused_attn.das index b64bfe960d..b1d43af478 100644 --- a/modules/dasLLAMA/benchmarks/attn/bench_metal_pf_fused_attn.das +++ b/modules/dasLLAMA/benchmarks/attn/bench_metal_pf_fused_attn.das @@ -1,5 +1,7 @@ options gen2 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward // Fused prefill attention lab (M5 NAX arc phase 1): ONE kernel per (32-query block, head) // walking K/V in 32-position tiles — scores live in threadgroup scratch (never DRAM), diff --git a/modules/dasLLAMA/benchmarks/attn/bench_metal_sq_attn.das b/modules/dasLLAMA/benchmarks/attn/bench_metal_sq_attn.das index 854aca7f75..9954110935 100644 --- a/modules/dasLLAMA/benchmarks/attn/bench_metal_sq_attn.das +++ b/modules/dasLLAMA/benchmarks/attn/bench_metal_sq_attn.das @@ -3,6 +3,8 @@ options persistent_heap options _function_length = 0 // one MSL kernel body + its hand-bound dispatch per lab — barrier/register coupled, no seam options _cyclomatic_complexity = 0 // same — the side-by-side runners are flat arm ladders options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require dastest/testing_boost require dasllama/dasllama_env // the g_env_* knob globals ([EnvConfig] declarations; ENVIRONMENT.md is generated from them) diff --git a/modules/dasLLAMA/benchmarks/ew/bench_metal_gk_rows.das b/modules/dasLLAMA/benchmarks/ew/bench_metal_gk_rows.das index ccdaca2583..0f0f38ebf0 100644 --- a/modules/dasLLAMA/benchmarks/ew/bench_metal_gk_rows.das +++ b/modules/dasLLAMA/benchmarks/ew/bench_metal_gk_rows.das @@ -1,6 +1,8 @@ options gen2 options persistent_heap options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require dastest/testing_boost require dasllama/dasllama_env // the g_env_* knob globals ([EnvConfig] declarations; ENVIRONMENT.md is generated from them) diff --git a/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemm_kernels.das b/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemm_kernels.das index 18c4552e5a..66c1634def 100644 --- a/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemm_kernels.das +++ b/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemm_kernels.das @@ -3,6 +3,8 @@ options persistent_heap options _function_length = 0 // one MSL kernel body + its hand-bound dispatch per lab — barrier/register coupled, no seam options _cyclomatic_complexity = 0 // same — run_lab is the flat variant ladder options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require dastest/testing_boost require dasllama/dasllama_env // the g_env_* knob globals ([EnvConfig] declarations; ENVIRONMENT.md is generated from them) diff --git a/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemv_kernels.das b/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemv_kernels.das index a148d71dec..770178f316 100644 --- a/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemv_kernels.das +++ b/modules/dasLLAMA/benchmarks/matmul/bench_metal_gemv_kernels.das @@ -2,6 +2,8 @@ options gen2 options persistent_heap options _dasllama_internal = true options max_unreserved_size = 1073741824 // the synthetic planes are hundreds of MB by design (cls3b's q8 blob is 418 MB) +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require dastest/testing_boost require dasllama/dasllama_env // the g_env_* knob globals ([EnvConfig] declarations; ENVIRONMENT.md is generated from them) diff --git a/modules/dasLLAMA/benchmarks/matmul/bench_metal_kq_mm_lab.das b/modules/dasLLAMA/benchmarks/matmul/bench_metal_kq_mm_lab.das index a7ed64a46e..51dedbf9f4 100644 --- a/modules/dasLLAMA/benchmarks/matmul/bench_metal_kq_mm_lab.das +++ b/modules/dasLLAMA/benchmarks/matmul/bench_metal_kq_mm_lab.das @@ -4,6 +4,8 @@ options stack = 524288 // every dasLLAMA program root takes this budget (optio options _function_length = 0 // one MSL kernel body per lab twin — barrier/register coupled, no seam options _cyclomatic_complexity = 0 // the lab runner is a flat shape/arm ladder options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require metal/msl_shader require ?das_metal metal/das_metal_boost diff --git a/modules/dasLLAMA/benchmarks/matmul/bench_metal_moe_lab.das b/modules/dasLLAMA/benchmarks/matmul/bench_metal_moe_lab.das index 4e0ad1dfdf..86e3abf07b 100644 --- a/modules/dasLLAMA/benchmarks/matmul/bench_metal_moe_lab.das +++ b/modules/dasLLAMA/benchmarks/matmul/bench_metal_moe_lab.das @@ -4,6 +4,8 @@ options stack = 524288 // every dasLLAMA program root takes this budget (optio options _function_length = 0 // one MSL kernel body + its hand-bound dispatch per lab — barrier/register coupled, no seam options _cyclomatic_complexity = 0 // same — the lab runners are flat knockout ladders options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward require ?das_metal metal/das_metal_boost // GPU driver half, Apple builds only require dasllama/dasllama_env // the g_env_* knob globals ([EnvConfig] declarations; ENVIRONMENT.md is generated from them) diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes.das index 2c074364a1..36c42414ca 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_asr.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_asr.das index b9f0557354..1a753f7f95 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_asr.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_asr.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes_asr shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_blocks.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_blocks.das index 658250d4b2..9e5219add5 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_blocks.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_blocks.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes_blocks shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_dflash.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_dflash.das index e795e3c72d..4835b82762 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_dflash.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_dflash.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes_dflash shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_front.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_front.das index 4d17cc47ca..c6f98a530c 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_front.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_front.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes_front shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_rows.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_rows.das index ff9d9765bf..f284f8c62d 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_rows.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_rows.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_cuda_classes_rows shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_tts.das b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_tts.das index 2a7434792b..47066cbc18 100644 --- a/modules/dasLLAMA/dasllama/dasllama_cuda_classes_tts.das +++ b/modules/dasLLAMA/dasllama/dasllama_cuda_classes_tts.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The CUDA home's TTS stamps: the kernels the discrete TTS driver (`dasllama_tower_tts`) dispatches, each on the template //! the Vulkan home stamps under the same dispatch name (`dasllama_gpu_kernels_common`, `dasllama_gpu_kernels_discrete`). diff --git a/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_common.das b/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_common.das index b4538ab0a9..d4e87f2461 100644 --- a/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_common.das +++ b/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_common.das @@ -1,5 +1,7 @@ options gen2 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The kernels both GPU homes run, written once: a `class template` here carries a kernel's buffers, its //! argument struct and its body, and each home stamps it under its own dispatch name. module dasllama_gpu_kernels_common shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_discrete.das b/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_discrete.das index 4b404e062e..35f8f30cdb 100644 --- a/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_discrete.das +++ b/modules/dasLLAMA/dasllama/dasllama_gpu_kernels_discrete.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The kernel bodies the discrete GPU homes share - Vulkan and CUDA, not Metal: the decode GEMV family over every //! `KqFmt` with its decode helpers, the token step's row families, the decode attention, the K/V mirror stores and diff --git a/modules/dasLLAMA/dasllama/dasllama_gpu_math.das b/modules/dasLLAMA/dasllama/dasllama_gpu_math.das index dcd63469a7..03a3217b54 100644 --- a/modules/dasLLAMA/dasllama/dasllama_gpu_math.das +++ b/modules/dasLLAMA/dasllama/dasllama_gpu_math.das @@ -1,4 +1,6 @@ options gen2 +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The GPU kernel helpers both kernel homes splice into their shader bodies: pure ALU, no table, no backend //! lowering - the Metal and the Vulkan emitters each carry a call into its shader as a function of that shader. module dasllama_gpu_math shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_classes_tts.das b/modules/dasLLAMA/dasllama/dasllama_metal_classes_tts.das index 8f9e488275..239459ecee 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_classes_tts.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_classes_tts.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The Metal home's TTS stamps: the kernels the shared TTS driver (`dasllama_tower_tts`) dispatches, each on the template //! the discrete homes stamp under the same dispatch name (`dasllama_gpu_kernels_common`). diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_dflash.das b/modules/dasLLAMA/dasllama/dasllama_metal_dflash.das index 6ece4e3578..f57e39c038 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_dflash.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_dflash.das @@ -2,6 +2,8 @@ options gen2 options indenting = 4 options _comment_hygiene = true options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_metal_dflash shared private diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_gemm.das b/modules/dasLLAMA/dasllama/dasllama_metal_gemm.das index 1e6c8f47ef..039a7ee753 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_gemm.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_gemm.das @@ -2,6 +2,8 @@ options gen2 options _comment_hygiene = true options _metal_manual_dispatch = true // PERMANENT opt-out: single-dispatch synchronous donor BELOW the engine-graph layer (kn_*/hz live in dasllama_metal_common, which requires dasllama_common -> this module — a cycle). No graph, no intra-encoder hazard surface; the same cycle forces this module's OWN device/queue (the one-device-per-family rule's licensed exception). Moving kn_* into das_metal_boost would lift this. options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_metal_gemm shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_kernels.das b/modules/dasLLAMA/dasllama/dasllama_metal_kernels.das index 5904e4358b..b74e614993 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_kernels.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_kernels.das @@ -1,6 +1,8 @@ options gen2 options _comment_hygiene = true options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_metal_kernels shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_nmt.das b/modules/dasLLAMA/dasllama/dasllama_metal_nmt.das index d23b941b7f..5ed431747b 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_nmt.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_nmt.das @@ -2,6 +2,8 @@ options gen2 options indenting = 4 options _comment_hygiene = true options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_metal_nmt shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_prefill.das b/modules/dasLLAMA/dasllama/dasllama_metal_prefill.das index 7bacbb4583..ea005c5387 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_prefill.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_prefill.das @@ -1,6 +1,8 @@ options gen2 options _comment_hygiene = true options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_metal_prefill shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_metal_rail.das b/modules/dasLLAMA/dasllama/dasllama_metal_rail.das index 9a670e87af..f9eab5e513 100644 --- a/modules/dasLLAMA/dasllama/dasllama_metal_rail.das +++ b/modules/dasLLAMA/dasllama/dasllama_metal_rail.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The Metal home's tower rail: the encoder a shared chain body records on, the planes by role, and the class state a //! `[metal_rail_dispatch]` stamp's generated `ensure_` / `enc_(rail, roles, pc, ...)` runs over. diff --git a/modules/dasLLAMA/dasllama/dasllama_vulkan_classes.das b/modules/dasLLAMA/dasllama/dasllama_vulkan_classes.das index faa0343862..3286e76db8 100644 --- a/modules/dasLLAMA/dasllama/dasllama_vulkan_classes.das +++ b/modules/dasLLAMA/dasllama/dasllama_vulkan_classes.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_vulkan_classes shared public diff --git a/modules/dasLLAMA/dasllama/dasllama_vulkan_classes_dflash.das b/modules/dasLLAMA/dasllama/dasllama_vulkan_classes_dflash.das index 3e2e7e8d17..4729669fbf 100644 --- a/modules/dasLLAMA/dasllama/dasllama_vulkan_classes_dflash.das +++ b/modules/dasLLAMA/dasllama/dasllama_vulkan_classes_dflash.das @@ -1,6 +1,8 @@ options gen2 options indenting = 4 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward module dasllama_vulkan_classes_dflash shared public diff --git a/modules/dasLLAMA/harness/vk_gemm_probe.das b/modules/dasLLAMA/harness/vk_gemm_probe.das index 52cfba38a5..b0d48cfdb8 100644 --- a/modules/dasLLAMA/harness/vk_gemm_probe.das +++ b/modules/dasLLAMA/harness/vk_gemm_probe.das @@ -1,6 +1,8 @@ options gen2 options stack = 524288 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward // ATTRIBUTION SWEEP - isolated per-shape rates of the prefill GEMM tiles (cm2:, cm2d:, k4|k6, the shape pins). // ATTRIBUTION SWEEP cm2w: - the l stamp's rate by wave count, the workgroups the device fills. diff --git a/modules/dasLLAMA/harness/vk_gemv_probe.das b/modules/dasLLAMA/harness/vk_gemv_probe.das index 067af57ad0..14205f2e74 100644 --- a/modules/dasLLAMA/harness/vk_gemv_probe.das +++ b/modules/dasLLAMA/harness/vk_gemv_probe.das @@ -1,6 +1,8 @@ options gen2 options stack = 524288 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward // ATTRIBUTION SWEEP - isolated per-format rates of the decode GEMV classes at one served shape: // synthetic planes per kq format at [n x d], the shipped kq_gemv class dispatched over enough diff --git a/modules/dasLLAMA/harness/vk_gk_rows_probe.das b/modules/dasLLAMA/harness/vk_gk_rows_probe.das index 9d74ff7ec8..78762114e5 100644 --- a/modules/dasLLAMA/harness/vk_gk_rows_probe.das +++ b/modules/dasLLAMA/harness/vk_gk_rows_probe.das @@ -1,6 +1,8 @@ options gen2 options stack = 524288 options _dasllama_internal = true +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward //! The row-kernel ruler for the Vulkan stamps of the templates both homes stamp (`dasllama_gpu_kernels_common.das`): each //! class timed alone at a qwen35moe / qwen4exp decode shape (and the deltanet out-norm at a 512-row window) on the device diff --git a/modules/dasLLAMA/performance/coopmat_mulmm_port.das b/modules/dasLLAMA/performance/coopmat_mulmm_port.das index 541aeb3f55..a3225c9968 100644 --- a/modules/dasLLAMA/performance/coopmat_mulmm_port.das +++ b/modules/dasLLAMA/performance/coopmat_mulmm_port.das @@ -1,5 +1,7 @@ options gen2 options indenting = 4 +options loop_unroll_cost = 0 // kernel source: the emitter gets loops and locals as written +options disable_forward // scratch probe: OUR dasSpirv kernel at the matmul_q8_0_f32_f16acc_aligned_l config vs the // compiled reference spv, same device buffers, one shape (the 24-TF headline: m=9728 k=2560 n=512).