fix(mir/builder): use function-local ValueId throughout MIR builder

Phase 25.1b: Complete SSA fix - eliminate all global ValueId usage in function contexts.

Root cause: ~75 locations throughout MIR builder were using global value
generator (self.value_gen.next()) instead of function-local allocator
(f.next_value_id()), causing SSA verification failures and runtime
"use of undefined value" errors.

Solution:
- Added next_value_id() helper that automatically chooses correct allocator
- Fixed 19 files with ~75 occurrences of ValueId allocation
- All function-context allocations now use function-local IDs

Files modified:
- src/mir/builder/utils.rs: Added next_value_id() helper, fixed 8 locations
- src/mir/builder/builder_calls.rs: 17 fixes
- src/mir/builder/ops.rs: 8 fixes
- src/mir/builder/stmts.rs: 7 fixes
- src/mir/builder/emission/constant.rs: 6 fixes
- src/mir/builder/rewrite/*.rs: 10 fixes
- + 13 other files

Verification:
- cargo build --release: SUCCESS
- Simple tests with NYASH_VM_VERIFY_MIR=1: Zero undefined errors
- Multi-parameter static methods: All working

Known remaining: ValueId(22) in Stage-B (separate issue to investigate)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
nyash-codex
2025-11-17 00:48:18 +09:00
parent 35842503e6
commit eadde8d1dd
59 changed files with 1603 additions and 370 deletions

View File

@ -93,7 +93,7 @@ impl super::MirBuilder {
if let CallTarget::Global(ref name) = target {
// 0) Dev-only safety: treat condition_fn as always-true predicate when missing
if name == "condition_fn" {
let dstv = dst.unwrap_or_else(|| self.value_gen.next());
let dstv = dst.unwrap_or_else(|| self.next_value_id());
// Emit integer constant via ConstantEmissionBox
let one = crate::mir::builder::emission::constant::emit_integer(self, 1);
if dst.is_none() {
@ -110,7 +110,7 @@ impl super::MirBuilder {
// 1) Direct module function fallback: call by name if present
if let Some(ref module) = self.current_module {
if module.functions.contains_key(name) {
let dstv = dst.unwrap_or_else(|| self.value_gen.next());
let dstv = dst.unwrap_or_else(|| self.next_value_id());
let name_const = match crate::mir::builder::name_const::make_name_const_result(self, name) {
Ok(v) => v,
Err(e) => return Err(e),
@ -137,7 +137,7 @@ impl super::MirBuilder {
let (bx, _arity) = matches.remove(0);
let func_name = format!("{}.{}{}", bx, name, format!("/{}", arity_for_try));
// Emit legacy call directly to preserve behavior
let dstv = dst.unwrap_or_else(|| self.value_gen.next());
let dstv = dst.unwrap_or_else(|| self.next_value_id());
let name_const = match crate::mir::builder::name_const::make_name_const_result(self, &func_name) {
Ok(v) => v,
Err(e) => return Err(e),
@ -314,7 +314,7 @@ impl super::MirBuilder {
// Create a string constant for the function name via NameConstBox
let name_const = crate::mir::builder::name_const::make_name_const_result(self, &name)?;
// Allocate a destination if not provided so we can annotate it
let actual_dst = if let Some(d) = dst { d } else { self.value_gen.next() };
let actual_dst = if let Some(d) = dst { d } else { self.next_value_id() };
let mut args = args;
crate::mir::builder::ssa::local::finalize_args(self, &mut args);
self.emit_instruction(MirInstruction::Call {
@ -416,7 +416,7 @@ impl super::MirBuilder {
}
ASTNode::New { class, arguments, .. } if class == "IntegerBox" && arguments.len() == 1 => {
let iv = match self.build_expression(arguments[0].clone()) { Ok(v) => v, Err(e) => return Some(Err(e)) };
let fv = self.value_gen.next();
let fv = self.next_value_id();
if let Err(e) = self.emit_instruction(MirInstruction::TypeOp { dst: fv, op: TypeOpKind::Cast, value: iv, ty: MirType::Float }) { return Some(Err(e)); }
math_args.push(fv);
}
@ -429,13 +429,13 @@ impl super::MirBuilder {
}
}
// new MathBox()
let math_recv = self.value_gen.next();
let math_recv = self.next_value_id();
if let Err(e) = self.emit_constructor_call(math_recv, "MathBox".to_string(), vec![]) { return Some(Err(e)); }
self.value_origin_newbox.insert(math_recv, "MathBox".to_string());
// birth()
if let Err(e) = self.emit_method_call(None, math_recv, "birth".to_string(), vec![]) { return Some(Err(e)); }
// call method
let dst = self.value_gen.next();
let dst = self.next_value_id();
if let Err(e) = self.emit_method_call(Some(dst), math_recv, name.to_string(), math_args) { return Some(Err(e)); }
Some(Ok(dst))
}
@ -458,7 +458,7 @@ impl super::MirBuilder {
let iface = env_field.as_str();
let m = method;
let mut extern_call = |iface_name: &str, method_name: &str, effects: EffectMask, returns: bool| -> Result<ValueId, String> {
let result_id = self.value_gen.next();
let result_id = self.next_value_id();
self.emit_instruction(MirInstruction::ExternCall { dst: if returns { Some(result_id) } else { None }, iface_name: iface_name.to_string(), method_name: method_name.to_string(), args: arg_values.clone(), effects })?;
if returns {
Ok(result_id)
@ -490,7 +490,7 @@ impl super::MirBuilder {
for a in arguments {
match self.build_expression(a.clone()) { Ok(v) => arg_values.push(v), Err(e) => return Some(Err(e)) }
}
let result_id = self.value_gen.next();
let result_id = self.next_value_id();
let fun_name = format!("{}.{}{}", cls_name, method, format!("/{}", arg_values.len()));
let fun_val = match crate::mir::builder::name_const::make_name_const_result(self, &fun_name) {
Ok(v) => v,
@ -541,7 +541,7 @@ impl super::MirBuilder {
if let Some(type_name) = special_handlers::extract_string_literal(&args[1]) {
let val = self.build_expression(args[0].clone())?;
let ty = special_handlers::parse_type_name_to_mir(&type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if name == "isType" {
TypeOpKind::Check
} else {
@ -569,7 +569,7 @@ impl super::MirBuilder {
// Special-case: global str(x) → x.str() に正規化(内部は関数へ統一される)
if name == "str" && arg_values.len() == 1 {
let dst = self.value_gen.next();
let dst = self.next_value_id();
// Use unified method emission; downstream rewrite will functionize as needed
self.emit_method_call(Some(dst), arg_values[0], "str".to_string(), vec![])?;
return Ok(dst);
@ -582,7 +582,7 @@ impl super::MirBuilder {
if !use_unified {
// Legacy path
let dst = self.value_gen.next();
let dst = self.next_value_id();
// === ChatGPT5 Pro Design: Type-safe function call resolution ===
// Resolve call target using new type-safe system; if it fails, try static-method fallback
@ -599,7 +599,7 @@ impl super::MirBuilder {
.collect();
if matches.len() == 1 {
let (bx, _arity) = matches.remove(0);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let func_name = format!("{}.{}{}", bx, name, format!("/{}", arg_values.len()));
// Emit unified global call to the lowered static method function
self.emit_unified_call(Some(dst), CallTarget::Global(func_name), arg_values)?;
@ -619,7 +619,7 @@ impl super::MirBuilder {
.collect();
if cands.len() == 1 {
let func_name = cands.remove(0);
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_legacy_call(Some(dst), CallTarget::Global(func_name), arg_values)?;
return Ok(dst);
}
@ -644,7 +644,7 @@ impl super::MirBuilder {
Ok(dst)
} else {
// Unified path for builtins/externs
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_unified_call(
Some(dst),
CallTarget::Global(name),
@ -713,7 +713,7 @@ impl super::MirBuilder {
let mut call_args = Vec::with_capacity(arity + 1);
call_args.push(me_id);
call_args.extend(arg_values.into_iter());
let dst = self.value_gen.next();
let dst = self.next_value_id();
// Emit as unified global call to lowered function
self.emit_unified_call(
Some(dst),
@ -762,7 +762,7 @@ impl super::MirBuilder {
arg_values.push(self.build_expression(arg)?);
}
let parent_value = crate::mir::builder::emission::constant::emit_string(self, parent);
let result_id = self.value_gen.next();
let result_id = self.next_value_id();
self.emit_box_or_plugin_call(
Some(result_id),
parent_value,

View File

@ -69,7 +69,7 @@ impl super::MirBuilder {
let saved_allow_ret = self.cleanup_allow_return;
let saved_allow_throw = self.cleanup_allow_throw;
let ret_slot = self.value_gen.next();
let ret_slot = self.next_value_id();
self.return_defer_active = true;
self.return_defer_slot = Some(ret_slot);
self.return_deferred_emitted = false;
@ -82,7 +82,7 @@ impl super::MirBuilder {
catch_clause.exception_type
);
}
let exception_value = self.value_gen.next();
let exception_value = self.next_value_id();
self.emit_instruction(MirInstruction::Catch {
exception_type: catch_clause.exception_type.clone(),
exception_value,

View File

@ -51,11 +51,7 @@ impl super::MirBuilder {
for p in params.iter() {
// Allocate a value ID using the current function's value generator
// This creates a local variable, not a parameter
let pid = if let Some(ref mut f) = self.current_function {
f.next_value_id()
} else {
self.value_gen.next()
};
let pid = self.next_value_id();
if p == "args" {
// new ArrayBox() with no args
self.emit_instruction(MirInstruction::NewBox {

View File

@ -6,54 +6,44 @@
use crate::mir::{ConstValue, MirInstruction, ValueId};
use crate::mir::builder::MirBuilder;
/// Helper to allocate value ID from correct generator (function-local or global)
#[inline]
fn next_value_id(b: &mut MirBuilder) -> ValueId {
if let Some(ref mut f) = b.current_function {
f.next_value_id()
} else {
b.value_gen.next()
}
}
#[inline]
pub fn emit_integer(b: &mut MirBuilder, val: i64) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::Integer(val) });
dst
}
#[inline]
pub fn emit_bool(b: &mut MirBuilder, val: bool) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::Bool(val) });
dst
}
#[inline]
pub fn emit_float(b: &mut MirBuilder, val: f64) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::Float(val) });
dst
}
#[inline]
pub fn emit_string<S: Into<String>>(b: &mut MirBuilder, s: S) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::String(s.into()) });
dst
}
#[inline]
pub fn emit_null(b: &mut MirBuilder) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::Null });
dst
}
#[inline]
pub fn emit_void(b: &mut MirBuilder) -> ValueId {
let dst = next_value_id(b);
let dst = b.next_value_id();
let _ = b.emit_instruction(MirInstruction::Const { dst, value: ConstValue::Void });
dst
}

View File

@ -76,7 +76,7 @@ impl super::MirBuilder {
if let Some(type_name) = Self::extract_string_literal(&m.arguments[0]) {
let obj_val = self.build_expression_impl(*m.object.clone())?;
let ty = Self::parse_type_name_to_mir(&type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if m.method == "is" { crate::mir::TypeOpKind::Check } else { crate::mir::TypeOpKind::Cast };
self.emit_instruction(MirInstruction::TypeOp { dst, op, value: obj_val, ty })?;
return Ok(dst);
@ -244,7 +244,7 @@ impl super::MirBuilder {
} => self.build_new_expression(class.clone(), arguments.clone()),
ASTNode::ArrayLiteral { elements, .. } => {
let arr_id = self.value_gen.next();
let arr_id = self.next_value_id();
self.emit_instruction(MirInstruction::NewBox {
dst: arr_id,
box_type: "ArrayBox".to_string(),
@ -278,7 +278,7 @@ impl super::MirBuilder {
Ok(arr_id)
}
ASTNode::MapLiteral { entries, .. } => {
let map_id = self.value_gen.next();
let map_id = self.next_value_id();
self.emit_instruction(MirInstruction::NewBox {
dst: map_id,
box_type: "MapBox".to_string(),
@ -409,7 +409,7 @@ impl super::MirBuilder {
match class_hint.as_deref() {
Some("ArrayBox") => {
let index_val = self.build_expression(index)?;
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_box_or_plugin_call(
Some(dst),
target_val,
@ -422,7 +422,7 @@ impl super::MirBuilder {
}
Some("MapBox") => {
let index_val = self.build_expression(index)?;
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_box_or_plugin_call(
Some(dst),
target_val,

View File

@ -19,7 +19,7 @@ impl super::MirBuilder {
if use_unified {
// New unified path - use emit_unified_call with Value target
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_unified_call(
Some(dst),
super::builder_calls::CallTarget::Value(callee_id),
@ -28,7 +28,7 @@ impl super::MirBuilder {
Ok(dst)
} else {
// Unified-off path: still encode callee as Value to avoid by-name resolution
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::Call {
dst: Some(dst),
func: callee_id,

View File

@ -162,7 +162,7 @@ impl super::MirBuilder {
}
}
let me = self.variable_map.get("me").copied();
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::NewClosure {
dst,
params: params.clone(),

View File

@ -14,7 +14,7 @@ impl super::MirBuilder {
// Prepare merge and result
let merge_block: BasicBlockId = self.block_gen.next();
let result_val = self.value_gen.next();
let result_val = self.next_value_id();
let mut phi_inputs: Vec<(BasicBlockId, ValueId)> = Vec::new();
// Create dispatch block where we start comparing arms
@ -76,7 +76,7 @@ impl super::MirBuilder {
LiteralValue::Null => crate::mir::builder::emission::constant::emit_null(self),
LiteralValue::Void => crate::mir::builder::emission::constant::emit_void(self),
};
let cond_id = self.value_gen.next();
let cond_id = self.next_value_id();
crate::mir::builder::emission::compare::emit_to(self, cond_id, super::CompareOp::Eq, scr_val, lit_id)?;
crate::mir::builder::emission::branch::emit_conditional(self, cond_id, then_block, else_target)?;

View File

@ -9,7 +9,7 @@ impl super::MirBuilder {
) -> Result<ValueId, String> {
let res_val = self.build_expression_impl(expression)?;
let res_local = self.local_ssa_ensure(res_val, 0);
let ok_id = self.value_gen.next();
let ok_id = self.next_value_id();
self.emit_instruction(super::MirInstruction::BoxCall {
dst: Some(ok_id),
box_val: res_local,
@ -27,7 +27,7 @@ impl super::MirBuilder {
value: Some(res_local),
})?;
self.start_new_block(else_block)?;
let val_id = self.value_gen.next();
let val_id = self.next_value_id();
self.emit_instruction(super::MirInstruction::BoxCall {
dst: Some(val_id),
box_val: res_local,

View File

@ -36,7 +36,7 @@ impl super::MirBuilder {
let mut args_vec = vec![field_name_id];
crate::mir::builder::ssa::local::finalize_field_base_and_args(self, &mut base, &mut args_vec);
// BoxCall: getField(name)
let field_val = self.value_gen.next();
let field_val = self.next_value_id();
self.emit_instruction(MirInstruction::BoxCall {
dst: Some(field_val),
box_val: base,

View File

@ -24,7 +24,7 @@ impl MirBuilder {
// Compose lowered function name: BoxName.method/N
let func_name = format!("{}.{}/{}", box_name, method, arg_values.len());
let dst = self.value_gen.next();
let dst = self.next_value_id();
if std::env::var("NYASH_STATIC_CALL_TRACE").ok().as_deref() == Some("1") {
eprintln!("[builder] static-call {}", func_name);
@ -43,7 +43,7 @@ impl MirBuilder {
type_name: &str,
) -> Result<ValueId, String> {
let mir_ty = Self::parse_type_name_to_mir(type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if method == "is" {
TypeOpKind::Check
} else {
@ -99,7 +99,7 @@ impl MirBuilder {
// Receiver class hintは emit_unified_call 側で起源/型から判断する(重複回避)
// 統一経路: emit_unified_call に委譲RouterPolicy と rewrite::* で安定化)
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_unified_call(
Some(dst),
CallTarget::Method { box_type: None, method, receiver: object_value },

View File

@ -34,7 +34,7 @@ impl super::MirBuilder {
let rhs = self
.ensure_slotified_for_use(rhs_raw, "@binop_rhs")
.unwrap_or(rhs_raw);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let mir_op = self.convert_binary_operator(operator)?;
@ -193,8 +193,8 @@ impl super::MirBuilder {
.map(|s| s == "IntegerBox")
.unwrap_or(false)
{
let li = self.value_gen.next();
let ri = self.value_gen.next();
let li = self.next_value_id();
let ri = self.next_value_id();
self.emit_instruction(MirInstruction::TypeOp {
dst: li,
op: TypeOpKind::Cast,
@ -404,7 +404,7 @@ impl super::MirBuilder {
};
if !name.is_empty() {
let in_guard = self.current_function.as_ref().map(|f| f.signature.name.starts_with(guard_prefix)).unwrap_or(false);
let dst = self.value_gen.next();
let dst = self.next_value_id();
if !in_guard {
self.emit_legacy_call(Some(dst), super::builder_calls::CallTarget::Global(name.to_string()), vec![operand_val])?;
self.value_types.insert(dst, rett);
@ -417,7 +417,7 @@ impl super::MirBuilder {
match operator.as_str() {
"-" => {
let zero = crate::mir::builder::emission::constant::emit_integer(self, 0);
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(MirInstruction::BinOp {
dst,
op: crate::mir::BinaryOp::Sub,
@ -428,7 +428,7 @@ impl super::MirBuilder {
}
"!" | "not" => {
let f = crate::mir::builder::emission::constant::emit_bool(self, false);
let dst = self.value_gen.next();
let dst = self.next_value_id();
crate::mir::builder::emission::compare::emit_to(
self,
dst,
@ -440,7 +440,7 @@ impl super::MirBuilder {
}
"~" => {
let all1 = crate::mir::builder::emission::constant::emit_integer(self, -1);
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(MirInstruction::BinOp {
dst,
op: crate::mir::BinaryOp::BitXor,
@ -452,7 +452,7 @@ impl super::MirBuilder {
_ => {}
}
}
let dst = self.value_gen.next();
let dst = self.next_value_id();
let mir_op = self.convert_unary_operator(operator)?;
self.emit_instruction(MirInstruction::UnaryOp {
dst,

View File

@ -88,7 +88,7 @@ impl MirBuilder {
if let (Some(func), Some(cur_bb)) = (&self.current_function, self.current_block) {
crate::mir::phi_core::common::debug_verify_phi_inputs(func, cur_bb, &inputs);
}
let merged = self.value_gen.next();
let merged = self.next_value_id();
if let (Some(func), Some(cur_bb)) = (self.current_function.as_mut(), self.current_block) {
crate::mir::ssot::cf_common::insert_phi_at_head(func, cur_bb, merged, inputs);
} else {
@ -123,7 +123,7 @@ impl MirBuilder {
let assigned_var_else = else_ast_for_analysis
.as_ref()
.and_then(|a| crate::mir::phi_core::if_phi::extract_assigned_var(a));
let result_val = self.value_gen.next();
let result_val = self.next_value_id();
// フェーズM: no_phi_mode分岐削除常にPHI命令を使用

View File

@ -53,7 +53,7 @@ pub(crate) fn try_known_rewrite(
call_args.push(object_value);
call_args.append(&mut arg_values);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
if let Err(e) = builder.emit_unified_call(
Some(dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -98,7 +98,7 @@ pub(crate) fn try_known_rewrite_to_dst(
call_args.push(object_value);
call_args.append(&mut arg_values);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let actual_dst = want_dst.unwrap_or_else(|| builder.value_gen.next());
let actual_dst = want_dst.unwrap_or_else(|| builder.next_value_id());
if let Err(e) = builder.emit_unified_call(
Some(actual_dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -150,7 +150,7 @@ pub(crate) fn try_unique_suffix_rewrite(
let arity_us = arg_values.len();
call_args.append(&mut arg_values);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
if let Err(e) = builder.emit_unified_call(
Some(dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -192,7 +192,7 @@ pub(crate) fn try_unique_suffix_rewrite_to_dst(
let arity_us = arg_values.len();
call_args.append(&mut arg_values);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let actual_dst = want_dst.unwrap_or_else(|| builder.value_gen.next());
let actual_dst = want_dst.unwrap_or_else(|| builder.next_value_id());
if let Err(e) = builder.emit_unified_call(
Some(actual_dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),

View File

@ -35,7 +35,7 @@ pub(crate) fn try_early_str_like(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
if let Err(e) = builder.emit_unified_call(
Some(dst),
crate::mir::builder::builder_calls::CallTarget::Global(chosen.clone()),
@ -65,7 +65,7 @@ pub(crate) fn try_early_str_like(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
if let Err(e) = builder.emit_unified_call(
Some(dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -89,7 +89,7 @@ pub(crate) fn try_early_str_like(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
if let Err(e) = builder.emit_unified_call(
Some(dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -158,7 +158,7 @@ pub(crate) fn try_early_str_like_to_dst(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let actual_dst = want_dst.unwrap_or_else(|| builder.value_gen.next());
let actual_dst = want_dst.unwrap_or_else(|| builder.next_value_id());
if let Err(e) = builder.emit_unified_call(
Some(actual_dst),
crate::mir::builder::builder_calls::CallTarget::Global(chosen.clone()),
@ -189,7 +189,7 @@ pub(crate) fn try_early_str_like_to_dst(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let actual_dst = want_dst.unwrap_or_else(|| builder.value_gen.next());
let actual_dst = want_dst.unwrap_or_else(|| builder.next_value_id());
if let Err(e) = builder.emit_unified_call(
Some(actual_dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),
@ -216,7 +216,7 @@ pub(crate) fn try_early_str_like_to_dst(
let mut call_args = Vec::with_capacity(1);
call_args.push(object_value);
crate::mir::builder::ssa::local::finalize_args(builder, &mut call_args);
let actual_dst = want_dst.unwrap_or_else(|| builder.value_gen.next());
let actual_dst = want_dst.unwrap_or_else(|| builder.next_value_id());
if let Err(e) = builder.emit_unified_call(
Some(actual_dst),
crate::mir::builder::builder_calls::CallTarget::Global(fname.clone()),

View File

@ -12,7 +12,7 @@ impl BlockScheduleBox {
if let Some(&cached) = builder.schedule_mat_map.get(&(bb, src)) {
return Ok(cached);
}
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
builder.insert_copy_after_phis(dst, src)?;
builder.schedule_mat_map.insert((bb, src), dst);
return Ok(dst);
@ -25,7 +25,7 @@ impl BlockScheduleBox {
pub fn emit_before_call_copy(builder: &mut MirBuilder, src: ValueId) -> Result<ValueId, String> {
// Prefer to reuse the after-phis materialized id for this src in this block
let base = Self::ensure_after_phis_copy(builder, src)?;
let dst = builder.value_gen.next();
let dst = builder.next_value_id();
builder.emit_instruction(MirInstruction::Copy { dst, src: base })?;
// Propagate metadata to keep dst consistent with base
crate::mir::builder::metadata::propagate::propagate(builder, base, dst);

View File

@ -37,7 +37,7 @@ pub fn ensure(builder: &mut MirBuilder, v: ValueId, kind: LocalKind) -> ValueId
if let Some(&loc) = builder.local_ssa_map.get(&key) {
return loc;
}
let loc = builder.value_gen.next();
let loc = builder.next_value_id();
// Best-effort: errors are propagated by caller; we ignore here to keep helper infallible
let _ = builder.emit_instruction(crate::mir::MirInstruction::Copy { dst: loc, src: v });
if std::env::var("NYASH_LOCAL_SSA_TRACE").ok().as_deref() == Some("1") {

View File

@ -15,7 +15,7 @@ impl super::MirBuilder {
super::utils::builder_debug_log(&format!("extract_string_literal OK: {}", type_name));
let val = self.build_expression(call.arguments[0].clone())?;
let ty = super::MirBuilder::parse_type_name_to_mir(&type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if call.name == "isType" { TypeOpKind::Check } else { TypeOpKind::Cast };
super::utils::builder_debug_log(&format!("emit TypeOp {:?} value={} dst= {}", op, val, dst));
self.emit_instruction(MirInstruction::TypeOp { dst, op, value: val, ty })?;
@ -46,7 +46,7 @@ impl super::MirBuilder {
));
let val = self.build_expression(arguments[0].clone())?;
let ty = super::MirBuilder::parse_type_name_to_mir(&type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if name == "isType" {
TypeOpKind::Check
} else {
@ -89,7 +89,7 @@ impl super::MirBuilder {
));
let obj_val = self.build_expression(*object.clone())?;
let ty = super::MirBuilder::parse_type_name_to_mir(&type_name);
let dst = self.value_gen.next();
let dst = self.next_value_id();
let op = if method == "is" {
TypeOpKind::Check
} else {
@ -204,7 +204,7 @@ impl super::MirBuilder {
self.variable_map.insert(var_name.clone(), var_id);
last_value = Some(var_id);
}
Ok(last_value.unwrap_or_else(|| self.value_gen.next()))
Ok(last_value.unwrap_or_else(|| self.next_value_id()))
}
// Return statement
@ -266,7 +266,7 @@ impl super::MirBuilder {
for a in arguments.into_iter() {
arg_vals.push(self.build_expression(a)?);
}
let future_id = self.value_gen.next();
let future_id = self.next_value_id();
self.emit_instruction(MirInstruction::ExternCall {
dst: Some(future_id),
iface_name: "env.future".to_string(),
@ -278,7 +278,7 @@ impl super::MirBuilder {
return Ok(future_id);
}
let expression_value = self.build_expression(expression)?;
let future_id = self.value_gen.next();
let future_id = self.next_value_id();
self.emit_instruction(MirInstruction::FutureNew {
dst: future_id,
value: expression_value,
@ -294,7 +294,7 @@ impl super::MirBuilder {
) -> Result<ValueId, String> {
let future_value = self.build_expression(expression)?;
self.emit_instruction(MirInstruction::Safepoint)?;
let result_id = self.value_gen.next();
let result_id = self.next_value_id();
self.emit_instruction(MirInstruction::Await {
dst: result_id,
future: future_value,

View File

@ -25,6 +25,19 @@ pub(super) fn builder_debug_log(msg: &str) {
}
impl super::MirBuilder {
// ---- Value ID allocation (function-local or module-global) ----
/// Allocate a new ValueId in the appropriate context
/// - Inside function: uses function-local allocator
/// - Outside function: uses module-global allocator
#[inline]
pub(super) fn next_value_id(&mut self) -> super::ValueId {
if let Some(ref mut f) = self.current_function {
f.next_value_id() // Function context
} else {
self.value_gen.next() // Module context
}
}
// ---- LocalSSA convenience (readability helpers) ----
#[allow(dead_code)]
#[inline]
@ -72,7 +85,7 @@ impl super::MirBuilder {
for name in names.iter() {
if !name.starts_with("__pin$") { continue; }
if let Some(&src) = self.variable_map.get(name) {
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::Copy { dst, src })?;
crate::mir::builder::metadata::propagate::propagate(self, src, dst);
self.variable_map.insert(name.clone(), dst);
@ -201,7 +214,7 @@ impl super::MirBuilder {
value: super::ValueId,
expected_type: String,
) -> Result<super::ValueId, String> {
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::TypeOp {
dst,
op: TypeOpKind::Check,
@ -217,7 +230,7 @@ impl super::MirBuilder {
value: super::ValueId,
target_type: super::MirType,
) -> Result<super::ValueId, String> {
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::TypeOp {
dst,
op: TypeOpKind::Cast,
@ -235,7 +248,7 @@ impl super::MirBuilder {
if crate::config::env::mir_core13_pure() {
return Ok(box_val);
}
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::WeakRef {
dst,
op: WeakRefOp::New,
@ -252,7 +265,7 @@ impl super::MirBuilder {
if crate::config::env::mir_core13_pure() {
return Ok(weak_ref);
}
let dst = self.value_gen.next();
let dst = self.next_value_id();
self.emit_instruction(super::MirInstruction::WeakRef {
dst,
op: WeakRefOp::Load,
@ -282,7 +295,12 @@ impl super::MirBuilder {
pub(crate) fn pin_to_slot(&mut self, v: super::ValueId, hint: &str) -> Result<super::ValueId, String> {
self.temp_slot_counter = self.temp_slot_counter.wrapping_add(1);
let slot_name = format!("__pin${}${}", self.temp_slot_counter, hint);
let dst = self.value_gen.next();
// Phase 25.1b: Use function-local ID allocator to avoid SSA verification failures
let dst = if let Some(ref mut f) = self.current_function {
f.next_value_id() // Function context: use local ID
} else {
self.value_gen.next() // Module context: use global ID
};
self.emit_instruction(super::MirInstruction::Copy { dst, src: v })?;
if super::utils::builder_debug_enabled() || std::env::var("NYASH_PIN_TRACE").ok().as_deref() == Some("1") {
super::utils::builder_debug_log(&format!("pin slot={} src={} dst={}", slot_name, v.0, dst.0));
@ -295,7 +313,12 @@ impl super::MirBuilder {
/// Ensure a value has a local definition in the current block by inserting a Copy.
pub(crate) fn materialize_local(&mut self, v: super::ValueId) -> Result<super::ValueId, String> {
let dst = self.value_gen.next();
// Phase 25.1b: Use function-local ID allocator to avoid SSA verification failures
let dst = if let Some(ref mut f) = self.current_function {
f.next_value_id() // Function context: use local ID
} else {
self.value_gen.next() // Module context: use global ID
};
self.emit_instruction(super::MirInstruction::Copy { dst, src: v })?;
// Propagate metadata (type/origin) from source to the new local copy
crate::mir::builder::metadata::propagate::propagate(self, v, dst);