← Back to Pull requests

jit: do not compile methods with different optlevel in the same llvm module #62034

Open
KristofferC opened this pull request with 248 lines diff across 4 files
View on GitHub
KristofferC KristofferC commented on Jun 08, 2026 12:51 UTC
Author

The JIT compiles a batch of CodeInstances into one LLVM module, and selectOptLevel optimizes that module at the lowest julia-optimization-level among its functions. So a method first reached through a caller in an @optlevel 0 module was compiled at -O0. Its code, and with @simd reassociation its results, then depended on which caller happened to compile it first. Always-inline bodies emitted from such a module had the same effect on their host module.

This partitions the batch by effective optimization level and emits one module per level. All of the modules are defined in the JIT under a single LinkerMutex hold (addOutputs), so the batch stays atomic as in #61255. Calls between groups link directly to the callee rather than through a tojlinvoke trampoline; I checked this by disassembling the caller and following its call stub to the callee's specptr. The grouping uses jl_requested_optlevel, the same function codegen uses for the function attribute, and always-inline bodies no longer carry the attribute.

| | nightly | this PR |
|---|---|---|
| callee first reached via @optlevel 0 caller | compiled at -O0 | compiled at default level |
| always-inline body from @optlevel 0 module | drags host to -O0 | no effect |
| call between groups in one batch | n/a | direct (no trampoline) |

Written with Claude Code (Opus 5.5). The author has not yet read this description in full.

🤖 Generated with Claude Code

Diff: 248 lines (+184 / -64) across 4 files Reviewer: KristofferC Review duration: 217434m
All Vouch review confidence checks passed
Residual risk 0.11 = Change Risk (0.61) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.61 · 248 lines diff across 4 files
0.61
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.93 · 5 substantive comment(s)
0.93
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
82%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.330
Self Review self_review
0.140
Real PR Conversation Timeline
6 items
KristofferC KristofferC commented on code on Jun 08, 2026 14:08 UTC
Code Review
Compiler/test/codegen.jl:1
@@ -1218,3 +1218,32 @@ _blackbox_licmloop_simple(1.0)
     @test count(re_licmcall, ir_bb_simple) == 5  # unrolled, not hoisted
     @test !occursin(re_raw_arg, ir_bb_simple)
 end
+
+module OptLevelNoLeakHeavy
+    @noinline function ksum1(a)
+        s = 0.0
+        @inbounds @simd for i in eachindex(a)
+            s += a[i] * a[i]
+        end
+        return s
+    end
+    @noinline function ksum2(a)
+        s = 0.0
+        @inbounds @simd for i in eachindex(a)
+            s += a[i] * a[i]
+        end
+        return s
+    end
+end
+module OptLevelNoLeakSlow
+    Base.Experimental.@optlevel 0
+    using ..OptLevelNoLeakHeavy: ksum2
+    call2(a) = ksum2(a)
+end
+@testset "per-module optlevel does not leak across co-compiled modules" begin
+    Random.seed!(1)
+    a = rand(100_000)
+    expected = OptLevelNoLeakHeavy.ksum1(a)   # compiled directly at the default level
+    OptLevelNoLeakSlow.call2(a)               # ksum2 first reached (co-compiled) via an -O0 module
+    @test OptLevelNoLeakHeavy.ksum2(a) === expected

Maybe this won't test what it is supposed to test if bounds checking is forced on. Have to check.

KristofferC KristofferC commented on code on Jun 08, 2026 14:19 UTC
Code Review
Compiler/test/codegen.jl:1
@@ -1218,3 +1218,32 @@ _blackbox_licmloop_simple(1.0)
     @test count(re_licmcall, ir_bb_simple) == 5  # unrolled, not hoisted
     @test !occursin(re_raw_arg, ir_bb_simple)
 end
+
+module OptLevelNoLeakHeavy
+    @noinline function ksum1(a)
+        s = 0.0
+        @inbounds @simd for i in eachindex(a)
+            s += a[i] * a[i]
+        end
+        return s
+    end
+    @noinline function ksum2(a)
+        s = 0.0
+        @inbounds @simd for i in eachindex(a)
+            s += a[i] * a[i]
+        end
+        return s
+    end
+end
+module OptLevelNoLeakSlow
+    Base.Experimental.@optlevel 0
+    using ..OptLevelNoLeakHeavy: ksum2
+    call2(a) = ksum2(a)
+end
+@testset "per-module optlevel does not leak across co-compiled modules" begin
+    Random.seed!(1)
+    a = rand(100_000)
+    expected = OptLevelNoLeakHeavy.ksum1(a)   # compiled directly at the default level
+    OptLevelNoLeakSlow.call2(a)               # ksum2 first reached (co-compiled) via an -O0 module
+    @test OptLevelNoLeakHeavy.ksum2(a) === expected

Seems to work even with --check-bounds=yes, but does require O2.

julia +nightly --check-bounds=yes /tmp/test_opt.jl
per-module optlevel does not leak across co-compiled modules: Test Failed at /tmp/test_opt.jl:29
  Expression: OptLevelNoLeakHeavy.ksum2(a) === expected
   Evaluated: 33348.18205471307 === 33348.18205471279
...

julia +nightly --check-bounds=yes -O0 /tmp/test_opt.jl 
Test Summary:                                                | Pass  Total  Time
per-module optlevel does not leak across co-compiled modules |    1      1  0.1s

julia +nightly --check-bounds=yes -O1 /tmp/test_opt.jl 
Test Summary:                                                | Pass  Total  Time
per-module optlevel does not leak across co-compiled modules |    1      1  0.1s

xal-0 xal-0 commented on code on Jun 08, 2026 17:36 UTC
Code Review
src/jitlayers.cpp:1
@@ -442,62 +442,100 @@ static void jl_do_dump_compile(jl_code_instance_t *codeinst, uint64_t time)
                             julia_double_to_half(orig_time + time * 1e-9));
 }
 
+static constexpr size_t N_optlevels = 4;
+
+static int jl_clamp_optlevel(int requested) JL_NOTSAFEPOINT
+{
+    int opt_level = std::max(static_cast<int>(jl_options.opt_level), 0);
+    if (requested >= 0 && requested < opt_level)
+        opt_level = requested;
+    int opt_level_min = std::max(static_cast<int>(jl_options.opt_level_min), 0);
+    if (opt_level < opt_level_min)
+        opt_level = opt_level_min;
+    return std::min(opt_level, static_cast<int>(N_optlevels) - 1);
+}
+
+static int jl_codeinst_optlevel(jl_code_instance_t *ci)
+{
+    jl_method_instance_t *mi = jl_get_ci_mi(ci);
+    jl_value_t *def = mi->def.value;
+    int raw = jl_get_module_optlevel(jl_is_method(def) ? ((jl_method_t*)def)->module
+                                                       : mi->def.module);
+    return jl_clamp_optlevel(raw);
+}
+
 extern "C" JL_DLLEXPORT_CODEGEN void
 jl_emit_codeinsts_to_jit_impl(jl_code_instance_t **codeinsts, jl_code_info_t **srcs, int len)
 {
     if (len == 0)
         return;
 
     JL_TIMING(CODEINST_COMPILE, CODEINST_COMPILE);
-    const char *name = name_from_method_instance(jl_get_ci_mi(codeinsts[len - 1]));
-    auto ctx = std::make_unique<LLVMContext>();
-    auto &dl = jl_ExecutionEngine->getDataLayout();
-    auto &tt = jl_ExecutionEngine->getTargetTriple();
-    auto mod = jl_create_llvm_module(name, *ctx, dl, tt);
-    jl_codegen_output_t out{*mod};
-    out.get_context().setDiscardValueNames(true);
-    out.imaging_mode = false;
-    JL_GC_PUSH1(&out.temporary_roots);
 
+    // Partition the batch by effective optimization level and emit each group as
+    // its own LLVM module.
+    std::map<int, SmallVector<int, 0>> groups;
     for (int i = 0; i < len; ++i) {
-        jl_code_instance_t *codeinst = codeinsts[i];
-        jl_code_info_t *src = srcs[i];
-        jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
-
-        if (jl_atomic_load_relaxed(&codeinst->invoke))
-            continue;
+        if (jl_atomic_load_relaxed(&codeinsts[i]->invoke))
+            continue; // already compiled
+        groups[jl_codeinst_optlevel(codeinsts[i])].push_back(i);
+    }
+
+    for (auto &group : groups) {
+        SmallVector<int, 0> &idxs = group.second;
+        const char *name = name_from_method_instance(jl_get_ci_mi(codeinsts[idxs.back()]));
+        auto ctx = std::make_unique<LLVMContext>();
+        auto &dl = jl_ExecutionEngine->getDataLayout();
+        auto &tt = jl_ExecutionEngine->getTargetTriple();
+        auto mod = jl_create_llvm_module(name, *ctx, dl, tt);
+        jl_codegen_output_t out{*mod};
+        out.get_context().setDiscardValueNames(true);
+        out.imaging_mode = false;
+        JL_GC_PUSH1(&out.temporary_roots);
+
+        bool failed = false;
+        for (int i : idxs) {
+            jl_code_instance_t *codeinst = codeinsts[i];
+            jl_code_info_t *src = srcs[i];
+            jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
+
+            if (jl_atomic_load_relaxed(&codeinst->invoke))
+                continue;
 
-        out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
-        out.temporary_roots_set.clear();
-        if (!jl_emit_codeinst(out, codeinst, src)) { // contains safepoints
-            JL_GC_POP();
-            return;
-        }
+            out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
+            out.temporary_roots_set.clear();
+            if (!jl_emit_codeinst(out, codeinst, src)) { // contains safepoints
+                failed = true;
+                break;
+            }
 
-        // contains safepoints
-        jl_promote_method_roots(out, mi);
-        emit_always_inline(out, jl_get_method_ir); // contains safepoints
+            // contains safepoints
+            jl_promote_method_roots(out, mi);
+            emit_always_inline(out, jl_get_method_ir); // contains safepoints
 
-        // Non-opaque-closure MethodInstances are considered globally rooted
-        // through their methods, but for OC, we need to create a global root
-        // here.
-        if (jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure)
-            jl_as_global_root((jl_value_t*)mi, 1);
-    }
+            // Non-opaque-closure MethodInstances are considered globally rooted
+            // through their methods, but for OC, we need to create a global root
+            // here.
+            if (jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure)
+                jl_as_global_root((jl_value_t*)mi, 1);
+        }
 
-    out.temporary_roots = nullptr;
-    out.temporary_roots_set.clear();
-    JL_GC_POP();
+        out.temporary_roots = nullptr;
+        out.temporary_roots_set.clear();
+        JL_GC_POP();
 
-    if (out.ci_funcs.empty())
-        return;
+        if (failed)
+            return;
+        if (out.ci_funcs.empty())
+            continue;
 
-    emit_llvmcall_modules(out);
+        emit_llvmcall_modules(out);
 
-    auto &ES = jl_ExecutionEngine->getExecutionSession();
-    jl_emitted_output_t emitted =
-        out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
-    jl_ExecutionEngine->addOutput(std::move(emitted));
+        auto &ES = jl_ExecutionEngine->getExecutionSession();
+        jl_emitted_output_t emitted =
+            out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
+        jl_ExecutionEngine->addOutput(std::move(emitted));

I believe this reintroduces a more subtle version of the bug #61255 was intended to fix. In the current design, it is important that all of the CodeInfos passed to jl_emit_codeinsts_to_jit_impl be added to the JIT with a single addOutput call.

KristofferC KristofferC commented on code on Jun 08, 2026 21:00 UTC
Code Review
src/jitlayers.cpp:1
@@ -442,62 +442,100 @@ static void jl_do_dump_compile(jl_code_instance_t *codeinst, uint64_t time)
                             julia_double_to_half(orig_time + time * 1e-9));
 }
 
+static constexpr size_t N_optlevels = 4;
+
+static int jl_clamp_optlevel(int requested) JL_NOTSAFEPOINT
+{
+    int opt_level = std::max(static_cast<int>(jl_options.opt_level), 0);
+    if (requested >= 0 && requested < opt_level)
+        opt_level = requested;
+    int opt_level_min = std::max(static_cast<int>(jl_options.opt_level_min), 0);
+    if (opt_level < opt_level_min)
+        opt_level = opt_level_min;
+    return std::min(opt_level, static_cast<int>(N_optlevels) - 1);
+}
+
+static int jl_codeinst_optlevel(jl_code_instance_t *ci)
+{
+    jl_method_instance_t *mi = jl_get_ci_mi(ci);
+    jl_value_t *def = mi->def.value;
+    int raw = jl_get_module_optlevel(jl_is_method(def) ? ((jl_method_t*)def)->module
+                                                       : mi->def.module);
+    return jl_clamp_optlevel(raw);
+}
+
 extern "C" JL_DLLEXPORT_CODEGEN void
 jl_emit_codeinsts_to_jit_impl(jl_code_instance_t **codeinsts, jl_code_info_t **srcs, int len)
 {
     if (len == 0)
         return;
 
     JL_TIMING(CODEINST_COMPILE, CODEINST_COMPILE);
-    const char *name = name_from_method_instance(jl_get_ci_mi(codeinsts[len - 1]));
-    auto ctx = std::make_unique<LLVMContext>();
-    auto &dl = jl_ExecutionEngine->getDataLayout();
-    auto &tt = jl_ExecutionEngine->getTargetTriple();
-    auto mod = jl_create_llvm_module(name, *ctx, dl, tt);
-    jl_codegen_output_t out{*mod};
-    out.get_context().setDiscardValueNames(true);
-    out.imaging_mode = false;
-    JL_GC_PUSH1(&out.temporary_roots);
 
+    // Partition the batch by effective optimization level and emit each group as
+    // its own LLVM module.
+    std::map<int, SmallVector<int, 0>> groups;
     for (int i = 0; i < len; ++i) {
-        jl_code_instance_t *codeinst = codeinsts[i];
-        jl_code_info_t *src = srcs[i];
-        jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
-
-        if (jl_atomic_load_relaxed(&codeinst->invoke))
-            continue;
+        if (jl_atomic_load_relaxed(&codeinsts[i]->invoke))
+            continue; // already compiled
+        groups[jl_codeinst_optlevel(codeinsts[i])].push_back(i);
+    }
+
+    for (auto &group : groups) {
+        SmallVector<int, 0> &idxs = group.second;
+        const char *name = name_from_method_instance(jl_get_ci_mi(codeinsts[idxs.back()]));
+        auto ctx = std::make_unique<LLVMContext>();
+        auto &dl = jl_ExecutionEngine->getDataLayout();
+        auto &tt = jl_ExecutionEngine->getTargetTriple();
+        auto mod = jl_create_llvm_module(name, *ctx, dl, tt);
+        jl_codegen_output_t out{*mod};
+        out.get_context().setDiscardValueNames(true);
+        out.imaging_mode = false;
+        JL_GC_PUSH1(&out.temporary_roots);
+
+        bool failed = false;
+        for (int i : idxs) {
+            jl_code_instance_t *codeinst = codeinsts[i];
+            jl_code_info_t *src = srcs[i];
+            jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
+
+            if (jl_atomic_load_relaxed(&codeinst->invoke))
+                continue;
 
-        out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
-        out.temporary_roots_set.clear();
-        if (!jl_emit_codeinst(out, codeinst, src)) { // contains safepoints
-            JL_GC_POP();
-            return;
-        }
+            out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
+            out.temporary_roots_set.clear();
+            if (!jl_emit_codeinst(out, codeinst, src)) { // contains safepoints
+                failed = true;
+                break;
+            }
 
-        // contains safepoints
-        jl_promote_method_roots(out, mi);
-        emit_always_inline(out, jl_get_method_ir); // contains safepoints
+            // contains safepoints
+            jl_promote_method_roots(out, mi);
+            emit_always_inline(out, jl_get_method_ir); // contains safepoints
 
-        // Non-opaque-closure MethodInstances are considered globally rooted
-        // through their methods, but for OC, we need to create a global root
-        // here.
-        if (jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure)
-            jl_as_global_root((jl_value_t*)mi, 1);
-    }
+            // Non-opaque-closure MethodInstances are considered globally rooted
+            // through their methods, but for OC, we need to create a global root
+            // here.
+            if (jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure)
+                jl_as_global_root((jl_value_t*)mi, 1);
+        }
 
-    out.temporary_roots = nullptr;
-    out.temporary_roots_set.clear();
-    JL_GC_POP();
+        out.temporary_roots = nullptr;
+        out.temporary_roots_set.clear();
+        JL_GC_POP();
 
-    if (out.ci_funcs.empty())
-        return;
+        if (failed)
+            return;
+        if (out.ci_funcs.empty())
+            continue;
 
-    emit_llvmcall_modules(out);
+        emit_llvmcall_modules(out);
 
-    auto &ES = jl_ExecutionEngine->getExecutionSession();
-    jl_emitted_output_t emitted =
-        out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
-    jl_ExecutionEngine->addOutput(std::move(emitted));
+        auto &ES = jl_ExecutionEngine->getExecutionSession();
+        jl_emitted_output_t emitted =
+            out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
+        jl_ExecutionEngine->addOutput(std::move(emitted));

Thoughts about the updated revision?

KristofferC KristofferC commented on Jul 23, 2026 12:11 UTC
Author

Bump (@xal-0). I know you are planning on rewriting this, but maybe there is some value in getting this in in the meantime.

Reviewers
Assignees
KristofferC KristofferC
Labels
risk: low confidence: 82.7% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 61.4% (MEDIUM) · Higher = larger blast radius
61.4%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 82.7% · Lower = rushed or shallow review
82.7%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 10.6% · Safe to merge
10.6%