Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 149 additions & 1 deletion build/lib/tebako_python_builder/python_build.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,64 @@ class PythonBuild # rubocop:disable Metrics/ClassLength

MARKER = "# --- tebako: the fs TU + driver link (factory substitution) ---"

# gh-158283: LLVM 19 limited tail duplication of basic blocks that end
# in an indirect branch (llvm/llvm-project#78582). Clang lowers the
# interpreter's per-opcode computed-goto DISPATCH()es to ONE shared
# indirectbr and relies on the tail duplicator to copy it back into
# each handler; the new profitability limit stops that, so an affected
# compiler ships _PyEval_EvalFrameDefault with a single dispatch jump —
# defeating the per-opcode branch prediction that computed gotos exist
# for (9-13% slower on pyperformance; this factory's macos 3.14 legs
# built on the macos-15 fleet read fib-ratio 1.6-2.1 against the
# same-leg on-system reference where the clang-15-built published
# v0.3.3 exe reads 1.0-1.3 on the same image, and the fresh/v0.3.3
# binary gap reproduces at 1.26x interleaved; the published v0.3.3
# x86_64 exes carry the merged shape too — the x86_64 fleet has
# built with Xcode 16.3/16.4 all along). Fully fixed in LLVM
# 20.1.1 (llvm/llvm-project#114990); no 19.x release has the fix.
# Apple clang 1700.0.x (Xcode 16.3 AND 16.4 — the macos-15 fleet's
# whole toolchain set) carries the same bug, and 1700.3-1700.6
# (Xcode 26.0-26.3) still merges most dispatch jumps.
#
# The probe and the flag are CPython's own merged remedy (gh-158286,
# against configure.ac — 3.14.7's configure predates it, so the recipe
# probes here): a compile test on the compiler's identity macros —
# older clangs are unaffected and REJECT the option outright, so a
# version sniff would be both wrong and fragile. The flag must reach
# ceval.o ONLY: upstream measured regex_effbot 6-9% SLOWER when the
# forced duplication reaches the regex engine's own computed goto
# (code-layout-dependent, 1-9% across layouts — gh-158283's data), so
# a build-wide CFLAGS append would trade the interpreter's regression
# for the regex engine's. The channel is per-line:
#
# 3.14+: CFLAGS_CEVAL, Makefile.pre's ceval-only knob
# ($(PY_CORE_CFLAGS) $(CFLAGS_CEVAL) on the Python/ceval.o rule);
# configure substitutes the env value AND appends its own
# -finline-max-stacksize=512 probe result to the same variable.
# pre-3.14: Makefile.pre carries no CFLAGS_CEVAL (the knob lands
# with 3.14), so substitute_makefiles appends a GNU make
# target-specific binding, `Python/ceval.o: CFLAGS_NODIST += …` —
# ceval.o's recipe expands $(CFLAGS_NODIST) through the recursive
# PY_CFLAGS_NODIST with the target-local value, and every other
# TU (ceval_gil.o, _sre.o, the stdlib set) expands the empty
# global. Marker-verified end to end against a configured 3.13.15
# tree: the token lands on Python/ceval.o's compile line alone.
#
# GCC legs never see the flag (-mllvm is clang-only). A build whose
# probe misses a NEW affected compiler is caught at the artifact:
# ci/check_symbol_provenance.sh counts the exe's dispatch branches.
DISPATCH_TAIL_DUP_PROBE = <<~'C'.freeze
#if defined(__apple_build_version__)
# if __apple_build_version__ < 17000000 || __apple_build_version__ >= 18000000
# error not affected
# endif
#elif !defined(__clang__) || __clang_major__ != 19
# error not affected
#endif
int main(void) { return 0; }
C
DISPATCH_TAIL_DUP_FLAG = "-mllvm -tail-dup-pred-size=1000".freeze

def initialize(platform:, python_version:, prefix:, tarball:, src_sha256:, # rubocop:disable Metrics/ParameterLists,Metrics/MethodLength
link_unit:, link_unit_dir:, repo_root:, jobs: nil, macos_deployment_target: nil)
@platform = platform
Expand All @@ -99,6 +157,8 @@ def initialize(platform:, python_version:, prefix:, tarball:, src_sha256:, # rub
@jobs = jobs
@macos_deployment_target = macos_deployment_target
@jit_env = {}
@dispatch_tail_dup_probed = false
@dispatch_tail_dup_flag = nil
end

attr_reader :src_dir, :stage_dir
Expand Down Expand Up @@ -411,7 +471,7 @@ def configure_env
{
"ZLIB_CFLAGS" => "-I#{File.join(zlib, "include")}",
"ZLIB_LIBS" => mlibs.static_lib("z")
}
}.merge(dispatch_tail_dup_env)
elsif @platform.linux_gnu?
{ "LDFLAGS" => "-pthread" }
elsif @platform.msys?
Expand All @@ -422,6 +482,38 @@ def configure_env
end.merge(@jit_env)
end

# The probe itself, memoized (configure_env and substitute_makefiles
# both key on the outcome; the compiler runs once). The probe file is
# always removed: a stale copy in the prefix would outlive its run.
def probe_dispatch_tail_dup
return if @dispatch_tail_dup_probed

@dispatch_tail_dup_probed = true
@dispatch_tail_dup_cc = ENV.fetch("CC", "cc")
FileUtils.mkdir_p(@prefix)
probe = File.join(@prefix, "dispatch_tail_dup_probe.c")
File.write(probe, DISPATCH_TAIL_DUP_PROBE)
_, st = Open3.capture2e(@dispatch_tail_dup_cc, "-c", probe, "-o", File::NULL)
FileUtils.rm_f(probe)
@dispatch_tail_dup_flag = DISPATCH_TAIL_DUP_FLAG if st.exitstatus&.zero?
rescue Errno::ENOENT
# A missing cc is not an affected compiler; configure names the
# toolchain break moments later with its own error.
FileUtils.rm_f(probe)
nil
end

# True when the workaround must ride substitute_makefiles'
# target-specific append instead of the CFLAGS_CEVAL env: Makefile.pre
# carries the ceval-only knob only from 3.14 (configure.subst's
# AC_SUBST([CFLAGS_CEVAL]) and the Python/ceval.o rule's reference
# land together); older lines' Makefiles would never expand an env
# CFLAGS_CEVAL, so their ceval.o gets the flag from GNU make's
# target-specific binding instead.
def dispatch_tail_dup_via_append?
(@python.major_minor <=> [3, 14]) < 0
end

# --- the JIT toolchain gate (jit lines only) -------------------------
#
# CPython's copy-and-patch JIT compiles its stencils at BUILD time with
Expand Down Expand Up @@ -592,6 +684,8 @@ def substitute_makefiles # rubocop:disable Metrics/MethodLength
content += "\n#{MARKER}\nTEBAKO_LIBS=\t#{mlibs.tebako_libs}\n" \
"Programs/tebako_python.o: Programs/tebako_python.c $(PYTHON_HEADERS)\n" \
"\t$(CC) -c $(PY_CORE_CFLAGS) -o $@ $<\n"
tail_dup = dispatch_tail_dup_append
content += "#{tail_dup}\n" if tail_dup
File.write(path, content)
end

Expand Down Expand Up @@ -656,6 +750,8 @@ def verify_substitutions(durable)
mlibs.modlib_rewrites.each_key do |key|
missing << key unless content =~ /^#{key}=\S/
end
tail_dup = dispatch_tail_dup_append
missing << "the ceval dispatch tail-dup binding" if tail_dup && !content.include?(tail_dup)
return if missing.empty?

raise TebakoPythonBuilder::Error.new(
Expand Down Expand Up @@ -761,6 +857,58 @@ def place_pip

public

# The gh-158283 workaround's enablement probe (the constant block's
# comment owns the mechanism AND the per-line channel table): compile
# the identity-macro test with the build's own compiler (CC when set,
# else cc — configure's effective choice on the macOS legs, where both
# names resolve the same Apple clang). An affected compiler compiles
# the probe; an unaffected one trips the probe's #error, so the
# workaround self-retires when the fleet's toolchain leaves the
# affected window (and never reaches a GCC leg). On 3.14+ the flag
# rides the CFLAGS_CEVAL env channel (this method's return);
# pre-3.14 carries no such variable, so the env stays empty there and
# substitute_makefiles' target-specific append delivers the flag
# instead (the probe memo is what the append keys on — configure runs
# before the substitutions in #run). Public: configure_env's seam,
# specced directly.
def dispatch_tail_dup_env
return {} unless @platform.macos?

probe_dispatch_tail_dup
return {} if @dispatch_tail_dup_flag.nil?

channel = if dispatch_tail_dup_via_append?
"via the target-specific CFLAGS_NODIST append (pre-3.14 Makefile.pre carries no CFLAGS_CEVAL)"
else
"via CFLAGS_CEVAL"
end
puts "-- gh-158283: the build compiler merges the computed-goto dispatch " \
"(#{@dispatch_tail_dup_cc} passes the probe) — ceval builds with #{DISPATCH_TAIL_DUP_FLAG} #{channel}"
return {} if dispatch_tail_dup_via_append?

{ "CFLAGS_CEVAL" => DISPATCH_TAIL_DUP_FLAG }
end

# Pre-3.14's channel for the workaround (the constant block's comment
# owns the why): a GNU make target-specific variable binding. GNU
# make applies it to ceval.o's recipe however that recipe is found
# (the implicit rule here), and ceval.o's header-only prerequisites
# carry no recipes for the value to leak into. nil when the probe did
# not arm or the line carries CFLAGS_CEVAL. Public: specced directly.
def dispatch_tail_dup_append
probe_dispatch_tail_dup if @platform.macos?
return nil unless dispatch_tail_dup_via_append? && @dispatch_tail_dup_flag

"Python/ceval.o: CFLAGS_NODIST += #{@dispatch_tail_dup_flag}"
end

# The memo record for the probe: true once probe_dispatch_tail_dup
# has run, however it came out (substitute_makefiles must not
# re-compile the probe to learn the outcome).
def dispatch_tail_dup_probed?
@dispatch_tail_dup_probed
end

# The staged prefix tree (the image root's content): stage/<root>
# with the root spelling normalized ("/__tfs__" -> "__tfs__", the
# windows "A:/t" -> "A/t" — a literal drive-qualified directory name
Expand Down
34 changes: 34 additions & 0 deletions ci/check_symbol_provenance.sh
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,40 @@ elif printf '%s' "$file_out" | grep -q 'Mach-O'; then
[ -z "$minos" ] && fail "otool -l on $EXE yielded no minos record — a Mach-O without a support floor cannot be gated"
[ "$minos" = "$floor" ] || fail "$EXE records minos $minos but contract.yml pins $floor — the macOS floor floated with the runner image (tebako-runtime-python#81)"
note "the exe's recorded support floor is the pinned $floor"

# The interpreter's computed-goto dispatch survived the build compiler.
# gh-158283: Apple clang 1700.x (Xcode 16.3-16.4 fully, 26.0-26.3 mostly —
# the macos-15 fleet) merges the ceval loop's per-opcode dispatch jumps
# into ONE shared indirect branch (llvm/llvm-project#78582; fixed
# upstream in LLVM 20.1.1), defeating the per-opcode branch prediction
# computed gotos exist for — a slow interpreter that boots green and
# passes every functional gate (the macos-arm64 3.14 legs read fib-ratio
# 1.6-2.1 vs the same-leg reference where the clang-15-built v0.3.3 exe
# reads 1.0-1.3 on the same image; the published v0.3.3 x86_64 exes
# carry the merged shape too — the x86_64 legs have built with Xcode
# 16.3/16.4 all along). The recipe's tail-dup workaround
# (PythonBuild#dispatch_tail_dup_env / #dispatch_tail_dup_append)
# forces the duplication on ceval; this arm is the ARTIFACT-level proof
# the build carries it, so a probe miss on a future toolchain is a
# named failure here, never a green slow exe. The dispatch spelling is
# arch-specific in otool's output: arm64 `br <reg>`, x86_64
# `jmpq *<operand>` — count both, never the arch's direct jumps.
# The population floor is 100: a merged build carries 1 dispatch branch,
# healthy shapes carry 185-360 (handler dedup varies by compiler). A
# deliberate switch to the tail-calling interpreter changes the shape
# this arm measures — re-baseline it in the same change. otool labels
# the function like the main arm above; capture-then-test, same reason.
dis_eval="$(otool -tV "$EXE" 2>/dev/null | awk '/^__PyEval_EvalFrameDefault:/{f=1; next} f && /^[_a-zA-Z].*:$/{exit} f' || true)"
if [ -z "$dis_eval" ]; then
fail "otool yielded no _PyEval_EvalFrameDefault body in $EXE — the dispatch-shape check cannot run"
else
dispatch_sites="$(printf '%s\n' "$dis_eval" | awk '$2=="br" || ($2 ~ /^jmp/ && $3 ~ /^\*/) {n++} END {print n+0}')"
if [ "$dispatch_sites" -lt 100 ]; then
fail "$EXE's _PyEval_EvalFrameDefault carries $dispatch_sites indirect dispatch branch(es) — the compiler merged the per-opcode computed-goto dispatch into one shared site (gh-158283; llvm/llvm-project#78582): a ~10-30% slower interpreter on dispatch-dense code (the macos-15 fleet's Apple clang 1700.x). The recipe's dispatch tail-dup workaround either did not probe this compiler or the flag was dropped — the ceval build needs -mllvm -tail-dup-pred-size=1000 (3.14+: CFLAGS_CEVAL; pre-3.14: the target-specific CFLAGS_NODIST append)"
else
note "the eval loop carries $dispatch_sites per-opcode dispatch branches (the computed-goto shape survived the compiler)"
fi
fi
fi

if [ "$failures" -gt 0 ]; then
Expand Down
112 changes: 112 additions & 0 deletions spec/python_build_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# frozen_string_literal: true

# Copyright (c) 2026 [Ribose Inc](https://www.ribose.com).
# All rights reserved.
# This file is a part of tamatebako
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

require "spec_helper"
require "fileutils"
require "tmpdir"

# PythonBuild#dispatch_tail_dup_env / #dispatch_tail_dup_append — the
# gh-158283 workaround's enablement probe and per-line delivery (the
# class comment owns the mechanism): a compiler in the affected window
# (LLVM 19 / Apple clang 1700.x) compiles the identity-macro probe and
# ceval builds with -mllvm -tail-dup-pred-size=1000; any other compiler
# trips the probe's #error and the workaround stays off, so GCC legs
# never see a clang-only option and the workaround self-retires when the
# fleet's toolchain leaves the window. The delivery is per-line: 3.14+
# rides the CFLAGS_CEVAL env (Makefile.pre's ceval-only knob); pre-3.14
# has no such variable, so the env stays empty and substitute_makefiles
# appends a target-specific CFLAGS_NODIST binding for Python/ceval.o.
# The probe text mirrors CPython's merged configure test (gh-158286)
# verbatim.
RSpec.describe TebakoPythonBuilder::PythonBuild do
def build_for(platform, prefix, python_version: "3.14.7")
described_class.new(platform: platform, python_version: python_version,
prefix: prefix, tarball: "unused.tar.gz", src_sha256: "0" * 64,
link_unit: nil, link_unit_dir: nil, repo_root: REPO_ROOT)
end

def fake_cc(dir, exit_status)
path = File.join(dir, "cc")
File.write(path, "#!/bin/sh\nexit #{exit_status}\n")
FileUtils.chmod(0o755, path)
path
end

around do |example|
saved = ENV.fetch("CC", nil)
example.run
ensure
saved.nil? ? ENV.delete("CC") : ENV["CC"] = saved
end

it "mirrors gh-158286's compiler windows verbatim in the probe" do
probe = described_class::DISPATCH_TAIL_DUP_PROBE
expect(probe).to include("__apple_build_version__ < 17000000 || __apple_build_version__ >= 18000000")
expect(probe).to include("!defined(__clang__) || __clang_major__ != 19")
end

it "arms CFLAGS_CEVAL when the macOS build compiler compiles the probe" do
Dir.mktmpdir("dispatch-tail-dup-spec") do |dir|
ENV["CC"] = fake_cc(dir, 0)
build = build_for(TebakoPythonBuilder::Platform.new("arm64-darwin23"), File.join(dir, "build"))
expect(build.dispatch_tail_dup_env)
.to eq({ "CFLAGS_CEVAL" => "-mllvm -tail-dup-pred-size=1000" })
expect(build.dispatch_tail_dup_append).to be_nil
end
end

it "arms the target-specific Makefile append (never the env) on pre-3.14 lines" do
Dir.mktmpdir("dispatch-tail-dup-spec") do |dir|
ENV["CC"] = fake_cc(dir, 0)
build = build_for(TebakoPythonBuilder::Platform.new("arm64-darwin23"), File.join(dir, "build"),
python_version: "3.13.15")
expect(build.dispatch_tail_dup_env).to eq({})
expect(build.dispatch_tail_dup_append)
.to eq("Python/ceval.o: CFLAGS_NODIST += -mllvm -tail-dup-pred-size=1000")
end
end

it "stays empty when the macOS build compiler trips the probe's #error" do
Dir.mktmpdir("dispatch-tail-dup-spec") do |dir|
ENV["CC"] = fake_cc(dir, 1)
build = build_for(TebakoPythonBuilder::Platform.new("arm64-darwin23"), File.join(dir, "build"))
expect(build.dispatch_tail_dup_env).to eq({})
expect(build.dispatch_tail_dup_append).to be_nil
expect(File.exist?(File.join(dir, "build", "dispatch_tail_dup_probe.c"))).to be(false)
end
end

it "never probes off-macOS (a GCC leg must not see the clang-only flag)" do
Dir.mktmpdir("dispatch-tail-dup-spec") do |dir|
ENV["CC"] = fake_cc(dir, 0)
build = build_for(TebakoPythonBuilder::Platform.new("x86_64-pc-linux-gnu"), File.join(dir, "build"))
expect(build.dispatch_tail_dup_env).to eq({})
expect(build.dispatch_tail_dup_append).to be_nil
expect(build.dispatch_tail_dup_probed?).to be(false)
end
end
end
Loading