Merged
feat(IR): Add ir text serialization #5455
Jie YinAdd on Aug 14
feat(IR): Add ir text serialization #5455
Merged
Jie YinAdd on Aug 14
Total: 24 files changed+3016-90
@@ -108,6 +108,7 @@ frontend@pypto:
108 src:108 src:
109 release:109 release:
110 - framework/include/core/any_cast.h110 - framework/include/core/any_cast.h
111+ - framework/include/core/bimap.h
111 - framework/include/core/common.h112 - framework/include/core/common.h
112 - framework/include/core/dtype.h113 - framework/include/core/dtype.h
113 - framework/include/core/error.h114 - framework/include/core/error.h
@@ -0,0 +1,64 @@
1+/**
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+ 
11+/*!
12+ * \file bimap.h
13+ * \brief Bidirectional map template (key <-> string).
14+ */
15+ 
16+#pragma once
17+ 
18+#include <string>
19+#include <unordered_map>
20+#include <utility>
21+ 
22+namespace npu {
23+namespace tile_fwk {
24+ 
25+template <typename T>
26+class BiMap {
27+public:
28+ BiMap(const std::initializer_list<std::pair<T, std::string>>& init)
29+ {
30+ for (const auto& [i, s] : init) {
31+ type2strDict[i] = s;
32+ str2typeDict[s] = i;
33+ }
34+ }
35+ 
36+ bool Count(T key) const { return type2strDict.count(key); }
37+ 
38+ bool Count(const std::string& key) const { return str2typeDict.count(key); }
39+ 
40+ const std::string& Find(T key, const std::string& defaultValue = "") const
41+ {
42+ if (type2strDict.count(key)) {
43+ return type2strDict.find(key)->second;
44+ } else {
45+ return defaultValue;
46+ }
47+ }
48+ 
49+ T Find(const std::string& key, T defaultValue) const
50+ {
51+ if (str2typeDict.count(key)) {
52+ return str2typeDict.find(key)->second;
53+ } else {
54+ return defaultValue;
55+ }
56+ }
57+ 
58+private:
59+ std::unordered_map<T, std::string> type2strDict;
60+ std::unordered_map<std::string, T> str2typeDict;
61+};
62+ 
63+} // namespace tile_fwk
64+} // namespace npu
@@ -21,6 +21,28 @@
21#include <cstdint>21#include <cstdint>
22#include <string>22#include <string>
23 23 
24+#include "core/bimap.h"
25+ 
26+// C-style type strings returned by DataType::ToCTypeString()
27+#define IR_KW_TYPE_BOOL "bool"
28+#define IR_KW_TYPE_INT8 "int8_t"
29+#define IR_KW_TYPE_INT16 "int16_t"
30+#define IR_KW_TYPE_INT32 "int32_t"
31+#define IR_KW_TYPE_INT64 "int64_t"
32+#define IR_KW_TYPE_UINT8 "uint8_t"
33+#define IR_KW_TYPE_UINT16 "uint16_t"
34+#define IR_KW_TYPE_UINT32 "uint32_t"
35+#define IR_KW_TYPE_UINT64 "uint64_t"
36+#define IR_KW_TYPE_FP16 "half"
37+#define IR_KW_TYPE_FP32 "float"
38+#define IR_KW_TYPE_FP64 "double"
39+#define IR_KW_TYPE_BF16 "bfloat16_t"
40+#define IR_KW_TYPE_FP8E4M3FN "float8_e4m3_t"
41+#define IR_KW_TYPE_FP8E5M2 "float8_e5m2_t"
42+#define IR_KW_TYPE_HF4 "hifloat4_t"
43+#define IR_KW_TYPE_HF8 "hifloat8_t"
44+#define IR_KW_TYPE_UNKNOWN "unknown"
45+ 
24namespace pypto {46namespace pypto {
25namespace ir {47namespace ir {
26 48 
@@ -218,6 +240,37 @@ public:
218 }240 }
219 }241 }
220 242 
243+ /**
244+ * \brief Bidirectional map between DataType code (uint8_t) and C-type string.
245+ *
246+ * Correspondence follows ToCTypeString(). Forward lookup: code -> string.
247+ * Reverse lookup: string -> code.
248+ */
249+ static inline const npu::tile_fwk::BiMap<uint8_t>& GetDataTypeCTypeStringDict()
250+ {
251+ static npu::tile_fwk::BiMap<uint8_t> dict{{
252+ {kBoolCode, IR_KW_TYPE_BOOL},
253+ {kInt8Code, IR_KW_TYPE_INT8},
254+ {kInt16Code, IR_KW_TYPE_INT16},
255+ {kInt32Code, IR_KW_TYPE_INT32},
256+ {kInt64Code, IR_KW_TYPE_INT64},
257+ {kIndexCode, IR_KW_TYPE_INT64},
258+ {kUInt8Code, IR_KW_TYPE_UINT8},
259+ {kUInt16Code, IR_KW_TYPE_UINT16},
260+ {kUInt32Code, IR_KW_TYPE_UINT32},
261+ {kUInt64Code, IR_KW_TYPE_UINT64},
262+ {kFp16Code, IR_KW_TYPE_FP16},
263+ {kFp32Code, IR_KW_TYPE_FP32},
264+ {kFp64Code, IR_KW_TYPE_FP64},
265+ {kBf16Code, IR_KW_TYPE_BF16},
266+ {kFp8e4m3fnCode, IR_KW_TYPE_FP8E4M3FN},
267+ {kFp8e5m2Code, IR_KW_TYPE_FP8E5M2},
268+ {kHf4Code, IR_KW_TYPE_UNKNOWN},
269+ {kHf8Code, IR_KW_TYPE_HF8},
270+ }};
271+ return dict;
272+ }
273+ 
221 /**274 /**
222 * \brief Get C style type string for code generation275 * \brief Get C style type string for code generation
223 *276 *
@@ -229,43 +282,7 @@ public:
229 */282 */
230 [[nodiscard]] std::string ToCTypeString() const283 [[nodiscard]] std::string ToCTypeString() const
231 {284 {
232- switch (code_) {285+ return GetDataTypeCTypeStringDict().Find(code_, IR_KW_TYPE_UNKNOWN);
233- case kBoolCode:
234- return "bool";
235- case kInt8Code:
236- return "int8_t";
237- case kInt16Code:
238- return "int16_t";
239- case kInt32Code:
240- return "int32_t";
241- case kInt64Code:
242- case kIndexCode:
243- return "int64_t";
244- case kUInt8Code:
245- return "uint8_t";
246- case kUInt16Code:
247- return "uint16_t";
248- case kUInt32Code:
249- return "uint32_t";
250- case kUInt64Code:
251- return "uint64_t";
252- case kFp16Code:
253- return "half";
254- case kFp32Code:
255- return "float";
256- case kFp64Code:
257- return "double";
258- case kBf16Code:
259- return "bfloat16_t";
260- case kFp8e4m3fnCode:
261- return "float8_e4m3_t";
262- case kFp8e5m2Code:
263- return "float8_e5m2_t";
264- case kHf8Code:
265- return "hifloat8_t";
266- default:
267- return "unknown";
268- }
269 }286 }
270 287 
271 /**288 /**
@@ -115,7 +115,8 @@ enum class ObjectKind {
115 Program,115 Program,
116 116 
117 // Op kinds117 // Op kinds
118- Op118+ Op,
119+ Invalid,
119};120};
120 121 
121/**122/**
@@ -199,7 +199,7 @@ using OpPtr = std::shared_ptr<const Op>;
199 * IR Syntax:199 * IR Syntax:
200 * RHS:200 * RHS:
201 * `%` name201 * `%` name
202- * LHR:202+ * LHS:
203 * type `%` name203 * type `%` name
204 * INCAST/OUTCAST:204 * INCAST/OUTCAST:
205 * type `%` name205 * type `%` name
@@ -23,6 +23,7 @@
23 23 
24#include "core/logging.h"24#include "core/logging.h"
25#include "ir/scalar_expr.h"25#include "ir/scalar_expr.h"
26+#include "ir/transforms/io_text.h"
26 27 
27namespace pypto {28namespace pypto {
28namespace ir {29namespace ir {
@@ -289,5 +290,122 @@ inline ExprPtr MakeNot(const ExprPtr& operand, const Span& span = Span::Unknown(
289 return std::make_shared<Not>(operand, DataType::BOOL, span);290 return std::make_shared<Not>(operand, DataType::BOOL, span);
290}291}
291 292 
293+// ========== Logical Operator Construction Functions ==========
294+ 
295+inline ExprPtr MakeAnd(const ExprPtr& left, const ExprPtr& right, const Span& span = Span::Unknown())
296+{
297+ PromoteBinaryOperands(left, right, "and", span);
298+ return std::make_shared<And>(left, right, DataType::BOOL, span);
299+}
300+ 
301+inline ExprPtr MakeOr(const ExprPtr& left, const ExprPtr& right, const Span& span = Span::Unknown())
302+{
303+ PromoteBinaryOperands(left, right, "or", span);
304+ return std::make_shared<Or>(left, right, DataType::BOOL, span);
305+}
306+ 
307+inline ExprPtr MakeXor(const ExprPtr& left, const ExprPtr& right, const Span& span = Span::Unknown())
308+{
309+ PromoteBinaryOperands(left, right, "xor", span);
310+ return std::make_shared<Xor>(left, right, DataType::BOOL, span);
311+}
312+ 
313+inline ExprPtr MakeAbs(const ExprPtr& operand, const Span& span = Span::Unknown())
314+{
315+ DataType dtype = NormalizeBoolDtype(GetScalarDtype(operand, span));
316+ return std::make_shared<Abs>(operand, dtype, span);
317+}
318+ 
319+// ========== Name-dispatched factory functions (for IR text loader) ==========
320+ 
321+/**
322+ * \brief Construct a binary expression node by operator name.
323+ *
324+ * Dispatches to the corresponding Make<Op> factory function.
325+ *
326+ * \param opName Operator name matching the node TypeName (e.g. "Add", "Sub").
327+ * \param left Left operand
328+ * \param right Right operand
329+ * \param span Source location
330+ * \return Constructed binary expression, or nullptr if opName is unknown.
331+ */
332+inline ExprPtr MakeBinaryOp(const std::string& opName, const ExprPtr& left, const ExprPtr& right,
333+ const Span& span = Span::Unknown())
334+{
335+ if (opName == IR_KW_SCALAR_BOP_ADD)
336+ return MakeAdd(left, right, span);
337+ if (opName == IR_KW_SCALAR_BOP_SUB)
338+ return MakeSub(left, right, span);
339+ if (opName == IR_KW_SCALAR_BOP_MUL)
340+ return MakeMul(left, right, span);
341+ if (opName == IR_KW_SCALAR_BOP_DIV)
342+ return MakeFloorDiv(left, right, span);
343+ if (opName == IR_KW_SCALAR_BOP_MOD)
344+ return MakeFloorMod(left, right, span);
345+ if (opName == IR_KW_SCALAR_BOP_FDIV)
346+ return MakeFloatDiv(left, right, span);
347+ if (opName == IR_KW_SCALAR_BOP_MIN)
348+ return MakeMin(left, right, span);
349+ if (opName == IR_KW_SCALAR_BOP_MAX)
350+ return MakeMax(left, right, span);
351+ if (opName == IR_KW_SCALAR_BOP_POW)
352+ return MakePow(left, right, span);
353+ if (opName == IR_KW_SCALAR_BOP_EQ)
354+ return MakeEq(left, right, span);
355+ if (opName == IR_KW_SCALAR_BOP_NE)
356+ return MakeNe(left, right, span);
357+ if (opName == IR_KW_SCALAR_BOP_LT)
358+ return MakeLt(left, right, span);
359+ if (opName == IR_KW_SCALAR_BOP_LE)
360+ return MakeLe(left, right, span);
361+ if (opName == IR_KW_SCALAR_BOP_GT)
362+ return MakeGt(left, right, span);
363+ if (opName == IR_KW_SCALAR_BOP_GE)
364+ return MakeGe(left, right, span);
365+ if (opName == IR_KW_SCALAR_BOP_LAND)
366+ return MakeAnd(left, right, span);
367+ if (opName == IR_KW_SCALAR_BOP_LOR)
368+ return MakeOr(left, right, span);
369+ if (opName == IR_KW_SCALAR_BOP_LXOR)
370+ return MakeXor(left, right, span);
371+ if (opName == IR_KW_SCALAR_BOP_AND)
372+ return MakeBitAnd(left, right, span);
373+ if (opName == IR_KW_SCALAR_BOP_OR)
374+ return MakeBitOr(left, right, span);
375+ if (opName == IR_KW_SCALAR_BOP_XOR)
376+ return MakeBitXor(left, right, span);
377+ if (opName == IR_KW_SCALAR_BOP_SHL)
378+ return MakeBitShiftLeft(left, right, span);
379+ if (opName == IR_KW_SCALAR_BOP_SHR)
380+ return MakeBitShiftRight(left, right, span);
381+ return nullptr;
382+}
383+ 
384+/**
385+ * \brief Construct a unary expression node by operator name.
386+ *
387+ * Dispatches to the corresponding Make<Op> factory function.
388+ *
389+ * \param opName Operator name matching the node TypeName (e.g. "Neg", "Cast").
390+ * \param operand Operand expression
391+ * \param span Source location
392+ * \return Constructed unary expression, or nullptr if opName is unknown.
393+ */
394+inline ExprPtr MakeUnaryOp(const std::string& opName, const ExprPtr& operand, DataType castDtype = DataType::INT64,
395+ const Span& span = Span::Unknown())
396+{
397+ if (opName == IR_KW_SCALAR_UOP_ABS)
398+ return MakeAbs(operand, span);
399+ if (opName == IR_KW_SCALAR_UOP_NEG)
400+ return MakeNeg(operand, span);
401+ if (opName == IR_KW_SCALAR_UOP_NOT)
402+ return MakeNot(operand, span);
403+ if (opName == IR_KW_SCALAR_UOP_INV)
404+ return MakeBitNot(operand, span);
405+ if (opName == IR_KW_SCALAR_UOP_CAST)
406+ return MakeCast(operand, castDtype, span);
407+ return nullptr;
408+}
409+ 
292} // namespace ir410} // namespace ir
293} // namespace pypto411} // namespace pypto
@@ -559,7 +559,7 @@ public:
559 559 
560using WhileStmtPtr = std::shared_ptr<const WhileStmt>;560using WhileStmtPtr = std::shared_ptr<const WhileStmt>;
561 561 
562-/*562+/**
563 * IR Syntax:563 * IR Syntax:
564 * `section` sectionKind_564 * `section` sectionKind_
565 * body565 * body
@@ -682,7 +682,7 @@ public:
682 682 
683using ContinueStmtPtr = std::shared_ptr<const ContinueStmt>;683using ContinueStmtPtr = std::shared_ptr<const ContinueStmt>;
684 684 
685-/*685+/**
686 * IR Syntax:686 * IR Syntax:
687 * result `,` result_token `=` opcode `(` arg1 `,` arg2 `,` ... `)` `;`687 * result `,` result_token `=` opcode `(` arg1 `,` arg2 `,` ... `)` `;`
688 */688 */
@@ -721,10 +721,10 @@ public:
721 721 
722using ScalarOpStmtPtr = std::shared_ptr<const ScalarOpStmt>;722using ScalarOpStmtPtr = std::shared_ptr<const ScalarOpStmt>;
723 723 
724-/*724+/**
725 * IR Syntax:725 * IR Syntax:
726 * result0 `,` result1 `,` ... `,` result_token `=`726 * result0 `,` result1 `,` ... `,` result_token `=`
727- * opcode `(` arg1 `,` arg2 `,` ... `)`727+ * opcode `(` arg1 `,` arg2 `,` ... `)` `token` `(` tok0 `,` ... tokN `)`
728 * `#` attr0 `(` attr0_value `)` ... `#` attrN `(` attrN_value `)` `;`728 * `#` attr0 `(` attr0_value `)` ... `#` attrN `(` attrN_value `)` `;`
729 */729 */
730class TensorOpStmt : public Stmt {730class TensorOpStmt : public Stmt {
@@ -18,6 +18,7 @@
18#include "ir/memref.h"18#include "ir/memref.h"
19#include "ir/scalar_expr.h"19#include "ir/scalar_expr.h"
20#include "ir/stmt.h"20#include "ir/stmt.h"
21+#include "ir/type.h"
21 22 
22namespace pypto {23namespace pypto {
23namespace ir {24namespace ir {
@@ -230,16 +231,69 @@ R StmtFunctor<R, Args...>::VisitStmt(const StmtPtr& stmt, Args... args)
230#undef STMT_FUNCTOR_DISPATCH231#undef STMT_FUNCTOR_DISPATCH
231 232 
232/**233/**
233- * \brief Unified functor for both expressions and statements234+ * \brief Base template for type functors
234 *235 *
235- * Combines ExprFunctor and StmtFunctor to provide a unified interface236+ * Provides a visitor-like interface for operating on IR types.
236- * for visiting both expression and statement IR nodes.237+ * Subclasses implement specific operations by overriding VisitType_ methods.
237 *238 *
238 * \tparam R Return type of the visit operations239 * \tparam R Return type of the visit operations
239 * \tparam Args Additional arguments passed to visit methods240 * \tparam Args Additional arguments passed to visit methods
240 */241 */
241template <typename R, typename... Args>242template <typename R, typename... Args>
242-class IRFunctor : public ExprFunctor<R, Args...>, public StmtFunctor<R, Args...> {243+class TypeFunctor {
244+public:
245+ virtual ~TypeFunctor() = default;
246+ 
247+ virtual R VisitType(const TypePtr& type, Args... args);
248+ 
249+protected:
250+ virtual R VisitType_(const UnknownTypePtr& op, Args... args) = 0;
251+ virtual R VisitType_(const ScalarTypePtr& op, Args... args) = 0;
252+ virtual R VisitType_(const TensorTypePtr& op, Args... args) = 0;
253+ virtual R VisitType_(const TileTypePtr& op, Args... args) = 0;
254+ virtual R VisitType_(const TupleTypePtr& op, Args... args) = 0;
255+ virtual R VisitType_(const MemRefTypePtr& op, Args... args) = 0;
256+ virtual R VisitType_(const PtrTypePtr& op, Args... args) = 0;
257+ virtual R VisitType_(const TokenTypePtr& op, Args... args) = 0;
258+ virtual R VisitType_(const NoneTypePtr& op, Args... args) = 0;
259+ virtual R VisitType_(const LogicalTensorTypePtr& op, Args... args) = 0;
260+};
261+ 
262+#define TYPE_FUNCTOR_DISPATCH(OpType) \
263+ if (auto op = As<OpType>(type)) { \
264+ return VisitType_(op, std::forward<Args>(args)...); \
265+ }
266+ 
267+template <typename R, typename... Args>
268+R TypeFunctor<R, Args...>::VisitType(const TypePtr& type, Args... args)
269+{
270+ TYPE_FUNCTOR_DISPATCH(TensorType);
271+ TYPE_FUNCTOR_DISPATCH(TileType);
272+ TYPE_FUNCTOR_DISPATCH(ScalarType);
273+ TYPE_FUNCTOR_DISPATCH(TupleType);
274+ TYPE_FUNCTOR_DISPATCH(PtrType);
275+ TYPE_FUNCTOR_DISPATCH(TokenType);
276+ TYPE_FUNCTOR_DISPATCH(NoneType);
277+ TYPE_FUNCTOR_DISPATCH(LogicalTensorType);
278+ TYPE_FUNCTOR_DISPATCH(MemRefType);
279+ TYPE_FUNCTOR_DISPATCH(UnknownType);
280+ 
281+ throw TypeError("Unknown type in TypeFunctor::VisitType");
282+}
283+ 
284+#undef TYPE_FUNCTOR_DISPATCH
285+ 
286+/**
287+ * \brief Unified functor for expressions, statements, and types
288+ *
289+ * Combines ExprFunctor, StmtFunctor, and TypeFunctor to provide a unified
290+ * interface for visiting all IR node categories.
291+ *
292+ * \tparam R Return type of the visit operations
293+ * \tparam Args Additional arguments passed to visit methods
294+ */
295+template <typename R, typename... Args>
296+class IRFunctor : public ExprFunctor<R, Args...>, public StmtFunctor<R, Args...>, public TypeFunctor<R, Args...> {
243public:297public:
244 virtual ~IRFunctor() = default;298 virtual ~IRFunctor() = default;
245 299 
@@ -39,6 +39,7 @@ public:
39 39 
40 void VisitExpr(const ExprPtr& expr) override;40 void VisitExpr(const ExprPtr& expr) override;
41 void VisitStmt(const StmtPtr& stmt) override;41 void VisitStmt(const StmtPtr& stmt) override;
42+ void VisitType(const TypePtr& type) override;
42 43 
43protected:44protected:
44 /// Override to handle Var with a single method.45 /// Override to handle Var with a single method.
@@ -105,6 +106,18 @@ protected:
105 void VisitStmt_(const ScalarOpStmtPtr& op) override;106 void VisitStmt_(const ScalarOpStmtPtr& op) override;
106 void VisitStmt_(const StmtPtr& op) override;107 void VisitStmt_(const StmtPtr& op) override;
107 108 
109+ // Type handlers
110+ void VisitType_(const UnknownTypePtr& op) override;
111+ void VisitType_(const ScalarTypePtr& op) override;
112+ void VisitType_(const TensorTypePtr& op) override;
113+ void VisitType_(const TileTypePtr& op) override;
114+ void VisitType_(const TupleTypePtr& op) override;
115+ void VisitType_(const MemRefTypePtr& op) override;
116+ void VisitType_(const PtrTypePtr& op) override;
117+ void VisitType_(const TokenTypePtr& op) override;
118+ void VisitType_(const NoneTypePtr& op) override;
119+ void VisitType_(const LogicalTensorTypePtr& op) override;
120+ 
108 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.121 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.
109 /// Default: visits left and right children.122 /// Default: visits left and right children.
110 virtual void VisitBinaryExpr_(const BinaryExprPtr& op);123 virtual void VisitBinaryExpr_(const BinaryExprPtr& op);
@@ -0,0 +1,585 @@
1+/**
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+ * \file io_text.h
11+ * \brief IR text I/O — dumper and loader following the declared IR Syntax grammar.
12+ *
13+ * IRDumperText produces the canonical text representation declared in the
14+ * Doxygen "IR Syntax" blocks of each IR node header. IRLoaderText parses that
15+ * text back into IR nodes. Together they provide full round-trip serialisation.
16+ */
17+#ifndef PYPTO_IR_TRANSFORMS_IO_TEXT_H_
18+#define PYPTO_IR_TRANSFORMS_IO_TEXT_H_
19+ 
20+#include <sstream>
21+#include <string>
22+#include <string_view>
23+ 
24+#include "ir/core.h"
25+#include "ir/expr.h"
26+#include "ir/function.h"
27+#include "ir/program.h"
28+#include "ir/stmt.h"
29+#include "ir/transforms/base/visitor.h"
30+#include "ir/type.h"
31+ 
32+// ===========================================================================
33+// IR text grammar keywords and punctuation
34+// ===========================================================================
35+// ---- Word keywords ----
36+#define IR_KW_PROGRAM "program"
37+#define IR_KW_FUNCTION "function"
38+#define IR_KW_INCAST "incast"
39+#define IR_KW_OUTCAST "outcast"
40+#define IR_KW_IF "if"
41+#define IR_KW_THEN "then"
42+#define IR_KW_ELSE "else"
43+#define IR_KW_FOR "for"
44+#define IR_KW_INRANGE "inrange"
45+#define IR_KW_ITER "iter"
46+#define IR_KW_WHILE "while"
47+#define IR_KW_YIELD "yield"
48+#define IR_KW_RETURN "return"
49+#define IR_KW_SECTION "section"
50+#define IR_KW_EVAL "eval"
51+#define IR_KW_BREAK "break"
52+#define IR_KW_CONTINUE "continue"
53+#define IR_KW_TUPLE "tuple"
54+#define IR_KW_GETITEM "getitem"
55+#define IR_KW_SCALAR_EXPR "scalar_expr"
56+#define IR_KW_UNKNOWN "unknown"
57+#define IR_KW_TENSOR "tensor"
58+#define IR_KW_TILE "tile"
59+#define IR_KW_PTR "ptr"
60+#define IR_KW_TOKEN "token"
61+#define IR_KW_NONE "none"
62+#define IR_KW_TENSOR_VIEW "tensor_view"
63+#define IR_KW_TILE_VIEW "tile_view"
64+#define IR_KW_MEMREF "memref"
65+#define IR_KW_MEMREF_TYPE "memref_type"
66+#define IR_KW_LOGICAL_TENSOR "logical_tensor"
67+#define IR_KW_HW_INFO "hw_info"
68+#define IR_KW_TRUE "true"
69+#define IR_KW_FALSE "false"
70+#define IR_KW_ENTRY "entry"
71+#define IR_KW_TYPE "type"
72+#define IR_KW_DIM "x"
73+ 
74+// ---- Scalar binary operator names ----
75+#define IR_KW_SCALAR_BOP_ADD "add"
76+#define IR_KW_SCALAR_BOP_SUB "sub"
77+#define IR_KW_SCALAR_BOP_MUL "mul"
78+#define IR_KW_SCALAR_BOP_DIV "div"
79+#define IR_KW_SCALAR_BOP_MOD "mod"
80+#define IR_KW_SCALAR_BOP_FDIV "fdiv"
81+#define IR_KW_SCALAR_BOP_MIN "min"
82+#define IR_KW_SCALAR_BOP_MAX "max"
83+#define IR_KW_SCALAR_BOP_POW "pow"
84+#define IR_KW_SCALAR_BOP_EQ "eq"
85+#define IR_KW_SCALAR_BOP_NE "ne"
86+#define IR_KW_SCALAR_BOP_LT "lt"
87+#define IR_KW_SCALAR_BOP_LE "le"
88+#define IR_KW_SCALAR_BOP_GT "gt"
89+#define IR_KW_SCALAR_BOP_GE "ge"
90+#define IR_KW_SCALAR_BOP_LAND "land"
91+#define IR_KW_SCALAR_BOP_LOR "lor"
92+#define IR_KW_SCALAR_BOP_LXOR "lxor"
93+#define IR_KW_SCALAR_BOP_AND "and"
94+#define IR_KW_SCALAR_BOP_OR "or"
95+#define IR_KW_SCALAR_BOP_XOR "xor"
96+#define IR_KW_SCALAR_BOP_SHL "shl"
97+#define IR_KW_SCALAR_BOP_SHR "shr"
98+ 
99+// ---- Scalar unary operator names ----
100+#define IR_KW_SCALAR_UOP_ABS "abs"
@@ -159,7 +159,10 @@ using ScalarTypePtr = std::shared_ptr<const ScalarType>;
159 * stride and layout information.159 * stride and layout information.
160 *160 *
161 * IR Syntax:161 * IR Syntax:
162- * `tensor_view` `<` validshape0 `x` ... validshapeN `,` stride0 `x` ... strideN `,` layout (`,` ptr)? `>`162+ * has_value == true:
163+ * `tensor_view` `<` validshape0 `x` ... validshapeN `,` stride0 `x` ... strideN `,` layout `,` ptr `>`
164+ * has_value == false:
165+ * `tensor_view` `<` `>`
163 */166 */
164struct TensorView {167struct TensorView {
165 std::vector<ExprPtr> validShape; ///< Valid shape dimensions (symbolic or constant)168 std::vector<ExprPtr> validShape; ///< Valid shape dimensions (symbolic or constant)
@@ -242,6 +245,12 @@ enum class CompactMode {
242 *245 *
243 * Contains layout, fractal, padding, and compact mode parameters246 * Contains layout, fractal, padding, and compact mode parameters
244 * that describe how a tile is physically stored in hardware memory.247 * that describe how a tile is physically stored in hardware memory.
248+ *
249+ * IR Syntax:
250+ * has_value == true:
251+ * `hardware` `<` blayout `,` slayout `,` fractal `,` pad `,` compact `>`
252+ * has_value == false:
253+ * `hardware` `<` `>`
245 */254 */
246struct HardwareInfo {255struct HardwareInfo {
247 static constexpr uint64_t kDefaultFractal = 512;256 static constexpr uint64_t kDefaultFractal = 512;
@@ -277,7 +286,10 @@ struct HardwareInfo {
277 * a tile views its underlying memory.286 * a tile views its underlying memory.
278 *287 *
279 * IR Syntax:288 * IR Syntax:
280- * `tile_view` `<` validshape0 `x` ... validshapeN `,` stride0 `x` ... strideN `,` start_offset `>`289+ * has_value == true:
290+ * `tile_view` `<` validshape0 `x` ... validshapeN `,` stride0 `x` ... strideN `,` start_offset `>`
291+ * has_value == false:
292+ * `tile_view` `<` `>`
281 */293 */
282struct TileView {294struct TileView {
283 std::vector<ExprPtr> validShape; ///< Valid shape dimensions295 std::vector<ExprPtr> validShape; ///< Valid shape dimensions
@@ -370,7 +382,7 @@ using ShapedTypePtr = std::shared_ptr<const ShapedType>;
370 * Represents a tensor type with a data type and shape dimensions.382 * Represents a tensor type with a data type and shape dimensions.
371 *383 *
372 * IR Syntax:384 * IR Syntax:
373- * `tensor` `<` shape0 `x` ... shapeN `,` dtype ( `,` tensor_view )? `>`385+ * `tensor` `<` shape0 `x` ... shapeN `,` dtype `,` tensor_view `>`
374 */386 */
375class TensorType : public ShapedType {387class TensorType : public ShapedType {
376public:388public:
@@ -429,7 +441,7 @@ using TensorTypePtr = std::shared_ptr<const TensorType>;
429 * Note: Code generation currently only supports up to 2D tiles.441 * Note: Code generation currently only supports up to 2D tiles.
430 *442 *
431 * IR Syntax:443 * IR Syntax:
432- * `tile` `<` shape0 `x` ... shapeN `,` dtype ( `,` tileView_ )? ( `,` hardwareInfo_ )? `>`444+ * `tile` `<` shape0 `x` ... shapeN `,` dtype `,` tileView `,` hardwareInfo `>`
433 */445 */
434class TileType : public ShapedType {446class TileType : public ShapedType {
435public:447public:
@@ -489,7 +501,7 @@ using TileTypePtr = std::shared_ptr<const TileType>;
489 * Tuples are used for multiple return values and structured data.501 * Tuples are used for multiple return values and structured data.
490 *502 *
491 * IR Syntax:503 * IR Syntax:
492- * `tuple` `<` dtype `>`504+ * `tuple` `<` type0 `,` ... `,` typeN `>`
493 */505 */
494class TupleType : public Type {506class TupleType : public Type {
495public:507public:
@@ -0,0 +1,592 @@
1+/**
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+ * \file dumper_text.cpp
11+ * \brief IR text dumper implementation following the declared IR Syntax grammar.
12+ */
13+ 
14+#include "ir/transforms/io_text.h"
15+ 
16+#include <cstdint>
17+#include <cstring>
18+#include <iomanip>
19+#include <typeindex>
20+ 
21+#include "core/any_cast.h"
22+#include "core/dtype.h"
23+#include "core/logging.h"
24+#include "ir/core.h"
25+#include "ir/function.h"
26+#include "ir/kind_traits.h"
27+#include "ir/memref.h"
28+#include "ir/memory_space.h"
29+#include "ir/op_attr_types.h"
30+#include "ir/pipe.h"
31+#include "ir/program.h"
32+#include "ir/scalar_expr.h"
33+#include "ir/span.h"
34+#include "ir/stmt.h"
35+ 
36+namespace pypto {
37+namespace ir {
38+ 
39+// ---------------------------------------------------------------------------
40+// Operator name lookup
41+// ---------------------------------------------------------------------------
42+const char* IRDumperText::BinaryOpName(const BinaryExprPtr& op)
43+{
44+ return GetBinaryOpDict().Find(op->GetKind(), "UnknownBinOp").c_str();
45+}
46+ 
47+const char* IRDumperText::UnaryOpName(const UnaryExprPtr& op)
48+{
49+ return GetUnaryOpDict().Find(op->GetKind(), "UnknownUnOp").c_str();
50+}
51+ 
52+// ---------------------------------------------------------------------------
53+// Attr value printing
54+// ---------------------------------------------------------------------------
55+void IRDumperText::PrintAttrValue(const std::string& key, const std::any& value)
56+{
57+ if (value.type() == typeid(int)) {
58+ stream_ << AnyCast<int>(value, key);
59+ } else if (value.type() == typeid(uint64_t)) {
60+ stream_ << AnyCast<uint64_t>(value);
61+ } else if (value.type() == typeid(double)) {
62+ stream_ << AnyCast<double>(value, key);
63+ } else if (value.type() == typeid(float)) {
64+ stream_ << static_cast<double>(AnyCast<float>(value, key));
65+ } else if (value.type() == typeid(bool)) {
66+ stream_ << (AnyCast<bool>(value, key) ? IR_KW_TRUE : IR_KW_FALSE);
67+ } else if (value.type() == typeid(DataType)) {
68+ stream_ << AnyCast<DataType>(value, key).ToCTypeString();
69+ } else if (value.type() == typeid(MemorySpace)) {
70+ stream_ << MemorySpaceToString(AnyCast<MemorySpace>(value, key));
71+ } else if (value.type() == typeid(std::vector<int>)) {
72+ const auto& vals = AnyCast<std::vector<int>>(value, key);
73+ stream_ << IR_PUN_LBRACKET;
74+ for (size_t i = 0; i < vals.size(); ++i) {
75+ if (i > 0) {
76+ stream_ << IR_PUN_COMMA << " ";
77+ }
78+ stream_ << vals[i];
79+ }
80+ stream_ << IR_PUN_RBRACKET;
81+ } else if (value.type() == typeid(std::vector<int64_t>)) {
82+ const auto& vals = AnyCast<std::vector<int64_t>>(value, key);
83+ stream_ << IR_PUN_LBRACKET;
84+ for (size_t i = 0; i < vals.size(); ++i) {
85+ if (i > 0) {
86+ stream_ << IR_PUN_COMMA << " ";
87+ }
88+ stream_ << vals[i];
89+ }
90+ stream_ << IR_PUN_RBRACKET;
91+ } else {
92+ stream_ << "Unsupported";
93+ }
94+}
95+ 
96+void IRDumperText::PrintAttr(const std::string& key, const std::any& value)
97+{
98+ stream_ << " " << IR_PUN_ATTRNAME << key << IR_PUN_LPAREN;
99+ PrintAttrValue(key, value);
100+ stream_ << IR_PUN_RPAREN;
@@ -47,6 +47,8 @@ void IRVisitor::VisitExpr(const ExprPtr& expr) { ExprFunctor<void>::VisitExpr(ex
47 47 
48void IRVisitor::VisitStmt(const StmtPtr& stmt) { StmtFunctor<void>::VisitStmt(stmt); }48void IRVisitor::VisitStmt(const StmtPtr& stmt) { StmtFunctor<void>::VisitStmt(stmt); }
49 49 
50+void IRVisitor::VisitType(const TypePtr& type) { TypeFunctor<void>::VisitType(type); }
51+ 
50void IRVisitor::VisitVarLike_(const VarPtr& op)52void IRVisitor::VisitVarLike_(const VarPtr& op)
51{53{
52 if (auto tensor_type = As<TensorType>(op->GetType())) {54 if (auto tensor_type = As<TensorType>(op->GetType())) {
@@ -295,5 +297,17 @@ void IRVisitor::VisitStmt_(const TensorOpStmtPtr& op)
295 297 
296void IRVisitor::VisitStmt_(const StmtPtr&) {}298void IRVisitor::VisitStmt_(const StmtPtr&) {}
297 299 
300+// Type handlers - default: no-op
301+void IRVisitor::VisitType_(const UnknownTypePtr&) {}
302+void IRVisitor::VisitType_(const ScalarTypePtr&) {}
303+void IRVisitor::VisitType_(const TensorTypePtr&) {}
304+void IRVisitor::VisitType_(const TileTypePtr&) {}
305+void IRVisitor::VisitType_(const TupleTypePtr&) {}
306+void IRVisitor::VisitType_(const MemRefTypePtr&) {}
307+void IRVisitor::VisitType_(const PtrTypePtr&) {}
308+void IRVisitor::VisitType_(const TokenTypePtr&) {}
309+void IRVisitor::VisitType_(const NoneTypePtr&) {}
310+void IRVisitor::VisitType_(const LogicalTensorTypePtr&) {}
311+ 
298} // namespace ir312} // namespace ir
299} // namespace pypto313} // namespace pypto
@@ -29,6 +29,7 @@
29 29 
30#include "tilefwk/error.h"30#include "tilefwk/error.h"
31#include "tilefwk/symbolic_scalar.h"31#include "tilefwk/symbolic_scalar.h"
32+#include "core/bimap.h"
32 33 
33namespace npu::tile_fwk {34namespace npu::tile_fwk {
34 35 
@@ -245,44 +246,6 @@ constexpr int ParamLocOutcast = 2;
245 246 
246std::string ParamLocToStr(uint32_t loc);247std::string ParamLocToStr(uint32_t loc);
247 248 
248-template <typename T>
249-class BiMap {
250-public:
251- BiMap(const std::initializer_list<std::pair<T, std::string>>& init)
252- {
253- for (const auto& [i, s] : init) {
254- type2strDict[i] = s;
255- str2typeDict[s] = i;
256- }
257- }
258- 
259- bool Count(T key) const { return type2strDict.count(key); }
260- 
261- bool Count(const std::string& key) const { return str2typeDict.count(key); }
262- 
263- const std::string& Find(T key, const std::string& defaultValue = "") const
264- {
265- if (type2strDict.count(key)) {
266- return type2strDict.find(key)->second;
267- } else {
268- return defaultValue;
269- }
270- }
271- 
272- T Find(const std::string& key, T defaultValue) const
273- {
274- if (str2typeDict.count(key)) {
275- return str2typeDict.find(key)->second;
276- } else {
277- return defaultValue;
278- }
279- }
280- 
281-private:
282- std::unordered_map<T, std::string> type2strDict;
283- std::unordered_map<std::string, T> str2typeDict;
284-};
285- 
286inline const BiMap<CoreType>& GetCoreTypeDict()249inline const BiMap<CoreType>& GetCoreTypeDict()
287{250{
288 static BiMap<CoreType> dict{{251 static BiMap<CoreType> dict{{
@@ -28,3 +28,7 @@ PTO_Fwk_UTest_AddCaseLib(
28 PRIVATE_INCLUDE_DIRECTORIES ${PTO_FWK_SRC_ROOT}/framework/include/pypto_pro28 PRIVATE_INCLUDE_DIRECTORIES ${PTO_FWK_SRC_ROOT}/framework/include/pypto_pro
29 LINK_LIBRARIES ${LinkLibraries}29 LINK_LIBRARIES ${LinkLibraries}
30)30)
31+ 
32+target_compile_definitions(${_Target} PRIVATE
33+ IO_TEXT_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/src/ir/test_io_text_dump_data"
34+)
@@ -0,0 +1,82 @@
1+/**
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+ * \file io_text_dump_test.cpp
11+ * \brief Data-driven round-trip tests: load -> dump -> compare for IR text format.
12+ *
13+ * Each ``.pypto`` file in ``io_text_dump_test_data/`` is loaded via TextLoadFunction,
14+ * re-dumped via TextDump, and compared against the original file content.
15+ */
16+ 
17+#include <filesystem>
18+#include <fstream>
19+#include <sstream>
20+#include <string>
21+#include <vector>
22+ 
23+#include "gtest/gtest.h"
24+ 
25+#include "ir/transforms/io_text.h"
26+ 
27+namespace pypto {
28+namespace ir {
29+ 
30+namespace fs = std::filesystem;
31+ 
32+class IoTextDumpTest : public testing::Test {};
33+ 
34+static const fs::path kDataDir = fs::path(IO_TEXT_TEST_DATA_DIR);
35+ 
36+/// Read a file into a string, stripping trailing whitespace for comparison.
37+static std::string ReadFile(const fs::path& path)
38+{
39+ std::ifstream f(path);
40+ std::stringstream ss;
41+ ss << f.rdbuf();
42+ std::string content = ss.str();
43+ while (!content.empty() && (content.back() == '\n' || content.back() == '\r' || content.back() == ' ')) {
44+ content.pop_back();
45+ }
46+ return content;
47+}
48+ 
49+/// Collect all .pypto files in the data directory.
50+static std::vector<fs::path> CollectDataFiles()
51+{
52+ std::vector<fs::path> files;
53+ if (fs::exists(kDataDir)) {
54+ for (const auto& entry : fs::directory_iterator(kDataDir)) {
55+ if (entry.path().extension() == ".pypto") {
56+ files.push_back(entry.path());
57+ }
58+ }
59+ }
60+ std::sort(files.begin(), files.end());
61+ return files;
62+}
63+ 
64+TEST_F(IoTextDumpTest, DISABLED_LoadDumpMatch)
65+{
66+ std::vector<fs::path> dataFilePathList = CollectDataFiles();
67+ ASSERT_FALSE(dataFilePathList.empty()) << "No .pypto data files found in: " << kDataDir;
68+ for (auto dataFilePath : dataFilePathList) {
69+ std::string original = ReadFile(dataFilePath);
70+ ASSERT_FALSE(original.empty()) << "Empty or missing file: " << dataFilePath;
71+ 
72+ // Load -> Dump -> Compare
73+ auto prog = TextLoadProgram(original);
74+ ASSERT_NE(prog, nullptr) << "Load failed for: " << dataFilePath.filename();
75+ 
76+ std::string dumped = TextDump(prog);
77+ EXPECT_EQ(dumped, original) << "Round-trip mismatch in: " << dataFilePath.filename();
78+ }
79+}
80+ 
81+} // namespace ir
82+} // namespace pypto
@@ -0,0 +1,10 @@
1+program #entry(binops) {
2+ function binops incast(int32_t %a) outcast(int32_t) #type(Opaque) #entry(true) {
3+ int32_t %x = ((cast int64_t %a) add 1);
4+ int32_t %y = ((cast int64_t %x) mul 2);
5+ int32_t %z = (%y sub %x);
6+ int32_t %w = (neg %z);
7+ int32_t %v = (cast float %w);
8+ return %v;
9+ }
10+}
@@ -0,0 +1,8 @@
1+program #entry(loop) {
2+ function loop incast() outcast(int32_t) #type(Opaque) #entry(true) {
3+ for %i inrange 0, 10, 1 iter {} {
4+ int32_t %s = ((cast int64_t %s) add %i);
5+ }
6+ return %s;
7+ }
8+}
@@ -0,0 +1,10 @@
1+program #entry(cond) {
2+ function cond incast() outcast(int32_t) #type(Opaque) #entry(true) {
3+ if true then {
4+ return 1;
5+ }
6+ else {
7+ return 0;
8+ }
9+ }
10+}
@@ -0,0 +1,8 @@
1+program #entry(misc_stmts) {
2+ function misc_stmts incast(int32_t %a) outcast() #type(Opaque) #entry(true) {
3+ myop(%a);
4+ break;
5+ continue;
6+ yield %a;
7+ }
8+}
@@ -0,0 +1,6 @@
1+program #entry(simple) {
2+ function simple incast(int32_t %x) outcast(int32_t) #type(Opaque) #entry(true) {
3+ int32_t %y = 42;
4+ return %y;
5+ }
6+}
@@ -0,0 +1,5 @@
1+program #entry(types) {
2+ function types incast(float %a, tensor<4 x 8, float, tensor_view<>> %b) outcast(tensor<4 x 8, float, tensor_view<>>) #type(Opaque) #entry(true) {
3+ return %b;
4+ }
5+}
@@ -0,0 +1,179 @@
1+/**
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+ * \file test_text_roundtrip.cpp
11+ * \brief Round-trip tests for IRDumperText / IRLoaderText.
12+ */
13+ 
14+#include "gtest/gtest.h"
15+ 
16+#include <memory>
17+#include <string>
18+#include <vector>
19+ 
20+#include "core/dtype.h"
21+#include "ir/expr.h"
22+#include "ir/function.h"
23+#include "ir/memref.h"
24+#include "ir/program.h"
25+#include "ir/scalar_expr.h"
26+#include "ir/span.h"
27+#include "ir/stmt.h"
28+#include "ir/transforms/io_text.h"
29+#include "ir/type.h"
30+#include "test_ir.h"
31+ 
32+namespace pypto {
33+namespace ir {
34+ 
35+static TypePtr Scalar(DataType dt) { return std::make_shared<ScalarType>(dt); }
36+static Span Sp() { return Span("test", 1, 1); }
37+ 
38+static VarPtr Var_(const std::string& name, DataType dt = DataType::INT32)
39+{
40+ return std::make_shared<Var>(name, Scalar(dt), Sp());
41+}
42+ 
43+class IoTextDumpRoundTripTest : public testing::Test {};
44+ 
45+// ---- Expression round-trip ----
46+TEST_F(IoTextDumpRoundTripTest, DISABLED_TestExprRoundTrip)
47+{
48+ auto a = std::make_shared<ConstInt>(42, DataType::INT32, Sp());
49+ EXPECT_EQ(TextDump(a), "42");
50+ EXPECT_EQ(TextDump(TextLoadExpr("42")), "42");
51+ 
52+ auto b = std::make_shared<ConstFloat>(3.5, DataType::FP32, Sp());
53+ EXPECT_EQ(TextDump(b), "3.5");
54+ 
55+ EXPECT_EQ(TextDump(std::make_shared<ConstBool>(true, Sp())), "true");
56+ EXPECT_EQ(TextDump(std::make_shared<ConstBool>(false, Sp())), "false");
57+ 
58+ // Binary: (1 add 2)
59+ auto one = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
60+ auto two = std::make_shared<ConstInt>(2, DataType::INT32, Sp());
61+ auto add = std::make_shared<Add>(one, two, DataType::INT32, Sp());
62+ EXPECT_EQ(TextDump(add), "(1 add 2)");
63+ auto loaded = TextLoadExpr("(1 add 2)");
64+ EXPECT_EQ(TextDump(loaded), "(1 add 2)");
65+ 
66+ // Unary: (neg 5)
67+ auto five = std::make_shared<ConstInt>(5, DataType::INT32, Sp());
68+ auto neg = std::make_shared<Neg>(five, DataType::INT32, Sp());
69+ EXPECT_EQ(TextDump(neg), "(neg 5)");
70+ EXPECT_EQ(TextDump(TextLoadExpr("(neg 5)")), "(neg 5)");
71+ 
72+ // Cast: (cast float 1)
73+ auto cast = std::make_shared<Cast>(one, DataType::FP32, Sp());
74+ EXPECT_EQ(TextDump(cast), "(cast float 1)");
75+ EXPECT_EQ(TextDump(TextLoadExpr("(cast float 1)")), "(cast float 1)");
76+ 
77+ // MakeTuple: tuple(1, 2)
78+ auto tup = std::make_shared<MakeTuple>(std::vector<ExprPtr>{one, two}, Sp());
79+ EXPECT_EQ(TextDump(tup), "tuple(1, 2)");
80+ EXPECT_EQ(TextDump(TextLoadExpr("tuple(1, 2)")), "tuple(1, 2)");
81+ 
82+ // GetItemExpr: getitem(tuple(1, 2), 0)
83+ auto idx = std::make_shared<ConstInt>(0, DataType::INDEX, Sp());
84+ auto gi = std::make_shared<GetItemExpr>(tup, idx, Sp());
85+ EXPECT_EQ(TextDump(gi), "getitem(tuple(1, 2), 0)");
86+}
87+ 
88+// ---- Type round-trip ----
89+TEST_F(IoTextDumpRoundTripTest, DISABLED_TestTypeRoundTrip)
90+{
91+ EXPECT_EQ(TextDumpType(Scalar(DataType::FP32)), "float");
92+ EXPECT_EQ(TextDumpType(TextLoadType("float")), "float");
93+ 
94+ EXPECT_EQ(TextDumpType(GetUnknownType()), "unknown");
95+ EXPECT_EQ(TextDumpType(GetTokenType()), "token");
96+ EXPECT_EQ(TextDumpType(GetNoneType()), "none");
97+ 
98+ EXPECT_EQ(TextDumpType(std::make_shared<PtrType>(DataType::FP16)), "ptr<half>");
99+ EXPECT_EQ(TextDumpType(TextLoadType("ptr<half>")), "ptr<half>");
100+ 
101+ auto tensor = std::make_shared<TensorType>(
102+ std::vector<ExprPtr>{std::make_shared<ConstInt>(4, DataType::INT64, Sp()),
103+ std::make_shared<ConstInt>(8, DataType::INT64, Sp())},
104+ DataType::FP32);
105+ EXPECT_EQ(TextDumpType(tensor), "tensor<4 x 8, float, tensor_view<>>");
106+ EXPECT_EQ(TextDumpType(TextLoadType("tensor<4 x 8, float, tensor_view<>>")), "tensor<4 x 8, float, tensor_view<>>");
107+}
108+ 
109+// ---- Statement round-trip ----
110+TEST_F(IoTextDumpRoundTripTest, DISABLED_TestStmtRoundTrip)
111+{
112+ // AssignStmt: int32_t %x = 42;
113+ auto x = Var_("x");
114+ auto assign = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(42, DataType::INT32, Sp()), Sp());
115+ std::string dumped = TextDump(assign);
116+ EXPECT_NE(dumped.find("int32_t %x = 42;"), std::string::npos);
117+ 
118+ // Round-trip
119+ auto loaded = TextLoadStmt(dumped);
120+ EXPECT_EQ(TextDump(loaded), dumped);
121+ 
122+ // ReturnStmt
123+ auto ret = std::make_shared<ReturnStmt>(std::vector<ExprPtr>{std::make_shared<ConstInt>(1, DataType::INT32, Sp())},
124+ Sp());
125+ std::string retDumped = TextDump(ret);
126+ EXPECT_NE(retDumped.find("return"), std::string::npos);
127+ auto retLoaded = TextLoadStmt(retDumped);
128+ EXPECT_EQ(TextDump(retLoaded), retDumped);
129+ 
130+ // YieldStmt
131+ auto yld = std::make_shared<YieldStmt>(std::vector<ExprPtr>{std::make_shared<ConstInt>(1, DataType::INT32, Sp())},
132+ Sp());
133+ std::string yldDumped = TextDump(yld);
134+ EXPECT_NE(yldDumped.find("yield"), std::string::npos);
135+ 
136+ // BreakStmt / ContinueStmt
137+ EXPECT_EQ(TextDump(std::make_shared<BreakStmt>(Sp())), "break;");
138+ EXPECT_EQ(TextDump(std::make_shared<ContinueStmt>(Sp())), "continue;");
139+ EXPECT_EQ(TextDump(TextLoadStmt("break;")), "break;");
140+ EXPECT_EQ(TextDump(TextLoadStmt("continue;")), "continue;");
141+}
142+ 
143+// ---- For loop round-trip ----
144+TEST_F(IoTextDumpRoundTripTest, DISABLED_TestForLoopRoundTrip)
145+{
146+ auto i = Var_("i");
147+ auto zero = std::make_shared<ConstInt>(0, DataType::INT32, Sp());
148+ auto ten = std::make_shared<ConstInt>(10, DataType::INT32, Sp());
149+ auto one = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
150+ auto body = std::make_shared<AssignStmt>(Var_("x"), one, Sp());
151+ auto forStmt = std::make_shared<ForStmt>(i, zero, ten, one, std::vector<IterArgPtr>{}, body, std::vector<VarPtr>{},
152+ Sp());
153+ std::string dumped = TextDump(forStmt);
154+ EXPECT_NE(dumped.find("for"), std::string::npos);
155+ EXPECT_NE(dumped.find("inrange"), std::string::npos);
156+ 
157+ auto loaded = TextLoadStmt(dumped);
158+ EXPECT_EQ(TextDump(loaded), dumped);
159+}
160+ 
161+// ---- Function round-trip ----
162+TEST_F(IoTextDumpRoundTripTest, DISABLED_TestFunctionRoundTrip)
163+{
164+ auto x = Var_("x");
165+ auto body = std::make_shared<ReturnStmt>(
166+ std::vector<ExprPtr>{std::make_shared<ConstInt>(42, DataType::INT32, Sp())}, Sp());
167+ auto func = std::make_shared<Function>("f", std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)},
168+ body, Sp());
169+ std::string dumped = TextDump(func);
170+ EXPECT_NE(dumped.find("function f"), std::string::npos);
171+ EXPECT_NE(dumped.find("incast("), std::string::npos);
172+ EXPECT_NE(dumped.find("outcast("), std::string::npos);
173+ 
174+ auto loaded = TextLoadFunction(dumped);
175+ EXPECT_EQ(TextDump(loaded), dumped);
176+}
177+ 
178+} // namespace ir
179+} // namespace pypto