修正了种子编译器的错误
This commit is contained in:
@@ -330,6 +330,33 @@ class ForHandle(BaseHandle):
|
||||
for name in implicit_names:
|
||||
if name not in nonlocal_var_names:
|
||||
nonlocal_var_names.append(name)
|
||||
# 堆分配 nonlocal 变量:避免外层函数返回后栈帧释放导致悬垂指针
|
||||
# 闭包返回模式(return nested_fn)要求捕获变量在堆上存活
|
||||
malloc_fn_type: ir.FunctionType = ir.FunctionType(ir.IntType(8).as_pointer(), [ir.IntType(64)])
|
||||
malloc_func: ir.Function = Gen._get_or_declare_func('malloc', malloc_fn_type)
|
||||
for var_name in nonlocal_var_names:
|
||||
if var_name in Gen.variables and Gen.variables[var_name] is not None:
|
||||
old_var: ir.Value = Gen.variables[var_name]
|
||||
if isinstance(old_var.type, ir.PointerType):
|
||||
elem_type: ir.Type = old_var.type.pointee
|
||||
# 计算元素大小(字节)
|
||||
elem_size: int = 8 # 默认指针大小
|
||||
if isinstance(elem_type, ir.IntType):
|
||||
elem_size = max(1, elem_type.width // 8)
|
||||
elif isinstance(elem_type, ir.FloatType):
|
||||
elem_size = 4
|
||||
elif isinstance(elem_type, ir.DoubleType):
|
||||
elem_size = 8
|
||||
elif isinstance(elem_type, ir.PointerType):
|
||||
elem_size = 8
|
||||
# malloc 堆存储
|
||||
heap_raw: ir.Value = Gen.builder.call(malloc_func, [ir.Constant(ir.IntType(64), elem_size)], name=f"heap_{var_name}")
|
||||
heap_ptr: ir.Value = Gen.builder.bitcast(heap_raw, ir.PointerType(elem_type), name=f"heap_{var_name}_ptr")
|
||||
# 复制栈值到堆
|
||||
old_val: ir.Value = Gen._load(old_var, name=f"load_old_{var_name}")
|
||||
Gen._store(old_val, heap_ptr)
|
||||
# 更新 Gen.variables 使外层和嵌套函数都使用堆指针
|
||||
Gen.variables[var_name] = heap_ptr
|
||||
extra_params: list[tuple[str, ir.Type]] = []
|
||||
for var_name in nonlocal_var_names:
|
||||
if var_name in Gen.variables and Gen.variables[var_name] is not None:
|
||||
|
||||
Reference in New Issue
Block a user