Merged
feat(machine): Add yield scalar expr support for IfStmt and ForStmt #5465
feat(machine): Add yield scalar expr support for IfStmt and ForStmt #5465
Merged
gaoxingwangAdd on Aug 15
Total: 4 files changed+371-6
@@ -40,6 +40,12 @@ void FindExprFromForStmt(IrBackendContext& ctx, FunctionCache& cache, Linker& li
40{40{
41 SymbolicScalar iterSymbol(forStmt->loopVar_->name_);41 SymbolicScalar iterSymbol(forStmt->loopVar_->name_);
42 linker.AddSymbol(iterSymbol);42 linker.AddSymbol(iterSymbol);
43+ for (auto& retVar : forStmt->returnVars_) {
44+ if (ir::As<ir::ScalarType>(retVar->GetType())) {
45+ SymbolicScalar retSymbol(retVar->name_);
46+ linker.AddSymbol(retSymbol);
47+ }
48+ }
43 Function* loopFunc = IrBuildVirtualLoopFunc(ctx, forStmt.get(), dynFunc);49 Function* loopFunc = IrBuildVirtualLoopFunc(ctx, forStmt.get(), dynFunc);
44 linker.AddPrimaryExpressionForLoopBes(loopFunc, ExprPtrToSymbolicScalar(forStmt->start_));50 linker.AddPrimaryExpressionForLoopBes(loopFunc, ExprPtrToSymbolicScalar(forStmt->start_));
45 linker.AddPrimaryExpressionForLoopBes(loopFunc, ExprPtrToSymbolicScalar(forStmt->stop_));51 linker.AddPrimaryExpressionForLoopBes(loopFunc, ExprPtrToSymbolicScalar(forStmt->stop_));
@@ -52,6 +58,12 @@ void FindExprFromForStmt(IrBackendContext& ctx, FunctionCache& cache, Linker& li
52void FindExprFromIfStmt(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, const ir::IfStmtPtr& ifStmt,58void FindExprFromIfStmt(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, const ir::IfStmtPtr& ifStmt,
53 Function* dynFunc, std::vector<ir::ExprPtr>& condStack)59 Function* dynFunc, std::vector<ir::ExprPtr>& condStack)
54{60{
61+ for (auto& retVar : ifStmt->returnVars_) {
62+ if (ir::As<ir::ScalarType>(retVar->GetType())) {
63+ SymbolicScalar retSymbol(retVar->name_);
64+ linker.AddSymbol(retSymbol);
65+ }
66+ }
55 condStack.push_back(ifStmt->condition_);67 condStack.push_back(ifStmt->condition_);
56 FindExprFromIRStmt(ctx, cache, linker, ifStmt->thenBody_, dynFunc, condStack);68 FindExprFromIRStmt(ctx, cache, linker, ifStmt->thenBody_, dynFunc, condStack);
57 if (ifStmt->elseBody_) {69 if (ifStmt->elseBody_) {
@@ -89,12 +101,12 @@ void VisitIfStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Link
89 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "if (" << cond << ") {\n";101 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "if (" << cond << ") {\n";
90 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, ifStmt->thenBody_, dynFunc, slotIdxMapping, group,102 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, ifStmt->thenBody_, dynFunc, slotIdxMapping, group,
91 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,103 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,
92- exprSrcFiles, valDependTensorMeta);104+ exprSrcFiles, valDependTensorMeta, ifStmt->returnVars_);
93 if (ifStmt->elseBody_) {105 if (ifStmt->elseBody_) {
94 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "} else {\n";106 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "} else {\n";
95 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, ifStmt->elseBody_.value(), dynFunc, slotIdxMapping,107 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, ifStmt->elseBody_.value(), dynFunc, slotIdxMapping,
96 group, rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1,108 group, rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1,
97- expName, exprSrcFiles, valDependTensorMeta);109+ expName, exprSrcFiles, valDependTensorMeta, ifStmt->returnVars_);
98 }110 }
99 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "}\n";111 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "}\n";
100}112}
@@ -272,6 +284,16 @@ void FindExprFromIRStmt(IrBackendContext& ctx, FunctionCache& cache, Linker& lin
272 case ir::ObjectKind::TensorOpStmt:284 case ir::ObjectKind::TensorOpStmt:
273 FindExprFromTensorOpStmt(cache, linker, stmt, dynFunc, condStack);285 FindExprFromTensorOpStmt(cache, linker, stmt, dynFunc, condStack);
274 break;286 break;
287+ case ir::ObjectKind::YieldStmt: {
288+ if (auto yieldStmt = ir::As<ir::YieldStmt>(stmt)) {
289+ for (auto& val : yieldStmt->value_) {
290+ if (ir::As<ir::ScalarType>(val->GetType())) {
291+ linker.GetSymbolTable()->AddSymbolFromExpression(ExprPtrToSymbolicScalar(val));
292+ }
293+ }
294+ }
295+ break;
296+ }
275 default:297 default:
276 break;298 break;
277 }299 }
@@ -343,7 +365,7 @@ void VisitForStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Lin
343 365 
344 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, forStmt->body_, dynFunc, slotIdxMapping, group,366 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, forStmt->body_, dynFunc, slotIdxMapping, group,
345 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,367 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,
346- exprSrcFiles, valDependTensorMeta);368+ exprSrcFiles, valDependTensorMeta, forStmt->returnVars_);
347 369 
348 if (needCrossDie) {370 if (needCrossDie) {
349 controlFlowOss << std::setw((indent + 1) * TABSIZE) << ' ' << "RUNTIME_ClearLoopDieId(" << iterSymbolName371 controlFlowOss << std::setw((indent + 1) * TABSIZE) << ' ' << "RUNTIME_ClearLoopDieId(" << iterSymbolName
@@ -363,7 +385,8 @@ void VisitIRStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Link
363 std::unordered_map<Function*, Function*>& rootTileDict,385 std::unordered_map<Function*, Function*>& rootTileDict,
364 std::ostringstream& controlFlowOss, std::ostringstream& expressionOss,386 std::ostringstream& controlFlowOss, std::ostringstream& expressionOss,
365 std::ostringstream& exprHeaderOss, int indent, const std::string& expName,387 std::ostringstream& exprHeaderOss, int indent, const std::string& expName,
366- std::vector<std::string>& exprSrcFiles, ValDependTensorMeta& valDependTensorMeta)388+ std::vector<std::string>& exprSrcFiles, ValDependTensorMeta& valDependTensorMeta,
389+ const std::vector<ir::VarPtr>& currentReturnVars)
367{390{
368 if (!stmt) {391 if (!stmt) {
369 return;392 return;
@@ -374,7 +397,7 @@ void VisitIRStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Link
374 for (auto& child : seq->stmts_) {397 for (auto& child : seq->stmts_) {
375 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, child, dynFunc, slotIdxMapping, group,398 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, child, dynFunc, slotIdxMapping, group,
376 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent,399 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent,
377- expName, exprSrcFiles, valDependTensorMeta);400+ expName, exprSrcFiles, valDependTensorMeta, currentReturnVars);
378 }401 }
379 }402 }
380 break;403 break;
@@ -410,6 +433,21 @@ void VisitIRStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Link
410 BuildControlFlow(cfCtx, pathFunc, indent);433 BuildControlFlow(cfCtx, pathFunc, indent);
411 break;434 break;
412 }435 }
436+ case ir::ObjectKind::YieldStmt: {
437+ if (auto yieldStmt = ir::As<ir::YieldStmt>(stmt)) {
438+ const auto* getInputCseMap = ResolveGetInputCseMap(ctx);
439+ for (size_t i = 0; i < yieldStmt->value_.size() && i < currentReturnVars.size(); i++) {
440+ if (ir::As<ir::ScalarType>(yieldStmt->value_[i]->GetType()) &&
441+ ir::As<ir::ScalarType>(currentReturnVars[i]->GetType())) {
442+ auto yieldExpr = ExprPtrToSymbolicScalar(yieldStmt->value_[i]);
443+ auto exprStr = SymbolicExpressionTable::BuildExpression(yieldExpr.Raw(), getInputCseMap);
444+ controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "VALUE_" << currentReturnVars[i]->name_
445+ << " = " << exprStr << ";\n";
446+ }
447+ }
448+ }
449+ break;
450+ }
413 default:451 default:
414 break;452 break;
415 }453 }
@@ -67,7 +67,8 @@ void VisitIRStmtForControlFlow(IrBackendContext& ctx, FunctionCache& cache, Link
67 std::unordered_map<Function*, Function*>& rootTileDict,67 std::unordered_map<Function*, Function*>& rootTileDict,
68 std::ostringstream& controlFlowOss, std::ostringstream& expressionOss,68 std::ostringstream& controlFlowOss, std::ostringstream& expressionOss,
69 std::ostringstream& exprHeaderOss, int indent, const std::string& expName,69 std::ostringstream& exprHeaderOss, int indent, const std::string& expName,
70- std::vector<std::string>& exprSrcFiles, ValDependTensorMeta& valDependTensorMeta);70+ std::vector<std::string>& exprSrcFiles, ValDependTensorMeta& valDependTensorMeta,
71+ const std::vector<ir::VarPtr>& currentReturnVars = {});
71 72 
72void BuildControlFlowFromIR(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, const std::string& sectionName,73void BuildControlFlowFromIR(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, const std::string& sectionName,
73 Function* func, std::unordered_map<int, int>& slotIdxMapping,74 Function* func, std::unordered_map<int, int>& slotIdxMapping,
@@ -49,6 +49,11 @@ ir::VarPtr MakeVar(const std::string& name)
49 return std::make_shared<ir::Var>(name, std::make_shared<ir::ScalarType>(ir::DataType::INT64), Sp());49 return std::make_shared<ir::Var>(name, std::make_shared<ir::ScalarType>(ir::DataType::INT64), Sp());
50}50}
51 51 
52+ir::VarPtr MakeTensorVar(const std::string& name)
53+{
54+ return std::make_shared<ir::Var>(name, std::make_shared<ir::LogicalTensorType>(), Sp());
55+}
56+ 
52ir::StmtPtr MakeTensorOpStmt(const std::string& opcode, const std::vector<std::pair<std::string, std::any>>& attrs = {})57ir::StmtPtr MakeTensorOpStmt(const std::string& opcode, const std::vector<std::pair<std::string, std::any>>& attrs = {})
53{58{
54 return std::make_shared<ir::TensorOpStmt>(std::vector<ir::VarPtr>{}, nullptr, opcode, std::vector<ir::ExprPtr>{},59 return std::make_shared<ir::TensorOpStmt>(std::vector<ir::VarPtr>{}, nullptr, opcode, std::vector<ir::ExprPtr>{},
@@ -62,11 +67,29 @@ ir::StmtPtr MakeForStmt(ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop,
62 std::vector<ir::VarPtr>{}, Sp(), attrs);67 std::vector<ir::VarPtr>{}, Sp(), attrs);
63}68}
64 69 
70+ir::StmtPtr MakeForStmtWithReturn(ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop, ir::ExprPtr step,
71+ ir::StmtPtr body, std::vector<ir::VarPtr> returnVars)
72+{
73+ return std::make_shared<ir::ForStmt>(loopVar, start, stop, step, std::vector<ir::IterArgPtr>{}, body,
74+ std::move(returnVars), Sp());
75+}
76+ 
65ir::StmtPtr MakeIfStmt(ir::ExprPtr cond, ir::StmtPtr thenBody, std::optional<ir::StmtPtr> elseBody = std::nullopt)77ir::StmtPtr MakeIfStmt(ir::ExprPtr cond, ir::StmtPtr thenBody, std::optional<ir::StmtPtr> elseBody = std::nullopt)
66{78{
67 return std::make_shared<ir::IfStmt>(cond, thenBody, elseBody, std::vector<ir::VarPtr>{}, Sp());79 return std::make_shared<ir::IfStmt>(cond, thenBody, elseBody, std::vector<ir::VarPtr>{}, Sp());
68}80}
69 81 
82+ir::StmtPtr MakeIfStmtWithReturn(ir::ExprPtr cond, ir::StmtPtr thenBody, std::optional<ir::StmtPtr> elseBody,
Jie Yin
Jie YinJie YinAug 18

这些用 ir builder 提供的接口吧?

likedislike
gaoxingwang
gaoxingwang
Aug 18 Comments:
likedislike
83+ std::vector<ir::VarPtr> returnVars)
84+{
85+ return std::make_shared<ir::IfStmt>(cond, thenBody, elseBody, std::move(returnVars), Sp());
86+}
87+ 
88+ir::StmtPtr MakeYieldStmt(std::vector<ir::ExprPtr> values)
89+{
90+ return std::make_shared<ir::YieldStmt>(std::move(values), Sp());
91+}
92+ 
70ir::StmtPtr MakeSeqStmts(std::vector<ir::StmtPtr> stmts)93ir::StmtPtr MakeSeqStmts(std::vector<ir::StmtPtr> stmts)
71{94{
72 auto seq = std::make_shared<ir::SeqStmts>(std::move(stmts), Sp());95 auto seq = std::make_shared<ir::SeqStmts>(std::move(stmts), Sp());
@@ -611,3 +634,228 @@ TEST_F(TestSuite_IrBackend, BuildControlFlowFromIR_EmitsGetInputCseStackInits)
611 std::string rmCmd = "rm -rf " + workDir;634 std::string rmCmd = "rm -rf " + workDir;
612 ASSERT_EQ(system(rmCmd.c_str()), 0);635 ASSERT_EQ(system(rmCmd.c_str()), 0);
613}636}
637+ 
638+TEST_F(TestSuite_IrBackend, FindExprFromIfStmt_RegistersReturnVars)
639+{
640+ IrBackendContext irBackendCtx;
641+ DynFuncFixture dynFixture;
642+ LinkerFixture linkerFixture;
643+ FunctionCache cache;
644+ std::vector<ir::ExprPtr> condStack;
645+ 
646+ auto retVarA = MakeVar("a1");
647+ auto retVarB = MakeVar("b1");
648+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({}), std::nullopt, {retVarA, retVarB});
649+ 
650+ FindExprFromIRStmt(irBackendCtx, cache, *linkerFixture.linker, ifStmt, dynFixture.dynFunc.get(), condStack);
651+ 
652+ const auto& symTable = linkerFixture.linker->GetSymbolTable()->GetSymbolTable();
653+ EXPECT_TRUE(symTable.count("a1") > 0);
654+ EXPECT_TRUE(symTable.count("b1") > 0);
655+}
656+ 
657+TEST_F(TestSuite_IrBackend, FindExprFromIRStmt_YieldStmtCollectsSymbols)
658+{
659+ IrBackendContext irBackendCtx;
660+ DynFuncFixture dynFixture;
661+ LinkerFixture linkerFixture;
662+ FunctionCache cache;
663+ std::vector<ir::ExprPtr> condStack;
664+ 
665+ auto yield = MakeYieldStmt({MakeGetInputShapeDimExpr("ARG_x", 0)});
666+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({yield}), std::nullopt, {MakeVar("c1")});
667+ 
668+ FindExprFromIRStmt(irBackendCtx, cache, *linkerFixture.linker, ifStmt, dynFixture.dynFunc.get(), condStack);
669+ 
670+ const auto& symTable = linkerFixture.linker->GetSymbolTable()->GetSymbolTable();
671+ EXPECT_TRUE(symTable.count("c1") > 0);
672+ EXPECT_TRUE(symTable.count("RUNTIME_GetInputShapeDim") > 0);
673+}
674+ 
675+TEST_F(TestSuite_IrBackend, VisitIRStmtForControlFlow_IfStmtYieldImmediate)
676+{
677+ DynFuncFixture dynFixture;
678+ LinkerFixture linkerFixture;
679+ ControlFlowCtx ctx;
680+ 
681+ auto retVar = MakeVar("a1");
682+ auto yield = MakeYieldStmt({MakeImmediateExpr(2048)});
683+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({yield}), std::nullopt, {retVar});
684+ 
685+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", ifStmt,
686+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
687+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
688+ ctx.meta);
689+ 
690+ auto output = ctx.controlFlowOss.str();
691+ EXPECT_TRUE(output.find("VALUE_a1 = 2048;") != std::string::npos);
692+}
693+ 
694+TEST_F(TestSuite_IrBackend, VisitIRStmtForControlFlow_IfStmtYieldSymbolicExpr)
695+{
696+ DynFuncFixture dynFixture;
697+ LinkerFixture linkerFixture;
698+ ControlFlowCtx ctx;
699+ 
700+ auto retVar = MakeVar("c1");
701+ auto yield = MakeYieldStmt({MakeSymbolExpr("some_var")});
702+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({yield}), std::nullopt, {retVar});
703+ 
704+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", ifStmt,
705+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
706+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
707+ ctx.meta);
708+ 
709+ auto output = ctx.controlFlowOss.str();
710+ EXPECT_TRUE(output.find("VALUE_c1 = VALUE_some_var;") != std::string::npos);
711+}
712+ 
713+TEST_F(TestSuite_IrBackend, VisitIRStmtForControlFlow_NestedIfStmtYieldIsolation)
714+{
715+ DynFuncFixture dynFixture;
716+ LinkerFixture linkerFixture;
717+ ControlFlowCtx ctx;
718+ 
719+ auto innerYield = MakeYieldStmt({MakeImmediateExpr(1)});
720+ auto innerIf = MakeIfStmtWithReturn(MakeSymbolExpr("inner_cond"), MakeSeqStmts({innerYield}), std::nullopt,
721+ {MakeVar("a")});
722+ auto outerYield = MakeYieldStmt({MakeImmediateExpr(2)});
723+ auto outerIf = MakeIfStmtWithReturn(MakeSymbolExpr("outer_cond"), MakeSeqStmts({innerIf, outerYield}), std::nullopt,
724+ {MakeVar("x")});
725+ 
726+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", outerIf,
727+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
728+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
729+ ctx.meta);
730+ 
731+ auto output = ctx.controlFlowOss.str();
732+ EXPECT_TRUE(output.find("VALUE_a = 1;") != std::string::npos);
733+ EXPECT_TRUE(output.find("VALUE_x = 2;") != std::string::npos);
734+}
735+ 
736+TEST_F(TestSuite_IrBackend, VisitIRStmtForControlFlow_IfStmtNoReturnVarsBackwardCompat)
737+{
738+ DynFuncFixture dynFixture;
739+ LinkerFixture linkerFixture;
740+ ControlFlowCtx ctx;
741+ 
742+ auto yield = MakeYieldStmt({MakeImmediateExpr(42)});
743+ auto ifStmt = MakeIfStmt(MakeSymbolExpr("cond"), MakeSeqStmts({yield}));
744+ 
745+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", ifStmt,
746+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
747+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
748+ ctx.meta);
749+ 
750+ auto output = ctx.controlFlowOss.str();
751+ EXPECT_TRUE(output.find("= 42;") == std::string::npos);
752+}
753+ 
754+TEST_F(TestSuite_IrBackend, FindExprFromIfStmt_SkipsTensorReturnVars)
755+{
756+ IrBackendContext irBackendCtx;
757+ DynFuncFixture dynFixture;
758+ LinkerFixture linkerFixture;
759+ FunctionCache cache;
760+ std::vector<ir::ExprPtr> condStack;
761+ 
762+ auto scalarRet = MakeVar("scalar_a");
763+ auto tensorRet = MakeTensorVar("tensor_b");
764+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({}), std::nullopt, {scalarRet, tensorRet});
765+ 
766+ FindExprFromIRStmt(irBackendCtx, cache, *linkerFixture.linker, ifStmt, dynFixture.dynFunc.get(), condStack);
767+ 
768+ const auto& symTable = linkerFixture.linker->GetSymbolTable()->GetSymbolTable();
769+ EXPECT_TRUE(symTable.count("scalar_a") > 0);
770+ EXPECT_TRUE(symTable.count("tensor_b") == 0);
771+}
772+ 
773+TEST_F(TestSuite_IrBackend, VisitIRStmtForControlFlow_IfStmtYieldSkipsTensor)
774+{
775+ DynFuncFixture dynFixture;
776+ LinkerFixture linkerFixture;
777+ ControlFlowCtx ctx;
778+ 
779+ auto scalarRet = MakeVar("scalar_a");
780+ auto tensorRet = MakeTensorVar("tensor_b");
781+ auto scalarYield = MakeImmediateExpr(100);
782+ auto tensorYield = MakeTensorVar("tensor_val");
783+ auto yield = MakeYieldStmt({scalarYield, tensorYield});
784+ auto ifStmt = MakeIfStmtWithReturn(MakeSymbolExpr("cond"), MakeSeqStmts({yield}), std::nullopt,
785+ {scalarRet, tensorRet});
786+ 
787+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", ifStmt,
788+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
789+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
790+ ctx.meta);
791+ 
792+ auto output = ctx.controlFlowOss.str();
793+ EXPECT_TRUE(output.find("VALUE_scalar_a = 100;") != std::string::npos);
794+ EXPECT_TRUE(output.find("VALUE_tensor_b") == std::string::npos);
795+}
796+ 
797+TEST_F(TestSuite_IrBackend, FindExprFromForStmt_RegistersScalarReturnVars)
798+{
799+ IrBackendContext irBackendCtx;
800+ DynFuncFixture dynFixture;
801+ LinkerFixture linkerFixture;
802+ FunctionCache cache;
803+ 
804+ auto loopVar = MakeVar("loop_idx");
805+ auto scalarRet = MakeVar("acc");
806+ auto tensorRet = MakeTensorVar("tensor_out");
807+ auto forStmt = MakeForStmtWithReturn(loopVar, MakeImmediateExpr(0), MakeImmediateExpr(10), MakeImmediateExpr(1),
808+ MakeSeqStmts({}), {scalarRet, tensorRet});
809+ 
810+ std::vector<ir::ExprPtr> condStack;
811+ FindExprFromIRStmt(irBackendCtx, cache, *linkerFixture.linker, forStmt, dynFixture.dynFunc.get(), condStack);
812+ 
813+ const auto& symTable = linkerFixture.linker->GetSymbolTable()->GetSymbolTable();
814+ EXPECT_TRUE(symTable.count("loop_idx") > 0);
815+ EXPECT_TRUE(symTable.count("acc") > 0);
816+ EXPECT_TRUE(symTable.count("tensor_out") == 0);
817+}
818+ 
819+TEST_F(TestSuite_IrBackend, VisitForStmtForControlFlow_YieldScalarReturnVar)
820+{
821+ DynFuncFixture dynFixture;
822+ LinkerFixture linkerFixture;
823+ ControlFlowCtx ctx;
824+ 
825+ auto loopVar = MakeVar("loop_idx");
826+ auto retVar = MakeVar("counter");
827+ auto yield = MakeYieldStmt({MakeImmediateExpr(42)});
828+ auto forStmt = MakeForStmtWithReturn(loopVar, MakeImmediateExpr(0), MakeImmediateExpr(10), MakeImmediateExpr(1),
829+ MakeSeqStmts({yield}), {retVar});
830+ 
831+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", forStmt,
832+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
833+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
834+ ctx.meta);
835+ 
836+ auto output = ctx.controlFlowOss.str();
837+ EXPECT_TRUE(output.find("VALUE_counter = 42;") != std::string::npos);
838+}
839+ 
840+TEST_F(TestSuite_IrBackend, VisitForStmtForControlFlow_YieldSkipsTensor)
841+{
842+ DynFuncFixture dynFixture;
843+ LinkerFixture linkerFixture;
844+ ControlFlowCtx ctx;
845+ 
846+ auto loopVar = MakeVar("loop_idx");
847+ auto scalarRet = MakeVar("acc");
848+ auto tensorRet = MakeTensorVar("tensor_out");
849+ auto yield = MakeYieldStmt({MakeImmediateExpr(99), MakeTensorVar("tensor_val")});
850+ auto forStmt = MakeForStmtWithReturn(loopVar, MakeImmediateExpr(0), MakeImmediateExpr(10), MakeImmediateExpr(1),
851+ MakeSeqStmts({yield}), {scalarRet, tensorRet});
852+ 
853+ VisitIRStmtForControlFlow(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", forStmt,
854+ dynFixture.dynFunc.get(), ctx.slotIdxMapping, ctx.group, ctx.rootTileDict,
855+ ctx.controlFlowOss, ctx.expressionOss, ctx.exprHeaderOss, 1, "expr", ctx.exprSrcFiles,
856+ ctx.meta);
857+ 
858+ auto output = ctx.controlFlowOss.str();
859+ EXPECT_TRUE(output.find("VALUE_acc = 99;") != std::string::npos);
860+ EXPECT_TRUE(output.find("VALUE_tensor_out") == std::string::npos);
861+}
@@ -0,0 +1,78 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software; you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Test yield scalar in controlFlow-level constructs.
12+ 
13+Covers if/else inside for loop body yielding both constant and symbolic
14+expression scalars, used as inner loop bounds.
15+"""
16+ 
17+import os
18+ 
19+from numpy.testing import assert_allclose
20+import torch
21+ 
22+import pypto
23+ 
24+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
25+ 
26+ 
27+@pypto.frontend.jit()
28+def yield_const_and_symbolic_kernel(
29+ x: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32),
30+ out: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32),
31+):
32+ """if/else yields constant (step) and symbolic expression (stop), both as loop bounds."""
33+ m = x.shape[0]
34+ n = 128
35+ 
36+ pypto.set_vec_tile_shapes(1, 128)
37+ 
38+ for b_idx in pypto.loop(0, m, 32, name="OUTER_LOOP", idx_name="b_idx"):
39+ if pypto.cond(b_idx < m // 2):
40+ step_val = 1
41+ stop_val = b_idx + 32
42+ else:
43+ step_val = 2
44+ stop_val = b_idx + 16
45+ 
46+ for s_idx in pypto.loop(b_idx, stop_val, step_val, name="INNER_LOOP", idx_name="s_idx"):
47+ x_view = pypto.view(x, [1, n], [s_idx, 0])
48+ result = pypto.add(x_view, pypto.full([1, n], 1.0, pypto.DT_FP32))
49+ pypto.assemble(result, [s_idx, 0], out)
50+ 
51+ 
52+def test_yield_const_and_symbolic():
53+ """Verify VALUE_step_val = 1; and VALUE_stop_val = expr; in controlFlow cpp."""
54+ torch.npu.set_device(ST_DEVICE_ID)
55+ 
56+ m, n = 64, 128
57+ dtype = torch.float32
58+ 
59+ x = torch.randn(m, n, dtype=dtype).npu()
60+ out = torch.zeros(m, n, dtype=dtype).npu()
61+ 
62+ yield_const_and_symbolic_kernel(x, out)
63+ 
64+ torch.npu.synchronize()
65+ 
66+ golden = torch.zeros(m, n, dtype=dtype)
67+ for b_idx in range(0, m, 32):
68+ if b_idx < m // 2:
69+ step_val, stop_val = 1, b_idx + 32
70+ else:
71+ step_val, stop_val = 2, b_idx + 16
72+ for s_idx in range(b_idx, stop_val, step_val):
73+ golden[s_idx, :] = x[s_idx, :] + 1.0
74+ assert_allclose(out.cpu().numpy(), golden.cpu().numpy(), atol=1e-5, rtol=1e-5)
75+ 
76+ 
77+if __name__ == "__main__":
78+ test_yield_const_and_symbolic()