Merged
fix(ir): Fix store python object in pypto.loop #5245
lidongshengAdd on Aug 3
fix(ir): Fix store python object in pypto.loop #5245
Merged
lidongshengAdd on Aug 3
Total: 22 files changed+618-430
@@ -36,6 +36,13 @@ def has_scalar(values: list) -> bool:
36 return any(isinstance(v, pypto.pypto_impl.SymbolicScalar) for v in values)36 return any(isinstance(v, pypto.pypto_impl.SymbolicScalar) for v in values)
37 37 
38 38 
39+# Opaque Python values (dataclass instances, ...) are compile-time only:
40+# leave them in scope (the body's own stores keep them current) and skip
41+# them from the IR loop-carried / branch-carried yield state
42+def is_opaque_value(val) -> bool:
43+ return not (val is None or isinstance(val, (bool, int, float, pypto.SymbolicScalar, pypto.Tensor, list, tuple)))
44+ 
45+ 
39# ---- Compile-time ops ----46# ---- Compile-time ops ----
40 47 
41 48 
@@ -298,6 +305,8 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, stop, ctx: BuildContext):
298 iter_args, return_var_names = [], []305 iter_args, return_var_names = [], []
299 for name in sorted(body.store_names):306 for name in sorted(body.store_names):
300 val = scope.locals.get(name)307 val = scope.locals.get(name)
308+ if is_opaque_value(val):
309+ continue
301 var = ctx.create_var_like(name, ctx.unwrap(val))310 var = ctx.create_var_like(name, ctx.unwrap(val))
302 iter_arg = ctx.create_iter_arg(var, initValue=ctx.unwrap(val))311 iter_arg = ctx.create_iter_arg(var, initValue=ctx.unwrap(val))
303 scope.store(name, ctx.wrap(var))312 scope.store(name, ctx.wrap(var))
@@ -394,7 +403,11 @@ def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext)
394 scope = Scope.current()403 scope = Scope.current()
395 404 
396 saved = dict(scope.locals)405 saved = dict(scope.locals)
397- yield_var_names = sorted(then_block.store_names | else_block.store_names)406+ yield_var_names = [
407+ name
408+ for name in sorted(then_block.store_names | else_block.store_names)
409+ if not is_opaque_value(scope.locals.get(name))
410+ ]
398 411 
399 try:412 try:
400 ctx.checkpoint()413 ctx.checkpoint()
@@ -291,6 +291,7 @@ class BuildContext(ir.IRBuilder):
291 return val291 return val
292 292 
293 293 
294+ 
294class CollectContext(BuildContext):295class CollectContext(BuildContext):
295 pass296 pass
296 297 
@@ -0,0 +1,8 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
@@ -1,15 +0,0 @@
1-@ir.function
2-def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3- View_x@3 = VIEW(x@0)
4- View_y@4 = VIEW(y@1)
5- for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
6- if (loop_idx_32==0):
7- $1@6 = SUB(View_x@3, View_y@4)
8- z@2 = ASSEMBLE($1@6)
9- ir.yield_()
10- else:
11- $3@7 = ADD(View_x@3, View_y@4)
12- z@2 = ASSEMBLE($3@7)
13- ir.yield_()
14- continue
15- return x@0, y@1, z@2
@@ -1,9 +0,0 @@
1-@ir.function
2-def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3- View_x@3 = VIEW(x@0)
4- View_y@4 = VIEW(y@1)
5- for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
6- $1@6 = SUB(View_x@3, View_y@4)
7- z@2 = ASSEMBLE($1@6)
8- continue
9- return x@0, y@1, z@2
@@ -1,17 +0,0 @@
1-@ir.function
2-def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3- View_x@3 = VIEW(x@0)
4- View_y@4 = VIEW(y@1)
5- for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
6- if (loop_idx_32==0):
7- $0@5 = ADD(View_x@3, View_y@4)
8- $3@7 = ADD($0@5, View_x@3)
9- z@2 = ASSEMBLE($3@7)
10- ir.yield_()
11- else:
12- $1@6 = SUB(View_x@3, View_y@4)
13- $3_1@7 = ADD($1@6, View_x@3)
14- z@2 = ASSEMBLE($3_1@7)
15- ir.yield_()
16- continue
17- return x@0, y@1, z@2
@@ -1,15 +0,0 @@
1-@ir.function
2-def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3- View_x@3 = VIEW(x@0)
4- View_y@4 = VIEW(y@1)
5- for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
6- if (loop_idx_32==0):
7- $0@5 = ADD(View_x@3, View_y@4)
8- z@2 = ASSEMBLE($0@5)
9- ir.yield_()
10- else:
11- $3@7 = SUB(View_x@3, View_y@4)
12- z@2 = ASSEMBLE($3@7)
13- ir.yield_()
14- continue
15- return x@0, y@1, z@2
@@ -0,0 +1,54 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Common helpers shared across ir.Pass tests (merge_stmts_into_if and friends)."""
10+ 
11+import difflib
12+import logging
13+ 
14+from pypto import ir, pil
15+ 
16+ 
17+def check_snapshot(func, golden):
18+ actual = str(func)
19+ if golden.strip() != actual.strip():
20+ diff = "".join(
21+ difflib.unified_diff(
22+ golden.splitlines(keepends=True),
23+ actual.splitlines(keepends=True),
24+ )
25+ )
26+ raise AssertionError("IR snapshot mismatch in %s:\n%s" % (func.name, diff))
27+ 
28+ 
29+def _ssa_verify(verifier, prog, name):
30+ diagnostic = verifier.verify(prog)
31+ if diagnostic:
32+ print(f"{name}: {prog}\n")
33+ print(ir.IRVerifier.generate_report(diagnostic))
34+ raise
atomgit-bot

🟡 Medium Priority

变更行:python/tests/ut/ir/test_common.py 第 34 行的 raise。

受影响的代码:_ssa_verify 函数(第 29–34 行)在 diagnostic 为真值时执行 raise,但该调用不在任何 except 块内,因此 Python 运行时会抛出 RuntimeError: No active exception to reraise,而非带有诊断信息的 AssertionError 或 RuntimeError。

失败模式:当 SSA 验证失败(diagnostic 为真值)时,之前的 print 语句会输出诊断报告,但紧接着的 raise 会抛出令人困惑的 RuntimeError: No active exception to reraise,掩盖了真正的失败原因,并使测试失败信息难以理解。

触发条件:IR pass(canonicalize / dce / merge_stmts_into_if)产生的 IR 程序未通过 SSA 验证时触发。

注意:该问题在旧文件 test_merge_pass.py(已删除)中已存在,但随本次重构被原样迁移至新增的 test_common.py 文件中。

建议:将 bare raise 替换为携带诊断信息的 raise AssertionError,例如:raise AssertionError(f"SSA verification failed for {name}") 或 raise RuntimeError(f"SSA verification failed for {name}")。

likedislike
Incorrect?
35+ 
36+ 
37+def run_merge_pass(func, *args):
38+ """Compile a kernel and run canonicalize + dce + merge_stmts_into_if, stopping before lowering
39+ so the resulting if-tree (func.body) is inspectable. Mirrors compile_new_ir's first half."""
40+ b = ir.IRBuilder()
41+ func = pil.compile(func, *args)
42+ prog = b.create_program([func], "main", ir.Span.unknown())
43+ dce = ir.Pass.aggressive_dce()
44+ canonical = ir.Pass.canonicalize()
45+ merge = ir.Pass.merge_stmts_into_if()
46+ verifier = ir.IRVerifier.create_default()
47+ _ssa_verify(verifier, prog, "original")
48+ prog = dce(canonical(prog))
49+ _ssa_verify(verifier, prog, "dce")
50+ prog = canonical(merge(prog))
51+ _ssa_verify(verifier, prog, "merged")
52+ func = prog.functions[func.name]
53+ logging.info("\nmerged:\n%s" % func.body)
54+ return func
@@ -1,365 +0,0 @@
1-# -*- coding: utf-8 -*-
2-# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4-# CANN Open Software License Agreement Version 2.0 (the "License").
5-# Please refer to the License for details. You may not use this file except in compliance with the License.
6-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8-# See LICENSE in the root of the software repository for the full text of the License.
9-"""Comprehensive tests for ir.Pass.merge_stmts_into_if."""
10- 
11-import difflib
12-import inspect
13-import logging
14-import os
15- 
16-import pypto
17-from pypto import ir, pil
18- 
19- 
20-def _collect_stmts(stmt, cls):
21- """Recursively collect all stmts of a given IR type."""
22- result = []
23- if isinstance(stmt, cls):
24- result.append(stmt)
25- if isinstance(stmt, ir.SeqStmts):
26- for s in stmt.stmts:
27- result.extend(_collect_stmts(s, cls))
28- if isinstance(stmt, ir.ForStmt):
29- result.extend(_collect_stmts(stmt.body, cls))
30- if isinstance(stmt, ir.IfStmt):
31- result.extend(_collect_stmts(stmt.then_body, cls))
32- if stmt.else_body is not None:
33- result.extend(_collect_stmts(stmt.else_body, cls))
34- if isinstance(stmt, ir.WhileStmt):
35- result.extend(_collect_stmts(stmt.body, cls))
36- return result
37- 
38- 
39-def _check_snapshot(test_name, func):
40- module_name = os.path.splitext(os.path.basename(__file__))[0]
41- path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "snapshot",
42- "%s.%s.pir" % (module_name, test_name))
43- if not os.path.exists(path):
44- return
45- 
46- def normalize(x):
47- return x.rstrip("\n") + "\n"
48- 
49- with open(path) as f:
50- golden = normalize(f.read())
51- 
52- actual = str(func) + "\n"
53- actual = normalize(actual)
54- if golden != actual:
55- diff = "".join(
56- difflib.unified_diff(
57- golden.splitlines(keepends=True),
58- actual.splitlines(keepends=True),
59- fromfile="%s (golden)" % path,
60- tofile="%s (actual)" % path,
61- )
62- )
63- raise AssertionError("IR snapshot mismatch in %s:\n%s" % (test_name, diff))
64- 
65- 
66-def _ssa_verify(verifier, prog, name):
67- diagnostic = verifier.verify(prog)
68- if diagnostic:
69- print(f"{name}: {prog}\n")
70- print(ir.IRVerifier.generate_report(diagnostic))
71- raise
72- 
73- 
74-def _run_merge(func, *args):
75- """Compile a kernel and run canonicalize + dce + merge_stmts_into_if, stopping before lowering
76- so the resulting if-tree (func.body) is inspectable. Mirrors compile_new_ir's first half."""
77- b = ir.IRBuilder()
78- func = pil.compile(func, *args)
79- prog = b.create_program([func], "main", ir.Span.unknown())
80- dce = ir.Pass.aggressive_dce()
81- canonical = ir.Pass.canonicalize()
82- merge = ir.Pass.merge_stmts_into_if()
83- verifier = ir.IRVerifier.create_default()
84- _ssa_verify(verifier, prog, "original")
85- prog = dce(canonical(prog))
86- _ssa_verify(verifier, prog, "dce")
87- prog = canonical(merge(prog))
88- _ssa_verify(verifier, prog, "merged")
89- func = prog.functions[func.name]
90- logging.info("\nmerged:\n%s" % func.body)
91- _check_snapshot(inspect.stack()[1].function, func)
92- return func
93- 
94- 
95-def test_merge_pass1():
96- """A loop is a barrier (never duplicated into branches) and the pass recurses into its body."""
97- 
98- def foo(x, y, z):
99- pypto.set_vec_tile_shapes(16, 16)
100- for i in pypto.loop(2):
101- xv = pypto.view(x, [16, 16], [0, 0])
102- yv = pypto.view(y, [16, 16], [0, 0])
103- if i == 0:
104- t = xv + yv
105- else:
106- t = xv - yv
107- if i == 1:
108- t2 = t + xv
109- else:
110- t2 = t - xv
111- pypto.assemble(t2, [0, 0], z)
112- 
113- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
114- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
115- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
116- func = _run_merge(foo, x, y, z)
117- # The loop must stay single (barrier), not be duplicated into every leaf.
118- assert len(_collect_stmts(func.body, ir.ForStmt)) == 1
119- # Conditions nested in source order inside the loop body (pass recurses into loop bodies).
120- assert len(_collect_stmts(func.body, ir.IfStmt)) >= 2
121- 
122- 
123-def test_merge_pass2():
124- """Under `i == 0` the nested `i == 1` is UNSAT, so its branch is pruned (not 2^N leaves)."""
125- 
126- def foo(x, y, z):
127- pypto.set_vec_tile_shapes(16, 16)
128- xv = pypto.view(x, [16, 16], [0, 0])
129- yv = pypto.view(y, [16, 16], [0, 0])
130- for i in pypto.loop(2):
131- if i == 0:
132- if i == 1: # impossible under i == 0
133- t = xv + yv # DEAD -> must be pruned
134- else:
135- t = xv - yv
136- else:
137- t = xv + yv
138- pypto.assemble(t, [0, 0], z)
139- 
140- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
141- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
142- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
143- func = _run_merge(foo, x, y, z)
144- # Only the outer `i == 0` if remains; the impossible nested `i == 1` collapsed (would be 2 ifs
145- # without SAT pruning).
146- assert len(_collect_stmts(func.body, ir.IfStmt)) == 1
147- 
148- 
149-def test_merge_pass3():
150- """`i + 1 == 0` is impossible for i in {0, 1}: the solver models the loop range (i >= 0),
151- proves the then-branch UNSAT, and prunes it -> the if collapses to the surviving else branch.
152- """
153- 
154- def foo(x, y, z):
155- pypto.set_vec_tile_shapes(16, 16)
156- xv = pypto.view(x, [16, 16], [0, 0])
157- yv = pypto.view(y, [16, 16], [0, 0])
158- for i in pypto.loop(2):
159- if i + 1 == 0: # UNSAT under the loop range i in {0, 1} -> then-branch pruned
160- t = xv + yv
161- else:
162- t = xv - yv
163- pypto.assemble(t, [0, 0], z)
164- 
165- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
166- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
167- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
168- func = _run_merge(foo, x, y, z)
169- assert len(_collect_stmts(func.body, ir.IfStmt)) == 0
170- 
171- 
172-def test_merge_pass4():
173- """A loop between two ifs splits the region: each side is tree-built independently, loop stays single."""
174- 
175- def foo(x, y, z):
176- pypto.set_vec_tile_shapes(16, 16)
177- xv = pypto.view(x, [16, 16], [0, 0])
178- yv = pypto.view(y, [16, 16], [0, 0])
179- for i in pypto.loop(2):
180- if i == 0:
181- a = xv + yv
182- else:
183- a = xv - yv
184- for j in pypto.loop(2): # inner loop in the middle -> barrier (self-contained)
185- pypto.assemble(a, [j * 16, 0], z)
186- if i == 1:
187- c = a + yv
188- else:
189- c = a - yv
190- pypto.assemble(c, [0, 0], z)
191- 
192- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
193- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
194- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
195- func = _run_merge(foo, x, y, z)
196- # Inner loop appears exactly once (not duplicated across the surrounding if branches).
197- assert len(_collect_stmts(func.body, ir.ForStmt)) == 2 # outer + inner, each single
198- 
199- 
200-def test_merge_pass5():
201- """An if that yields a value consumed after it: the consumer is sunk into both branches and the
202- branch-local def is used in each (SSA preserved via return_vars + yield).
203- """
204- 
205- def foo(x, y, z):
206- pypto.set_vec_tile_shapes(16, 16)
207- xv = pypto.view(x, [16, 16], [0, 0])
208- yv = pypto.view(y, [16, 16], [0, 0])
209- for i in pypto.loop(2):
210- if i == 0:
211- t = xv + yv
212- else:
213- t = xv - yv
214- r = t + xv # consumer of the if's result `t`
215- pypto.assemble(r, [0, 0], z)
216- 
217- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
218- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
219- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
220- func = _run_merge(foo, x, y, z)
221- # The value-producing if is preserved...
222- assert len(_collect_stmts(func.body, ir.IfStmt)) == 1
223- # ...and the consumer `r = t + xv` is duplicated into both branches (one ADD per branch).
224- adds = [op for op in _collect_stmts(func.body, ir.TensorOpStmt) if op.opcode == 'ADD']
225- assert len(adds) >= 2, f"expected the consumer sunk into both branches, got {len(adds)} ADD"
226- 
227- 
228-def test_merge_pass6():
229- """A nested if that exists only under one branch stays nested only under that branch's leaves."""
230- 
231- def foo(x, y, z):
232- pypto.set_vec_tile_shapes(16, 16)
233- xv = pypto.view(x, [16, 16], [0, 0])
234- yv = pypto.view(y, [16, 16], [0, 0])
235- for i in pypto.loop(2):
236- if i == 0:
237- t = xv + yv
238- if i == 1: # nested only inside the i == 0 branch
239- t = t + yv
240- else:
241- t = xv - yv
242- pypto.assemble(t, [0, 0], z)
243- 
244- x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
245- y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
246- z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
247- func = _run_merge(foo, x, y, z)
248- # Outer i == 0 plus the nested i == 1 under the else (where i != 0 keeps both); the nested if
249- # under i == 0 was pruned (0 == 1 impossible). Inspect via the logged IR.
250- assert len(_collect_stmts(func.body, ir.IfStmt)) == 1
251- 
252- 
253-def test_merge_pass7():
254- """A nested if that exists only under one branch stays nested only under that branch's leaves."""
255- 
256- def foo(x, y, z):
257- pypto.set_vec_tile_shapes(16, 16)
258- xv = pypto.view(x, [16, 16], [0, 0])
259- _yv = pypto.view(y, [16, 16], [0, 0])
260- for i in pypto.loop(x.shape[0], unroll_list=[4]):
261- if i == 0:
262- t = xv + 1
263- else:
264- t = xv - 1
265- t = t + 2
266- if i == x.shape[0] - 1:
267- t = xv + 1
268- else:
269- t = xv - 1
270- pypto.assemble(t, [0, 0], z)
271- 
272- x = pypto.Tensor([-1, 32], pypto.DT_FP32, 'x')
273- y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y')
274- z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z')
275- func = _run_merge(foo, x, y, z)
276- assert len(_collect_stmts(func.body, ir.IfStmt)) == 6
277- 
278- 
279-def test_merge_pass8():
280- """A nested if that exists only under one branch stays nested only under that branch's leaves."""
281- 
282- def foo(x, y, z):
283- pypto.set_vec_tile_shapes(16, 16)
284- xv = pypto.view(x, [16, 16], [0, 0])
285- _yv = pypto.view(y, [16, 16], [0, 0])
286- for i in pypto.loop(x.shape[0], unroll_list=[4]):
287- if pypto.is_loop_begin(i):
288- t = xv + 1
289- else:
290- t = xv - 1
291- t = t + 2
292- if pypto.is_loop_end(i):
293- t = xv + 1
294- else:
295- t = xv - 1
296- pypto.assemble(t, [0, 0], z)
297- 
298- x = pypto.Tensor([-1, 32], pypto.DT_FP32, 'x')
299- y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y')
300- z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z')
301- func = _run_merge(foo, x, y, z)
302- assert len(_collect_stmts(func.body, ir.IfStmt)) == 6
303- 
304- 
305-def test_unroll_list():
306- 
307- def foo(a, b, c):
308- m, n = a.shape[0], a.shape[1]
309- for x in pypto.loop(10):
310- for y in pypto.loop(10):
311- for z in pypto.loop(n):
312- cur_seq = m - (n - 1 - z)
313- k = (cur_seq + 32 - 1) // 32
314- for i in pypto.loop(k, unroll_list=[32]):
315- t = c + 1
316- if i == 0:
317- t = t + 1
318- else:
319- t = t + 2
320- if i == k - 1:
321- t = t + 3
322- else:
323- t = t + 4
324- b[:] = t
325- x = pypto.Tensor((-1, -1), pypto.DT_FP32)
326- y = pypto.Tensor((32, 32), pypto.DT_FP32)
327- z = pypto.Tensor((32, 32), pypto.DT_FP32)
328- func = _run_merge(foo, x, y, z)
329- ifops = _collect_stmts(func.body, ir.IfStmt)
330- assert len(ifops) == 6 # each unroll function has 3 if statements
331- 
332- 
333-def test_oi_update():
334- 
335- def foo(a, b):
336- n = pypto.symbolic_scalar("n")
337- for x in pypto.loop(10):
338- for y in pypto.loop(10):
339- oi_update = pypto.tensor([32, 32], pypto.DT_FP32, "oi_update")
340- for i in pypto.loop(n, unroll_list=[2]):
341- if i == 0:
342- oi_update[:] = a + 1
343- else:
344- oi_update[:] = oi_update - 1
345- if i + 1 >= n:
346- b[:] = oi_update // 2
347- 
348- y = pypto.Tensor((32, 32), pypto.DT_FP32)
349- z = pypto.Tensor((32, 32), pypto.DT_FP32)
350- _run_merge(foo, y, z)
351- 
352- 
353-def test_fillpad():
354- """A local defined only inside one branch (x) must not become a loop carry."""
355- 
356- def foo(a, b):
357- n = pypto.symbolic_scalar("n")
358- for i in pypto.loop(n, unroll_list=[2]):
359- if i == n-1:
360- x = pypto.full([32, 32], 0, pypto.DT_FP32)
361- b[:] = x + 1
362- 
363- y = pypto.Tensor((32, 32), pypto.DT_FP32)
364- z = pypto.Tensor((32, 32), pypto.DT_FP32)
365- _run_merge(foo, y, z)
@@ -0,0 +1,8 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_fillpad.pir→python/tests/ut/ir/test_merge_pass/test_fillpad.py+31-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(a@0: ir.Tensor, b@1: ir.Tensor):16def foo(a@0: ir.Tensor, b@1: ir.Tensor):
3 for loop_idx_12, (b_1,) in ir.range(0, (((n-0)/2)*2), 2, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 2}):17 for loop_idx_12, (b_1,) in ir.range(0, (((n-0)/2)*2), 2, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 2}):
@@ -17,3 +31,20 @@ def foo(a@0: ir.Tensor, b@1: ir.Tensor):
17 b_14 = ir.yield_(b_11@1)31 b_14 = ir.yield_(b_11@1)
18 b_16 = continue b_14@132 b_16 = continue b_14@1
19 return a@0, b_16@133 return a@0, b_16@1
34+""" # noqa: E501
35+ 
36+ 
37+def test_fillpad():
38+ """A local defined only inside one branch (x) must not become a loop carry."""
39+ 
40+ def foo(a, b):
41+ n = pypto.symbolic_scalar("n")
42+ for i in pypto.loop(n, unroll_list=[2]):
43+ if i == n-1:
44+ x = pypto.full([32, 32], 0, pypto.DT_FP32)
45+ b[:] = x + 1
46+ 
47+ y = pypto.Tensor((32, 32), pypto.DT_FP32)
48+ z = pypto.Tensor((32, 32), pypto.DT_FP32)
49+ func = run_merge_pass(foo, y, z)
50+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_merge_pass1.pir→python/tests/ut/ir/test_merge_pass/test_merge_pass1.py+39-0
@@ -1,3 +1,16 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+import pypto
10+ 
11+from ..test_common import check_snapshot, run_merge_pass
12+ 
13+ir = """
1@ir.function14@ir.function
2def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):15def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3 for loop_idx_10 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):16 for loop_idx_10 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
@@ -26,3 +39,29 @@ def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
26 ir.yield_()39 ir.yield_()
27 continue40 continue
28 return x@0, y@1, z@241 return x@0, y@1, z@2
42+"""
43+ 
44+ 
45+def test_merge_pass1():
46+ """A loop is a barrier (never duplicated into branches) and the pass recurses into its body."""
47+ 
48+ def foo(x, y, z):
49+ pypto.set_vec_tile_shapes(16, 16)
50+ for i in pypto.loop(2):
51+ xv = pypto.view(x, [16, 16], [0, 0])
52+ yv = pypto.view(y, [16, 16], [0, 0])
53+ if i == 0:
54+ t = xv + yv
55+ else:
56+ t = xv - yv
57+ if i == 1:
58+ t2 = t + xv
59+ else:
60+ t2 = t - xv
61+ pypto.assemble(t2, [0, 0], z)
62+ 
63+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
64+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
65+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
66+ func = run_merge_pass(foo, x, y, z)
67+ check_snapshot(func, ir)
@@ -0,0 +1,54 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
15+@ir.function
16+def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
17+ View_x@3 = VIEW(x@0)
18+ View_y@4 = VIEW(y@1)
19+ for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
20+ if (loop_idx_32==0):
21+ $1@6 = SUB(View_x@3, View_y@4)
22+ z@2 = ASSEMBLE($1@6)
23+ ir.yield_()
24+ else:
25+ $3@7 = ADD(View_x@3, View_y@4)
26+ z@2 = ASSEMBLE($3@7)
27+ ir.yield_()
28+ continue
29+ return x@0, y@1, z@2
30+"""
31+ 
32+ 
33+def test_merge_pass2():
34+ """Under `i == 0` the nested `i == 1` is UNSAT, so its branch is pruned (not 2^N leaves)."""
35+ 
36+ def foo(x, y, z):
37+ pypto.set_vec_tile_shapes(16, 16)
38+ xv = pypto.view(x, [16, 16], [0, 0])
39+ yv = pypto.view(y, [16, 16], [0, 0])
40+ for i in pypto.loop(2):
41+ if i == 0:
42+ if i == 1: # impossible under i == 0
43+ t = xv + yv # DEAD -> must be pruned
44+ else:
45+ t = xv - yv
46+ else:
47+ t = xv + yv
48+ pypto.assemble(t, [0, 0], z)
49+ 
50+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
51+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
52+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
53+ func = run_merge_pass(foo, x, y, z)
54+ check_snapshot(func, ir)
@@ -0,0 +1,47 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
15+@ir.function
16+def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
17+ View_x@3 = VIEW(x@0)
18+ View_y@4 = VIEW(y@1)
19+ for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
20+ $1@6 = SUB(View_x@3, View_y@4)
21+ z@2 = ASSEMBLE($1@6)
22+ continue
23+ return x@0, y@1, z@2
24+"""
25+ 
26+ 
27+def test_merge_pass3():
28+ """`i + 1 == 0` is impossible for i in {0, 1}: the solver models the loop range (i >= 0),
29+ proves the then-branch UNSAT, and prunes it -> the if collapses to the surviving else branch.
30+ """
31+ 
32+ def foo(x, y, z):
33+ pypto.set_vec_tile_shapes(16, 16)
34+ xv = pypto.view(x, [16, 16], [0, 0])
35+ yv = pypto.view(y, [16, 16], [0, 0])
36+ for i in pypto.loop(2):
37+ if i + 1 == 0: # UNSAT under the loop range i in {0, 1} -> then-branch pruned
38+ t = xv + yv
39+ else:
40+ t = xv - yv
41+ pypto.assemble(t, [0, 0], z)
42+ 
43+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
44+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
45+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
46+ func = run_merge_pass(foo, x, y, z)
47+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_merge_pass4.pir→python/tests/ut/ir/test_merge_pass/test_merge_pass4.py+42-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):16def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3 View_x@3 = VIEW(x@0)17 View_x@3 = VIEW(x@0)
@@ -22,3 +36,31 @@ def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
22 ir.yield_()36 ir.yield_()
23 continue37 continue
24 return x@0, y@1, z@238 return x@0, y@1, z@2
39+"""
40+ 
41+ 
42+def test_merge_pass4():
43+ """A loop between two ifs splits the region: each side is tree-built independently, loop stays single."""
44+ 
45+ def foo(x, y, z):
46+ pypto.set_vec_tile_shapes(16, 16)
47+ xv = pypto.view(x, [16, 16], [0, 0])
48+ yv = pypto.view(y, [16, 16], [0, 0])
49+ for i in pypto.loop(2):
50+ if i == 0:
51+ a = xv + yv
52+ else:
53+ a = xv - yv
54+ for j in pypto.loop(2): # inner loop in the middle -> barrier (self-contained)
55+ pypto.assemble(a, [j * 16, 0], z)
56+ if i == 1:
57+ c = a + yv
58+ else:
59+ c = a - yv
60+ pypto.assemble(c, [0, 0], z)
61+ 
62+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
63+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
64+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
65+ func = run_merge_pass(foo, x, y, z)
66+ check_snapshot(func, ir)
@@ -0,0 +1,56 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
15+@ir.function
16+def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
17+ View_x@3 = VIEW(x@0)
18+ View_y@4 = VIEW(y@1)
19+ for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
20+ if (loop_idx_32==0):
21+ $0@5 = ADD(View_x@3, View_y@4)
22+ $3@7 = ADD($0@5, View_x@3)
23+ z@2 = ASSEMBLE($3@7)
24+ ir.yield_()
25+ else:
26+ $1@6 = SUB(View_x@3, View_y@4)
27+ $3_1@7 = ADD($1@6, View_x@3)
28+ z@2 = ASSEMBLE($3_1@7)
29+ ir.yield_()
30+ continue
31+ return x@0, y@1, z@2
32+"""
33+ 
34+ 
35+def test_merge_pass5():
36+ """An if that yields a value consumed after it: the consumer is sunk into both branches and the
37+ branch-local def is used in each (SSA preserved via return_vars + yield).
38+ """
39+ 
40+ def foo(x, y, z):
41+ pypto.set_vec_tile_shapes(16, 16)
42+ xv = pypto.view(x, [16, 16], [0, 0])
43+ yv = pypto.view(y, [16, 16], [0, 0])
44+ for i in pypto.loop(2):
45+ if i == 0:
46+ t = xv + yv
47+ else:
48+ t = xv - yv
49+ r = t + xv # consumer of the if's result `t`
50+ pypto.assemble(r, [0, 0], z)
51+ 
52+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
53+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
54+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
55+ func = run_merge_pass(foo, x, y, z)
56+ check_snapshot(func, ir)
@@ -0,0 +1,53 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
15+@ir.function
16+def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
17+ View_x@3 = VIEW(x@0)
18+ View_y@4 = VIEW(y@1)
19+ for loop_idx_32 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
20+ if (loop_idx_32==0):
21+ $0@5 = ADD(View_x@3, View_y@4)
22+ z@2 = ASSEMBLE($0@5)
23+ ir.yield_()
24+ else:
25+ $3@7 = SUB(View_x@3, View_y@4)
26+ z@2 = ASSEMBLE($3@7)
27+ ir.yield_()
28+ continue
29+ return x@0, y@1, z@2
30+"""
31+ 
32+ 
33+def test_merge_pass6():
34+ """A nested if that exists only under one branch stays nested only under that branch's leaves."""
35+ 
36+ def foo(x, y, z):
37+ pypto.set_vec_tile_shapes(16, 16)
38+ xv = pypto.view(x, [16, 16], [0, 0])
39+ yv = pypto.view(y, [16, 16], [0, 0])
40+ for i in pypto.loop(2):
41+ if i == 0:
42+ t = xv + yv
43+ if i == 1: # nested only inside the i == 0 branch
44+ t = t + yv
45+ else:
46+ t = xv - yv
47+ pypto.assemble(t, [0, 0], z)
48+ 
49+ x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x')
50+ y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y')
51+ z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z')
52+ func = run_merge_pass(foo, x, y, z)
53+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_merge_pass7.pir→python/tests/ut/ir/test_merge_pass/test_merge_pass7.py+41-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):16def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3 View_x@3 = VIEW(x@0)17 View_x@3 = VIEW(x@0)
@@ -90,3 +104,30 @@ def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
90 ir.yield_()104 ir.yield_()
91 continue105 continue
92 return x@0, y@1, z@2106 return x@0, y@1, z@2
107+""" # noqa: E501
108+ 
109+ 
110+def test_merge_pass7():
111+ """A nested if that exists only under one branch stays nested only under that branch's leaves."""
112+ 
113+ def foo(x, y, z):
114+ pypto.set_vec_tile_shapes(16, 16)
115+ xv = pypto.view(x, [16, 16], [0, 0])
116+ _yv = pypto.view(y, [16, 16], [0, 0])
117+ for i in pypto.loop(x.shape[0], unroll_list=[4]):
118+ if i == 0:
119+ t = xv + 1
120+ else:
121+ t = xv - 1
122+ t = t + 2
123+ if i == x.shape[0] - 1:
124+ t = xv + 1
125+ else:
126+ t = xv - 1
127+ pypto.assemble(t, [0, 0], z)
128+ 
129+ x = pypto.Tensor([-1, 32], pypto.DT_FP32, 'x')
130+ y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y')
131+ z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z')
132+ func = run_merge_pass(foo, x, y, z)
133+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_merge_pass8.pir→python/tests/ut/ir/test_merge_pass/test_merge_pass8.py+41-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):16def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
3 View_x@3 = VIEW(x@0)17 View_x@3 = VIEW(x@0)
@@ -90,3 +104,30 @@ def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor):
90 ir.yield_()104 ir.yield_()
91 continue105 continue
92 return x@0, y@1, z@2106 return x@0, y@1, z@2
107+""" # noqa: E501
108+ 
109+ 
110+def test_merge_pass8():
111+ """A nested if that exists only under one branch stays nested only under that branch's leaves."""
112+ 
113+ def foo(x, y, z):
114+ pypto.set_vec_tile_shapes(16, 16)
115+ xv = pypto.view(x, [16, 16], [0, 0])
116+ _yv = pypto.view(y, [16, 16], [0, 0])
117+ for i in pypto.loop(x.shape[0], unroll_list=[4]):
118+ if pypto.is_loop_begin(i):
119+ t = xv + 1
120+ else:
121+ t = xv - 1
122+ t = t + 2
123+ if pypto.is_loop_end(i):
124+ t = xv + 1
125+ else:
126+ t = xv - 1
127+ pypto.assemble(t, [0, 0], z)
128+ 
129+ x = pypto.Tensor([-1, 32], pypto.DT_FP32, 'x')
130+ y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y')
131+ z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z')
132+ func = run_merge_pass(foo, x, y, z)
133+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_oi_update.pir→python/tests/ut/ir/test_merge_pass/test_oi_update.py+36-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(a@0: ir.Tensor, b@1: ir.Tensor):16def foo(a@0: ir.Tensor, b@1: ir.Tensor):
3 for loop_idx_10, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):17 for loop_idx_10, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
@@ -54,3 +68,25 @@ def foo(a@0: ir.Tensor, b@1: ir.Tensor):
54 b_22 = continue b_20@168 b_22 = continue b_20@1
55 b_24 = continue b_22@169 b_24 = continue b_22@1
56 return a@0, b_24@170 return a@0, b_24@1
71+""" # noqa: E501
72+ 
73+ 
74+def test_oi_update():
75+ 
76+ def foo(a, b):
77+ n = pypto.symbolic_scalar("n")
78+ for x in pypto.loop(10):
79+ for y in pypto.loop(10):
80+ oi_update = pypto.tensor([32, 32], pypto.DT_FP32, "oi_update")
81+ for i in pypto.loop(n, unroll_list=[2]):
82+ if i == 0:
83+ oi_update[:] = a + 1
84+ else:
85+ oi_update[:] = oi_update - 1
86+ if i + 1 >= n:
87+ b[:] = oi_update // 2
88+ 
89+ y = pypto.Tensor((32, 32), pypto.DT_FP32)
90+ z = pypto.Tensor((32, 32), pypto.DT_FP32)
91+ func = run_merge_pass(foo, y, z)
92+ check_snapshot(func, ir)
Rpython/tests/ut/ir/snapshot/test_merge_pass.test_unroll_list.pir→python/tests/ut/ir/test_merge_pass/test_unroll_list.py+42-0
@@ -1,3 +1,17 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+ 
12+from ..test_common import check_snapshot, run_merge_pass
13+ 
14+ir = """
1@ir.function15@ir.function
2def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor):16def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor):
3 for loop_idx_18, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):17 for loop_idx_18, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
@@ -307,3 +321,31 @@ def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor):
307 b_50 = continue b_48@1321 b_50 = continue b_48@1
308 b_52 = continue b_50@1322 b_52 = continue b_50@1
309 return a@0, b_52@1, c@2323 return a@0, b_52@1, c@2
324+""" # noqa: E501
325+ 
326+ 
327+def test_unroll_list():
328+ 
329+ def foo(a, b, c):
330+ m, n = a.shape[0], a.shape[1]
331+ for x in pypto.loop(10):
332+ for y in pypto.loop(10):
333+ for z in pypto.loop(n):
334+ cur_seq = m - (n - 1 - z)
335+ k = (cur_seq + 32 - 1) // 32
336+ for i in pypto.loop(k, unroll_list=[32]):
337+ t = c + 1
338+ if i == 0:
339+ t = t + 1
340+ else:
341+ t = t + 2
342+ if i == k - 1:
343+ t = t + 3
344+ else:
345+ t = t + 4
346+ b[:] = t
347+ x = pypto.Tensor((-1, -1), pypto.DT_FP32)
348+ y = pypto.Tensor((32, 32), pypto.DT_FP32)
349+ z = pypto.Tensor((32, 32), pypto.DT_FP32)
350+ func = run_merge_pass(foo, x, y, z)
351+ check_snapshot(func, ir)
@@ -6,7 +6,7 @@
6# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,6# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.7# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8# See LICENSE in the root of the software repository for the full text of the License.8# See LICENSE in the root of the software repository for the full text of the License.
9-from dataclasses import dataclass9+from dataclasses import dataclass, replace
10from types import SimpleNamespace10from types import SimpleNamespace
11 11 
12import pytest12import pytest
@@ -714,13 +714,21 @@ def test_lambda():
714 714 
715 def foo(x):715 def foo(x):
716 # lambda has args716 # lambda has args
717- def add1(a): return a + 1 # noqa: E731717+ def add1(a):
718+ return a + 1 # noqa: E731
719+ 
718 ans.append(add1(x))720 ans.append(add1(x))
721+ 
719 # lambda with capture args722 # lambda with capture args
720- def addx(a): return x + a # noqa: E731723+ def addx(a):
724+ return x + a # noqa: E731
725+ 
721 ans.append(addx(1))726 ans.append(addx(1))
727+ 
722 # lambda with default args728 # lambda with default args
723- def add_def(a, b=10): return a + b # noqa: E731729+ def add_def(a, b=10):
730+ return a + b # noqa: E731
731+ 
724 ans.append(add_def(5))732 ans.append(add_def(5))
725 ans.append(add_def(5, 15))733 ans.append(add_def(5, 15))
726 734 
@@ -928,6 +936,7 @@ def test_tensor_move1():
928 def foo(a, b):936 def foo(a, b):
929 for _ in pypto.loop(10, unroll_list=[4]):937 for _ in pypto.loop(10, unroll_list=[4]):
930 b[:] = a + 1938 b[:] = a + 1
939+ 
931 x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')940 x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
932 y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')941 y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
933 func = pil.compile(foo, x, y)942 func = pil.compile(foo, x, y)
@@ -1085,6 +1094,7 @@ def test_function_call():
1085 t2 = b1094 t2 = b
1086 for _ in pypto.loop(1):1095 for _ in pypto.loop(1):
1087 bar(Data(data=[t1, t2]))1096 bar(Data(data=[t1, t2]))
1097+ 
1088 pil.compile(foo, 1, 2)1098 pil.compile(foo, 1, 2)
1089 1099 
1090 1100 
@@ -1101,10 +1111,12 @@ def test_getattr_and_delattr():
1101 # getattr 3-arg, attribute missing: returns the default1111 # getattr 3-arg, attribute missing: returns the default
1102 res.append(getattr(pypto, "DT_NOT_EXIST", pypto.DT_UINT8))1112 res.append(getattr(pypto, "DT_NOT_EXIST", pypto.DT_UINT8))
1103 # getattr 3-arg inside a dict literal (mirrors get_pypto_dtype usage)1113 # getattr 3-arg inside a dict literal (mirrors get_pypto_dtype usage)
1104- res.append({1114+ res.append(
1105- "present": getattr(pypto, "DT_FP32", pypto.DT_UINT8),1115+ {
1106- "missing": getattr(pypto, "DT_NOT_EXIST", pypto.DT_UINT8),1116+ "present": getattr(pypto, "DT_FP32", pypto.DT_UINT8),
1107- })1117+ "missing": getattr(pypto, "DT_NOT_EXIST", pypto.DT_UINT8),
1118+ }
1119+ )
1108 # delattr 2-arg: removes the attribute from the object1120 # delattr 2-arg: removes the attribute from the object
1109 obj = SimpleNamespace(a=1, b=2)1121 obj = SimpleNamespace(a=1, b=2)
1110 delattr(obj, "a")1122 delattr(obj, "a")
@@ -1119,3 +1131,34 @@ def test_getattr_and_delattr():
1119 assert res[3]["missing"] == pypto.DT_UINT81131 assert res[3]["missing"] == pypto.DT_UINT8
1120 assert res[4] is True1132 assert res[4] is True
1121 assert res[5] == 21133 assert res[5] == 2
1134+ 
1135+ 
1136+@dataclass
1137+class Context:
1138+ data: int
1139+ 
1140+ 
1141+def test_replace_in_loop():
1142+ 
1143+ def foo():
1144+ ctx = Context(data=1)
1145+ for _ in pypto.loop(1):
1146+ ctx = replace(ctx, data=2)
1147+ assert ctx.data == 2
1148+ 
1149+ pil.compile(foo, has_move=False)
1150+ 
1151+ 
1152+def test_replace_in_if_else():
1153+ 
1154+ def foo(n):
1155+ ctx = Context(data=1)
1156+ for i in pypto.loop(n):
1157+ if i:
1158+ ctx = replace(ctx, data=2)
1159+ else:
1160+ ctx = replace(ctx, data=3)
1161+ # used after the symbolic if/else; both branches keep data > 0
1162+ assert ctx.data > 0
1163+ 
1164+ pil.compile(foo, 10)