Merged
feat(ir): Merge module pypto_impl and pypto_block #3888
wuzhongxinAdd on Jun 9
feat(ir): Merge module pypto_impl and pypto_block #3888
Merged
wuzhongxinAdd on Jun 9
Total: 32 files changed+1387-1922
@@ -0,0 +1,96 @@
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+#pragma once
12+#include <memory>
13+#include <string>
14+#include <unordered_map>
15+#include <vector>
16+ 
17+namespace pypto {
18+namespace ir {
19+ 
20+class TupleType;
21+using TupleTypePtr = std::shared_ptr<const TupleType>;
22+ 
23+/**
24+ * \brief Compilation-session side table for tuple field names.
25+ *
26+ * Field names of named tuples / structs are *not* part of the tuple type's core
27+ * semantics (positional element types and order are). They are only needed by
28+ * codegen during the struct-compat transition (to emit `a.field`) and for dump /
29+ * error display. This side table keeps that metadata out of both the IR nodes and
30+ * the TupleType structural identity.
31+ *
32+ * The key is the `TupleType` pointer. TupleType is never structurally interned --
33+ * each `struct.create` / `MakeTuple` allocates a fresh instance (`make_shared`),
34+ * so same-shape-different-name structs get distinct keys. IR passes copy `TypePtr`
35+ * by shared_ptr (types are immutable and never rebuilt via reflection), so the
36+ * pointer stays valid and identical across LowerBreakContinue / ConvertToSSA /
37+ * ConstFoldAndSimplify / InlineHelperCalls.
38+ *
39+ * The parser populates this (via `makeNamedTuple` / struct.create lowering); the
40+ * instance rides on `Program` so codegen can capture it at its entry point.
41+ */
42+class IRDebugInfo {
43+public:
44+ /// Record the ordered field-name list for a named tuple / struct type.
45+ void RegisterTupleFields(const TupleTypePtr& type, std::vector<std::string> fields)
46+ {
47+ if (type == nullptr) {
48+ return;
49+ }
50+ tupleFields_[type.get()] = std::move(fields);
51+ }
52+ 
53+ /// Look up field names by type pointer. Returns nullptr if not registered.
54+ [[nodiscard]] const std::vector<std::string>* GetTupleFields(const TupleType* type) const
55+ {
56+ auto it = tupleFields_.find(type);
57+ return it == tupleFields_.end() ? nullptr : &it->second;
58+ }
59+ 
60+ /// Record the C++ struct type name for a named tuple / struct type (e.g. the tiling
61+ /// Python class name), so codegen emits `struct <name>` instead of a fixed default.
62+ void RegisterTupleName(const TupleTypePtr& type, std::string name)
63+ {
64+ if (type == nullptr) {
65+ return;
66+ }
67+ tupleNames_[type.get()] = std::move(name);
68+ }
69+ 
70+ /// Look up the struct type name by type pointer. Returns nullptr if not registered.
71+ [[nodiscard]] const std::string* GetTupleName(const TupleType* type) const
72+ {
73+ auto it = tupleNames_.find(type);
74+ return it == tupleNames_.end() ? nullptr : &it->second;
75+ }
76+ 
77+ /// Merge another table's entries into this one (later registrations win).
78+ void Merge(const IRDebugInfo& other)
79+ {
80+ for (const auto& [type, fields] : other.tupleFields_) {
81+ tupleFields_[type] = fields;
82+ }
83+ for (const auto& [type, name] : other.tupleNames_) {
84+ tupleNames_[type] = name;
85+ }
86+ }
87+ 
88+private:
89+ std::unordered_map<const TupleType*, std::vector<std::string>> tupleFields_;
90+ std::unordered_map<const TupleType*, std::string> tupleNames_;
91+};
92+ 
93+using IRDebugInfoPtr = std::shared_ptr<IRDebugInfo>;
94+ 
95+} // namespace ir
96+} // namespace pypto
@@ -115,8 +115,9 @@ public:
115 static_assert(115 static_assert(
116 std::is_same_v<T, bool> || std::is_same_v<T, int> || std::is_same_v<T, std::string> ||116 std::is_same_v<T, bool> || std::is_same_v<T, int> || std::is_same_v<T, std::string> ||
117 std::is_same_v<T, double> || std::is_same_v<T, DataType> || std::is_same_v<T, MemorySpace> ||117 std::is_same_v<T, double> || std::is_same_v<T, DataType> || std::is_same_v<T, MemorySpace> ||
118- std::is_same_v<T, std::vector<int>>,118+ std::is_same_v<T, std::vector<int>> || std::is_same_v<T, std::vector<std::string>>,
119- "SetAttrType only accepts: bool, int, std::string, double, DataType, MemorySpace, std::vector<int>");119+ "SetAttrType only accepts: bool, int, std::string, double, DataType, MemorySpace, "
120+ "std::vector<int>, std::vector<std::string>");
120 121 
121 attrs_.emplace(key, std::type_index(typeid(T)));122 attrs_.emplace(key, std::type_index(typeid(T)));
122 }123 }
@@ -0,0 +1,28 @@
1+/*
2+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+ * CANN Open Software License Agreement Version 2.0 (the "License").
4+ * Please refer to the License for details. You may not use this file except in compliance with the License.
5+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+ * See LICENSE in the root of the software repository for the full text of the License.
8+ */
9+ 
10+#ifndef PYPTO_IR_IDENTIFIER_H_
11+#define PYPTO_IR_IDENTIFIER_H_
12+ 
13+#include <regex>
14+#include <string>
15+ 
16+namespace pypto {
17+namespace ir {
18+ 
19+inline bool IsValidIdentifier(const std::string& name)
Jie Yin
Jie YinJie YinJun 11

改成正则表达式吧

likedislike
20+{
21+ static const std::regex kIdentifierPattern(R"([A-Za-z_][A-Za-z0-9_]*)");
22+ return std::regex_match(name, kIdentifierPattern);
23+}
24+ 
25+} // namespace ir
26+} // namespace pypto
27+ 
28+#endif // PYPTO_IR_IDENTIFIER_H_
@@ -17,6 +17,7 @@
17#include <vector>17#include <vector>
18 18 
19#include "ir/core.h"19#include "ir/core.h"
20+#include "ir/debug_info.h"
20#include "ir/expr.h"21#include "ir/expr.h"
21#include "ir/function.h"22#include "ir/function.h"
22#include "ir/reflection/field_traits.h"23#include "ir/reflection/field_traits.h"
@@ -37,17 +38,25 @@ namespace ir {
37 */38 */
38class Program : public IRNode {39class Program : public IRNode {
39public:40public:
40- Program(std::map<std::string, FunctionPtr> functions, std::string name, Span span)41+ Program(std::map<std::string, FunctionPtr> functions, std::string name, Span span,
41- : IRNode(std::move(span)), name_(std::move(name)), functions_(std::move(functions))42+ IRDebugInfoPtr debugInfo = nullptr)
43+ : IRNode(std::move(span)), name_(std::move(name)), functions_(std::move(functions)),
44+ debugInfo_(std::move(debugInfo))
42 {}45 {}
43 46 
44- Program(const std::vector<FunctionPtr>& functions, std::string name, Span span);47+ Program(const std::vector<FunctionPtr>& functions, std::string name, Span span,
48+ IRDebugInfoPtr debugInfo = nullptr);
45 49 
46 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::Program; }50 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::Program; }
47 [[nodiscard]] std::string TypeName() const override { return "Program"; }51 [[nodiscard]] std::string TypeName() const override { return "Program"; }
48 52 
49 [[nodiscard]] FunctionPtr GetFunction(const std::string& name) const;53 [[nodiscard]] FunctionPtr GetFunction(const std::string& name) const;
50 54 
55+ /// Tuple/struct field-name side table; owned by the Program, supplied by the parser.
56+ /// May be null when a Program is built without one (e.g. rebuilt by a pass). Excluded
57+ /// from GetFieldDescriptors -> not part of structural equality / hash / serialization.
58+ [[nodiscard]] const IRDebugInfo* GetDebugInfo() const { return debugInfo_.get(); }
59+ 
51 /**60 /**
52 * \brief Get field descriptors for reflection-based visitation61 * \brief Get field descriptors for reflection-based visitation
53 *62 *
@@ -64,6 +73,8 @@ public:
64public:73public:
65 std::string name_;74 std::string name_;
66 std::map<std::string, FunctionPtr> functions_;75 std::map<std::string, FunctionPtr> functions_;
76+ /// Codegen-level annotation; excluded from reflection (see GetDebugInfo).
77+ IRDebugInfoPtr debugInfo_;
67};78};
68 79 
69using ProgramPtr = std::shared_ptr<const Program>;80using ProgramPtr = std::shared_ptr<const Program>;
@@ -30,7 +30,7 @@ namespace ir {
30class IRVisitor;30class IRVisitor;
31class IRMutator;31class IRMutator;
32 32 
33-enum class SectionKind : uint8_t { Vector = 0, Cube = 1 };33+enum class SectionKind : uint8_t { Vector = 0, Cube = 1, VF = 2 };
34 34 
35inline std::string SectionKindToString(SectionKind kind)35inline std::string SectionKindToString(SectionKind kind)
36{36{
@@ -39,6 +39,8 @@ inline std::string SectionKindToString(SectionKind kind)
39 return "Vector";39 return "Vector";
40 case SectionKind::Cube:40 case SectionKind::Cube:
41 return "Cube";41 return "Cube";
42+ case SectionKind::VF:
43+ return "VF";
42 default:44 default:
43 break;45 break;
44 }46 }
@@ -52,6 +54,8 @@ inline SectionKind StringToSectionKind(const std::string& str)
52 return SectionKind::Vector;54 return SectionKind::Vector;
53 if (str == "Cube")55 if (str == "Cube")
54 return SectionKind::Cube;56 return SectionKind::Cube;
57+ if (str == "VF")
58+ return SectionKind::VF;
55 CHECK(false) << "Unknown SectionKind: " << str;59 CHECK(false) << "Unknown SectionKind: " << str;
56 return SectionKind::Vector;60 return SectionKind::Vector;
57}61}
@@ -107,10 +107,8 @@ void PrintFunctionReturnAnnotation(
107 std::ostream& stream, const std::vector<TypePtr>& return_types,107 std::ostream& stream, const std::vector<TypePtr>& return_types,
108 const std::function<std::string(const TypePtr&)>& print_type);108 const std::function<std::string(const TypePtr&)>& print_type);
109 109 
110-std::string PythonPrint(const IRNodePtr& node, const std::string& prefix = "pl", bool concise = false);110+std::string PythonPrint(const IRNodePtr& node, const std::string& prefix = "ir", bool concise = false);
111-std::string PythonPrint(const TypePtr& type, const std::string& prefix = "pl");111+std::string PythonPrint(const TypePtr& type, const std::string& prefix = "ir");
112-std::string PythonDslPrint(const IRNodePtr& node, const std::string& prefix = "pl");
113-std::string PythonDslPrint(const TypePtr& type, const std::string& prefix = "pl");
114 112 
115} // namespace ir113} // namespace ir
116} // namespace pypto114} // namespace pypto
@@ -476,11 +476,15 @@ public:
476 std::vector<TypePtr> types_; // Types in the tuple476 std::vector<TypePtr> types_; // Types in the tuple
477 477 
478 /**478 /**
479- * \brief Create a tuple type479+ * \brief Create a (positional) tuple type
480+ *
481+ * Field names of named tuples / structs are NOT part of the tuple type. They are
482+ * carried by the parser-populated IRDebugInfo side table (see ir/debug_info.h),
483+ * keyed by the TupleType pointer, so they do not affect structural identity.
480 *484 *
481 * \param types List of types in the tuple485 * \param types List of types in the tuple
482 */486 */
483- explicit TupleType(std::vector<TypePtr> types) : types_(std::move(types)) {}487+ explicit TupleType(std::vector<TypePtr> types);
484 488 
485 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TupleType; }489 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TupleType; }
486 [[nodiscard]] std::string TypeName() const override { return "TupleType"; }490 [[nodiscard]] std::string TypeName() const override { return "TupleType"; }
@@ -26,14 +26,13 @@ namespace ir {
26 26 
27MakeTuple::MakeTuple(std::vector<ExprPtr> elements, Span span) : Expr(std::move(span)), elements_(std::move(elements))27MakeTuple::MakeTuple(std::vector<ExprPtr> elements, Span span) : Expr(std::move(span)), elements_(std::move(elements))
28{28{
29- // Collect types from all element expressions
30 std::vector<TypePtr> elementTypes;29 std::vector<TypePtr> elementTypes;
31 elementTypes.reserve(elements_.size());30 elementTypes.reserve(elements_.size());
32 for (const auto& elem : elements_) {31 for (const auto& elem : elements_) {
33 elementTypes.push_back(elem->GetType());32 elementTypes.push_back(elem->GetType());
34 }33 }
35- 34+ // Positional TupleType. Field names of named tuples / structs are carried by the
36- // Set result type to TupleType35+ // parser-populated IRDebugInfo side table, not on the expression or the type.
37 type_ = std::make_shared<TupleType>(std::move(elementTypes));36 type_ = std::make_shared<TupleType>(std::move(elementTypes));
38}37}
39 38 
@@ -47,6 +47,7 @@ REGISTER_OP("block.matmul")
47 .add_argument("lhs", "Left matrix tile [M,K] (TileType)")47 .add_argument("lhs", "Left matrix tile [M,K] (TileType)")
48 .add_argument("rhs", "Right matrix tile [K,N] (TileType)")48 .add_argument("rhs", "Right matrix tile [K,N] (TileType)")
49 .add_argument("out", "Pre-allocated output tile [M,N] (TileType)")49 .add_argument("out", "Pre-allocated output tile [M,N] (TileType)")
50+ .set_attr<std::string>("phase") // AccPhase: "unspecified" / "partial" / "final" — unit_flag for TMATMUL
50 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,51 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
51 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {52 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
52 return DeduceBlockOutTileType(args, kwargs, "block.matmul", 3);53 return DeduceBlockOutTileType(args, kwargs, "block.matmul", 3);
@@ -60,6 +61,7 @@ REGISTER_OP("block.matmul_acc")
60 .add_argument("lhs", "Left matrix tile [M,K] (TileType)")61 .add_argument("lhs", "Left matrix tile [M,K] (TileType)")
61 .add_argument("rhs", "Right matrix tile [K,N] (TileType)")62 .add_argument("rhs", "Right matrix tile [K,N] (TileType)")
62 .add_argument("out", "Pre-allocated output tile [M,N] (TileType)")63 .add_argument("out", "Pre-allocated output tile [M,N] (TileType)")
64+ .set_attr<std::string>("phase") // AccPhase: "unspecified" / "partial" / "final" — unit_flag for TMATMUL_ACC
63 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,65 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
64 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {66 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
65 return DeduceBlockOutTileType(args, kwargs, "block.matmul_acc", 4);67 return DeduceBlockOutTileType(args, kwargs, "block.matmul_acc", 4);
@@ -134,6 +134,7 @@ REGISTER_OP("block.store")
134 .set_attr<std::string>("relu_pre_mode")134 .set_attr<std::string>("relu_pre_mode")
135 .set_attr<int>("pre_quant_scalar")135 .set_attr<int>("pre_quant_scalar")
136 .set_attr<std::string>("atomic") // "none" or "add"136 .set_attr<std::string>("atomic") // "none" or "add"
137+ .set_attr<std::string>("phase") // STPhase: "unspecified" / "partial" / "final" — unit_flag for TSTORE
137 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,138 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
138 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {139 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
139 CHECK(args.size() == 3) << "block.store requires 3 arguments, got " << args.size();140 CHECK(args.size() == 3) << "block.store requires 3 arguments, got " << args.size();
@@ -167,7 +168,7 @@ REGISTER_OP("block.store_fp")
167 return out_type;168 return out_type;
168 });169 });
169 170 
170-// block.move: (src_tile, out) -> TileType (out's type)171+// block.move: (src_tile, out, [offset]) -> TileType (out's type)
171REGISTER_OP("block.move")172REGISTER_OP("block.move")
172 .set_op_category("BlockOp")173 .set_op_category("BlockOp")
173 .set_description(174 .set_description(
@@ -175,14 +176,15 @@ REGISTER_OP("block.move")
175 "The TMOV variant is determined by the output tile's memory space.")176 "The TMOV variant is determined by the output tile's memory space.")
176 .add_argument("src", "Source tile (TileType)")177 .add_argument("src", "Source tile (TileType)")
177 .add_argument("out", "Pre-allocated destination tile (TileType)")178 .add_argument("out", "Pre-allocated destination tile (TileType)")
179+ .add_argument("offset", "Optional 2D offset [offset_m, offset_k] for sub-tile extraction (TupleType)")
178 .set_attr<std::string>("acc_to_vec_mode")180 .set_attr<std::string>("acc_to_vec_mode")
179 .set_attr<std::string>("relu_pre_mode")181 .set_attr<std::string>("relu_pre_mode")
180 .set_attr<int>("pre_quant_scalar")182 .set_attr<int>("pre_quant_scalar")
181 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,183 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
182 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {184 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
183- CHECK(args.size() == 2) << "The operator block.move requires 2 arguments, but got " << args.size();185+ CHECK(args.size() == 2 || args.size() == 3) << "The operator block.move requires 2 or 3 arguments, but got " << args.size();
184- auto out_type = As<TileType>(args.back()->GetType());186+ auto out_type = As<TileType>(args[1]->GetType());
185- CHECK(out_type) << "block.move: last argument (out) must be TileType";187+ CHECK(out_type) << "block.move: second argument (out) must be TileType";
186 return out_type;188 return out_type;
187 });189 });
188 190 
@@ -236,29 +238,30 @@ REGISTER_OP("block.ub_copy")
236 return DeduceBlockOutTileType(args, kwargs, "block.ub_copy", 2);238 return DeduceBlockOutTileType(args, kwargs, "block.ub_copy", 2);
237 });239 });
238 240 
239-// block.ssbuf_store: (offset) -> void241+// block.ssbuf_store: (struct_var, offset) -> void
240// Copies raw bytes of a named C++ struct into SSBUF at byte address offset.242// Copies raw bytes of a named C++ struct into SSBUF at byte address offset.
243+// args[0] is the named-tuple IR Var bound to the struct value; args[1] is the offset.
241REGISTER_OP("block.ssbuf_store")244REGISTER_OP("block.ssbuf_store")
242 .set_op_category("BlockOp")245 .set_op_category("BlockOp")
243 .set_description("Block explicit-output SSBUF store: copy a named struct into SSBUF at a byte address offset.")246 .set_description("Block explicit-output SSBUF store: copy a named struct into SSBUF at a byte address offset.")
247+ .add_argument("struct_var", "Named-struct IR Var to copy from")
244 .add_argument("offset", "SSBUF byte address offset")248 .add_argument("offset", "SSBUF byte address offset")
245 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,249 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
246 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {250 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
247- CHECK(args.size() == 1) << "The operator block.ssbuf_store requires 1 argument (offset), but got "251+ CHECK(args.size() == 2) << "The operator block.ssbuf_store requires 2 arguments (struct_var, offset)";
248- << args.size();
249 return std::make_shared<ScalarType>(DataType::INDEX);252 return std::make_shared<ScalarType>(DataType::INDEX);
250 });253 });
251 254 
252-// block.ssbuf_load: (offset) -> void255+// block.ssbuf_load: (struct_var, offset) -> void
253// Copies raw bytes from SSBUF at byte address offset into a named C++ struct.256// Copies raw bytes from SSBUF at byte address offset into a named C++ struct.
254REGISTER_OP("block.ssbuf_load")257REGISTER_OP("block.ssbuf_load")
255 .set_op_category("BlockOp")258 .set_op_category("BlockOp")
256 .set_description("Block explicit-output SSBUF load: copy SSBUF bytes at a byte address offset into a named struct.")259 .set_description("Block explicit-output SSBUF load: copy SSBUF bytes at a byte address offset into a named struct.")
260+ .add_argument("struct_var", "Named-struct IR Var to copy into")
257 .add_argument("offset", "SSBUF byte address offset")261 .add_argument("offset", "SSBUF byte address offset")
258 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,262 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
259 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {263 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
260- CHECK(args.size() == 1) << "The operator block.ssbuf_load requires 1 argument (offset), but got "264+ CHECK(args.size() == 2) << "The operator block.ssbuf_load requires 2 arguments (struct_var, offset)";
261- << args.size();
262 return std::make_shared<ScalarType>(DataType::INDEX);265 return std::make_shared<ScalarType>(DataType::INDEX);
263 });266 });
264 267 
@@ -12,73 +12,107 @@
12 * @file block_ops/struct_ops.cpp12 * @file block_ops/struct_ops.cpp
13 * \brief Struct array operations for clean C++ codegen.13 * \brief Struct array operations for clean C++ codegen.
14 *14 *
15- * These ops translate pl.struct arrays with dynamic indexing into15+ * - struct.create: Expression op that returns a named TupleType. Lowered by
16- * C++ struct definitions + array declarations + direct subscript access.16+ * the CCE backend to ``Name var = {.f0=v0, ...};``.
17- *17+ * - struct.create_array: Expression op that returns TupleType(N × named tuple).
18- * - struct.declare: emit struct type + array declaration18+ * Lowered to ``Name var[N] = {};`` plus per-slot field-init lines.
19- * - struct.get: read arr[idx].field
20- * - struct.set: write arr[idx].field = val
21 */19 */
22 20 
23#include <any>21#include <any>
22+#include <set>
24#include <string>23#include <string>
25#include <utility>24#include <utility>
26#include <vector>25#include <vector>
27 26 
27+#include "core/logging.h"
28#include "ir/expr.h"28#include "ir/expr.h"
29+#include "ir/identifier.h"
29#include "ir/op_registry.h"30#include "ir/op_registry.h"
30#include "ir/type.h"31#include "ir/type.h"
32+#include "tilefwk/error.h"
31 33 
32namespace pypto {34namespace pypto {
33namespace ir {35namespace ir {
34 36 
35-// struct.declare: () -> void (side effect: C++ struct + array declaration)37+REGISTER_OP("struct.create")
36-REGISTER_OP("struct.declare")
37 .set_op_category("StructOp")38 .set_op_category("StructOp")
38- .set_description("Declare a C++ struct type and array from pl.struct list.")39+ .set_description(
Jie Yin
Jie YinJie YinJun 11

改动较大的OP,补充UT

likedislike
wuzhongxin
wuzhongxin
Jun 11 Comments:
likedislike
39- .no_argument()40+ "Materialize a named tuple into a C++ struct. args are field values; kwargs `name` "
41+ "is the C++ struct type name and `fields` is the list of field names. Result type is "
42+ "TupleType(field_types, dbgName=fields). Must be let-bound to a Var by the producer.")
43+ .add_argument("...", "Field value expressions in declaration order")
44+ .set_attr<std::string>("name")
45+ .set_attr<std::vector<std::string>>("fields")
40 .f_deduce_type(46 .f_deduce_type(
41- [](const std::vector<ExprPtr>& /*args*/,47+ [](const std::vector<ExprPtr>& args,
42- const std::vector<std::pair<std::string, std::any>>& /*kwargs*/) -> TypePtr {48+ const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {
43- // No return type - used as EvalStmt (side effect)49+ std::string struct_name;
44- return std::make_shared<ScalarType>(DataType::INDEX);50+ std::vector<std::string> fields;
51+ bool has_name = false;
52+ bool has_fields = false;
53+ for (const auto& [key, value] : kwargs) {
54+ if (key == "name") {
55+ struct_name = std::any_cast<std::string>(value);
56+ has_name = true;
57+ } else if (key == "fields") {
58+ fields = std::any_cast<std::vector<std::string>>(value);
59+ has_fields = true;
60+ }
61+ }
62+ CHECK(has_name) << "struct.create requires kwarg 'name' (C++ struct type name)";
63+ CHECK(has_fields) << "struct.create requires kwarg 'fields' (list of field names)";
64+ CHECK(IsValidIdentifier(struct_name))
65+ << "struct.create 'name' must be a valid C identifier, got '" << struct_name << "'";
66+ CHECK(fields.size() == args.size())
67+ << "struct.create: fields count (" << fields.size() << ") must match args count (" << args.size()
68+ << ")";
69+ std::set<std::string> seen;
70+ for (const auto& f : fields) {
71+ CHECK(IsValidIdentifier(f)) << "struct.create field name '" << f << "' is not a valid identifier";
72+ CHECK(seen.insert(f).second) << "struct.create field name '" << f << "' is duplicated";
73+ }
74+ std::vector<TypePtr> field_types;
75+ field_types.reserve(args.size());
76+ for (size_t i = 0; i < args.size(); ++i) {
77+ CHECK(args[i]) << "struct.create arg #" << i << " is null";
78+ field_types.push_back(args[i]->GetType());
79+ }
80+ // Positional TupleType: field names live in IRDebugInfo (registered by the
Jie Yin
Jie YinJie YinJun 11

用AI写的?

likedislike
81+ // parser from the op's 'fields' kwarg), not on the type.
82+ (void)fields;
83+ return std::make_shared<TupleType>(std::move(field_types));
45 });84 });
46 85 
47-// struct.get: (index) -> int64 (returns field value)
48-REGISTER_OP("struct.get")
49- .set_op_category("StructOp")
50- .set_description("Read a field from a struct array at a dynamic index.")
51- .add_argument("index", "Array index expression")
52- .f_deduce_type(
53- [](const std::vector<ExprPtr>& /*args*/,
54- const std::vector<std::pair<std::string, std::any>>& /*kwargs*/) -> TypePtr {
55- // Struct fields are int64_t scalars
56- return std::make_shared<ScalarType>(DataType::INDEX);
57- });
58- 
59-// struct.set: (index, value) -> void (side effect: write to array)
60REGISTER_OP("struct.set")86REGISTER_OP("struct.set")
61 .set_op_category("StructOp")87 .set_op_category("StructOp")
62- .set_description("Write a field in a struct array at a dynamic index.")88+ .set_description(
63- .add_argument("index", "Array index expression")89+ "Statement side-effect call: write one struct field. args are (base, value); kwarg `field` "
64- .add_argument("value", "Value to write")90+ "is the C++ field name (same naming convention as struct.create's `fields`). Lowered by the "
91+ "CCE backend to `base.field = value;`. Must be used inside an EvalStmt, not as an RHS value.")
92+ .add_argument("base", "Struct instance (named TupleType)")
93+ .add_argument("value", "New field value expression")
94+ .set_attr<std::string>("field")
65 .f_deduce_type(95 .f_deduce_type(
66- [](const std::vector<ExprPtr>& /*args*/,96+ [](const std::vector<ExprPtr>& args,
67- const std::vector<std::pair<std::string, std::any>>& /*kwargs*/) -> TypePtr {97+ const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {
68- // No meaningful return type - used as EvalStmt (side effect)98+ CHECK(args.size() == 2) << "struct.set requires 2 args (base, value), got " << args.size();
69- return std::make_shared<ScalarType>(DataType::INDEX);99+ CHECK(args[0]) << "struct.set: base arg is null";
100+ CHECK(args[1]) << "struct.set: value arg is null";
101+ bool has_field = false;
102+ for (const auto& [key, value] : kwargs) {
103+ if (key == "field") {
104+ CHECK(IsValidIdentifier(std::any_cast<std::string>(value)))
105+ << "struct.set 'field' must be a valid identifier";
106+ has_field = true;
107+ }
108+ }
109+ CHECK(has_field) << "struct.set requires kwarg 'field' (the C++ field name to write)";
110+ CHECK(args[0]->GetType()->GetKind() == ObjectKind::TupleType)
111+ << "struct.set: base must have TupleType";
112+ // Statement side effect; the discarded result type mirrors the struct being written.
113+ return args[0]->GetType();
70 });114 });
71 115 
72-// struct.ref: (index) -> void (side effect: C++ reference declaration)
73-REGISTER_OP("struct.ref")
74- .set_op_category("StructOp")
75- .set_description("Declare a C++ reference to a struct array element: auto& var = arr[idx];")
76- .add_argument("index", "Array index expression")
77- .f_deduce_type(
78- [](const std::vector<ExprPtr>& /*args*/,
79- const std::vector<std::pair<std::string, std::any>>& /*kwargs*/) -> TypePtr {
80- return std::make_shared<ScalarType>(DataType::INDEX);
81- });
82 116 
83} // namespace ir117} // namespace ir
84} // namespace pypto118} // namespace pypto
@@ -15,6 +15,7 @@
15 15 
16#include "ir/expr.h"16#include "ir/expr.h"
17#include "ir/kind_traits.h"17#include "ir/kind_traits.h"
18+#include "ir/memref.h"
18#include "ir/op_registry.h"19#include "ir/op_registry.h"
19#include "ir/type.h"20#include "ir/type.h"
20 21 
@@ -33,15 +34,15 @@ TypePtr DeduceUnknownType(
33 return GetUnknownType();34 return GetUnknownType();
34}35}
35 36 
36-bool IsDcciScalarOffset(const ExprPtr& offset)37+bool IsIntScalar(const ExprPtr& expr)
37{38{
38- auto scalar_type = As<ScalarType>(offset->GetType());39+ auto scalar_type = As<ScalarType>(expr->GetType());
39 return scalar_type && (scalar_type->dtype_.IsInt() || scalar_type->dtype_ == DataType::INDEX);40 return scalar_type && (scalar_type->dtype_.IsInt() || scalar_type->dtype_ == DataType::INDEX);
40}41}
41 42 
42bool IsDcciTensorOffset(const ExprPtr& offset)43bool IsDcciTensorOffset(const ExprPtr& offset)
43{44{
44- if (IsDcciScalarOffset(offset)) {45+ if (IsIntScalar(offset)) {
45 return true;46 return true;
46 }47 }
47 auto tuple = As<MakeTuple>(offset);48 auto tuple = As<MakeTuple>(offset);
@@ -49,13 +50,89 @@ bool IsDcciTensorOffset(const ExprPtr& offset)
49 return false;50 return false;
50 }51 }
51 for (const auto& element : tuple->elements_) {52 for (const auto& element : tuple->elements_) {
52- if (!IsDcciScalarOffset(element)) {53+ if (!IsIntScalar(element)) {
53 return false;54 return false;
54 }55 }
55 }56 }
56 return true;57 return true;
57}58}
58 59 
60+TypePtr DeduceSyncAllType(
61+ const std::vector<ExprPtr>& args,
62+ const std::vector<std::pair<std::string, std::any>>& kwargs)
63+{
64+ std::string mode = "hard";
65+ std::string core_type = "mix";
66+ for (const auto& [key, value] : kwargs) {
67+ if (key == "mode") mode = std::any_cast<std::string>(value);
68+ if (key == "core_type") core_type = std::any_cast<std::string>(value);
69+ }
70+ 
71+ if (mode == "hard") {
72+ // args[0] is an empty MakeTuple for hard mode
73+ if (!args.empty()) {
74+ auto tuple = As<MakeTuple>(args[0]);
75+ CHECK(!tuple || tuple->elements_.empty())
76+ << "system.sync_all hard mode does not accept workspace arguments";
77+ }
78+ } else if (mode == "soft") {
79+ CHECK(core_type == "aiv_only" || core_type == "aic_only" || core_type == "mix")
80+ << "system.sync_all soft mode core_type must be aiv_only, aic_only, or mix, got '" << core_type << "'";
81+ CHECK(args.size() == 1) << "system.sync_all soft mode requires exactly 1 argument (workspaces list), got "
82+ << args.size();
83+ 
84+ // Unpack MakeTuple elements and classify by type
85+ auto tuple = As<MakeTuple>(args[0]);
86+ CHECK(tuple) << "system.sync_all soft mode: workspaces argument must be a list/tuple";
87+ 
88+ bool has_gm = false, has_ub = false, has_l1 = false, has_used_cores = false;
89+ for (const auto& elem : tuple->elements_) {
90+ auto elem_type = elem->GetType();
91+ if (As<TensorType>(elem_type)) {
92+ CHECK(!has_gm) << "system.sync_all: duplicate gm_workspace (TensorType) in workspaces list";
93+ has_gm = true;
94+ } else if (auto tile_type = As<TileType>(elem_type)) {
95+ CHECK(tile_type->memref_.has_value())
96+ << "system.sync_all: workspace tile must have memref";
97+ auto space = tile_type->memref_.value()->memorySpace_;
98+ if (space == MemorySpace::Vec) {
99+ CHECK(!has_ub) << "system.sync_all: duplicate ub_workspace (Vec TileType) in workspaces list";
100+ has_ub = true;
101+ } else if (space == MemorySpace::Mat) {
102+ CHECK(!has_l1) << "system.sync_all: duplicate l1_workspace (Mat TileType) in workspaces list";
103+ has_l1 = true;
104+ } else {
105+ CHECK(false) << "system.sync_all: workspace tile must be Vec or Mat, got "
106+ << static_cast<int>(space);
107+ }
108+ } else if (IsIntScalar(elem)) {
109+ CHECK(!has_used_cores) << "system.sync_all: duplicate used_cores (int scalar) in workspaces list";
110+ has_used_cores = true;
111+ } else {
112+ CHECK(false) << "system.sync_all: unrecognized element type in workspaces list: "
113+ << elem_type->TypeName();
114+ }
115+ }
116+ 
117+ // Validate required workspaces per core_type
118+ CHECK(has_gm) << "system.sync_all soft mode: workspaces list must contain a gm_workspace (TensorType)";
119+ if (core_type == "aiv_only") {
120+ CHECK(has_ub) << "system.sync_all soft aiv_only: workspaces list must contain ub_workspace (Vec TileType)";
121+ CHECK(!has_l1) << "system.sync_all soft aiv_only: l1_workspace (Mat TileType) is not allowed";
122+ } else if (core_type == "aic_only") {
123+ CHECK(has_l1) << "system.sync_all soft aic_only: workspaces list must contain l1_workspace (Mat TileType)";
124+ CHECK(!has_ub) << "system.sync_all soft aic_only: ub_workspace (Vec TileType) is not allowed";
125+ } else { // mix
126+ CHECK(has_ub) << "system.sync_all soft mix: workspaces list must contain ub_workspace (Vec TileType)";
127+ CHECK(has_l1) << "system.sync_all soft mix: workspaces list must contain l1_workspace (Mat TileType)";
128+ }
129+ } else {
130+ CHECK(false) << "system.sync_all: mode must be 'hard' or 'soft', got '" << mode << "'";
131+ }
132+ 
133+ return GetUnknownType();
134+}
135+ 
59} // namespace136} // namespace
60 137 
61// ============================================================================138// ============================================================================
@@ -168,15 +245,17 @@ REGISTER_OP("system.wait_cross_core_dyn")
168 .f_deduce_type(DeduceUnknownType);245 .f_deduce_type(DeduceUnknownType);
169 246 
170// Register system.sync_all (Global Core Synchronization)247// Register system.sync_all (Global Core Synchronization)
171-// Attributes: set_pipe, wait_pipe248+// Delegates to pto-isa SYNCALL<SyncAllMode, SyncCoreType>() / pto.syncall MLIR op.
249+// Hard mode (default): no arguments.
250+// Soft mode: workspaces list passed as a single MakeTuple arg.
251+// Backend codegen dispatches by type: TensorType→gm, Vec TileType→ub, Mat TileType→l1, ScalarType→used_cores.
172REGISTER_OP("system.sync_all")252REGISTER_OP("system.sync_all")
173- .set_description("Global core synchronization")253+ .set_description("Global core synchronization (hard or soft mode)")
174 .set_op_category("SyncOp")254 .set_op_category("SyncOp")
175- .no_argument()255+ .add_argument("workspaces", "Soft mode workspace list as MakeTuple (Tensor gm + Tile ub/l1 + optional int used_cores)")
176- .set_attr<bool>("aiv_only")256+ .set_attr<std::string>("mode") // "hard" or "soft"
177- .set_attr<int>("trigger_pipe")257+ .set_attr<std::string>("core_type") // "aiv_only", "aic_only", "mix"
178- .set_attr<int>("wait_pipe")258+ .f_deduce_type(DeduceSyncAllType);
179- .f_deduce_type(DeduceUnknownType);
180 259 
181// Register system.dcci (Data Cache Clean and Invalid)260// Register system.dcci (Data Cache Clean and Invalid)
182// Arguments:261// Arguments:
@@ -205,7 +284,7 @@ REGISTER_OP("system.dcci")
205 << "or a scalar integer element offset";284 << "or a scalar integer element offset";
206 }285 }
207 if (As<TileType>(target_type) && args.size() == 2) {286 if (As<TileType>(target_type) && args.size() == 2) {
208- CHECK(IsDcciScalarOffset(args[1]))287+ CHECK(IsIntScalar(args[1]))
209 << "system.dcci: tile target offset must be a scalar integer element offset (int or index Expr).\n"288 << "system.dcci: tile target offset must be a scalar integer element offset (int or index Expr).\n"
210 << " Example: dcci(tile, 0) - cache invalidation starting at element offset 0\n"289 << " Example: dcci(tile, 0) - cache invalidation starting at element offset 0\n"
211 << " Note: Use list/tuple offset only for tensor targets";290 << " Note: Use list/tuple offset only for tensor targets";
@@ -257,7 +336,7 @@ REGISTER_OP("system.mutex_lock_dyn")
257 .set_attr<int>("pipe")336 .set_attr<int>("pipe")
258 .set_attr<int>("mode")337 .set_attr<int>("mode")
259 .set_attr<int>("max_mutex_id")338 .set_attr<int>("max_mutex_id")
260- .set_attr<std::vector<int>>("buf_id_values")339+ .set_attr<std::vector<int>>("mutex_ids")
261 .f_deduce_type(DeduceUnknownType);340 .f_deduce_type(DeduceUnknownType);
262 341 
263// Register system.mutex_unlock_dyn (Mutex::Unlock with dynamic mutex_id, A5)342// Register system.mutex_unlock_dyn (Mutex::Unlock with dynamic mutex_id, A5)
@@ -268,7 +347,7 @@ REGISTER_OP("system.mutex_unlock_dyn")
268 .set_attr<int>("pipe")347 .set_attr<int>("pipe")
269 .set_attr<int>("mode")348 .set_attr<int>("mode")
270 .set_attr<int>("max_mutex_id")349 .set_attr<int>("max_mutex_id")
271- .set_attr<std::vector<int>>("buf_id_values")350+ .set_attr<std::vector<int>>("mutex_ids")
272 .f_deduce_type(DeduceUnknownType);351 .f_deduce_type(DeduceUnknownType);
273 352 
274// ============================================================================353// ============================================================================
@@ -307,5 +386,22 @@ REGISTER_OP("system.reset_mask")
307 .no_argument()386 .no_argument()
308 .f_deduce_type(DeduceUnknownType);387 .f_deduce_type(DeduceUnknownType);
309 388 
389+// ============================================================================
390+// Matmul Layout Transform Op — CCE-mode only (A5)
391+// ----------------------------------------------------------------------------
392+// Controls the fixpipe L0C drain direction. When enabled, fixpipe drains L0C
393+// in N-direction (column-first) instead of M-direction (row-first), allowing
394+// cube and fixpipe to access L0C along orthogonal axes within the same slot.
395+// This eliminates RAW hazards and enables single-buffer L0C with K-accumulation.
396+// Maps to AscendC SDK: SetMMLayoutTransform(bool).
397+// ============================================================================
398+ 
399+REGISTER_OP("system.set_mm_layout_transform")
400+ .set_description("Set matmul layout transform for fixpipe N-direction drain (A5)")
401+ .set_op_category("SyncOp")
402+ .no_argument()
403+ .set_attr<int>("enabled")
404+ .f_deduce_type(DeduceUnknownType);
405+ 
310} // namespace ir406} // namespace ir
311} // namespace pypto407} // namespace pypto
@@ -22,6 +22,7 @@
22#include <utility>22#include <utility>
23#include <vector>23#include <vector>
24 24 
25+#include "core/any_cast.h"
25#include "core/logging.h"26#include "core/logging.h"
26#include "ir/kind_traits.h"27#include "ir/kind_traits.h"
27#include "ir/op_registry.h"28#include "ir/op_registry.h"
@@ -43,6 +44,11 @@ TypePtr DeduceVFScalarType(
43 [[maybe_unused]] const std::vector<ExprPtr>& args,44 [[maybe_unused]] const std::vector<ExprPtr>& args,
44 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)45 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
45{46{
47+ for (const auto& [key, value] : kwargs) {
48+ if (key == "dtype") {
49+ return std::make_shared<ScalarType>(AnyCast<DataType>(value, "kwarg: dtype"));
50+ }
51+ }
46 return std::make_shared<ScalarType>(DataType::FP32);52 return std::make_shared<ScalarType>(DataType::FP32);
47}53}
48 54 
@@ -53,7 +59,7 @@ TypePtr DeduceVFMaskType(
53 return std::make_shared<ScalarType>(DataType::UINT16);59 return std::make_shared<ScalarType>(DataType::UINT16);
54}60}
55 61 
56-TypePtr DeduceVFFromFirstArg(62+TypePtr DeduceVFFromDstArg(
57 [[maybe_unused]] const std::vector<ExprPtr>& args,63 [[maybe_unused]] const std::vector<ExprPtr>& args,
58 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)64 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
59{65{
@@ -62,42 +68,8 @@ TypePtr DeduceVFFromFirstArg(
62 }68 }
63 return std::make_shared<ScalarType>(DataType::FP32);69 return std::make_shared<ScalarType>(DataType::FP32);
64}70}
65- 
66-TypePtr DeduceVFFromSecondArg(
67- [[maybe_unused]] const std::vector<ExprPtr>& args,
68- [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
69-{
70- if (args.size() >= 0x2) {
71- return args[1]->GetType();
72- }
73- return std::make_shared<ScalarType>(DataType::FP32);
74-}
75- 
76-TypePtr DeduceVFFromDstArg(
77- [[maybe_unused]] const std::vector<ExprPtr>& args,
78- [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
79-{
80- if (args.size() >= 0x3) {
81- return args[2]->GetType();
82- }
83- return std::make_shared<ScalarType>(DataType::FP32);
84-}
85- 
86} // namespace71} // namespace
87 72 
88-// Scope markers
89-REGISTER_OP("vf.vf_scope_enter")
90- .set_op_category("VFOp")
91- .set_description("VF scope enter marker")
92- .no_argument()
93- .f_deduce_type(DeduceVFUnknownType);
94- 
95-REGISTER_OP("vf.vf_scope_exit")
96- .set_op_category("VFOp")
97- .set_description("VF scope exit marker")
98- .no_argument()
99- .f_deduce_type(DeduceVFUnknownType);
100- 
101// Register declaration73// Register declaration
102REGISTER_OP("vf.RegTensor")74REGISTER_OP("vf.RegTensor")
103 .set_op_category("VFOp")75 .set_op_category("VFOp")
@@ -117,18 +89,23 @@ REGISTER_OP("vf.Duplicate")
117 .set_op_category("VFOp")89 .set_op_category("VFOp")
118 .set_description("Scalar broadcast to register")90 .set_description("Scalar broadcast to register")
119 .add_argument("dst", "Destination register")91 .add_argument("dst", "Destination register")
120- .f_deduce_type(DeduceVFFromFirstArg);92+ .add_argument("scalar", "Scalar value to broadcast")
93+ .add_argument("mask", "Mask register")
94+ .f_deduce_type(DeduceVFFromDstArg);
121 95 
122// Data transfer96// Data transfer
123REGISTER_OP("vf.LoadAlign")97REGISTER_OP("vf.LoadAlign")
124 .set_op_category("VFOp")98 .set_op_category("VFOp")
125 .set_description("Load aligned data from UB to register")99 .set_description("Load aligned data from UB to register")
126 .add_argument("dst", "Destination register")100 .add_argument("dst", "Destination register")
127- .f_deduce_type(DeduceVFFromFirstArg);101+ .add_argument("src", "Source UB pointer")
102+ .add_argument("offset", "Element offset into UB")
103+ .f_deduce_type(DeduceVFFromDstArg);
128 104 
129REGISTER_OP("vf.StoreAlign")105REGISTER_OP("vf.StoreAlign")
130 .set_op_category("VFOp")106 .set_op_category("VFOp")
131 .set_description("Store aligned data from register to UB")107 .set_description("Store aligned data from register to UB")
108+ .add_argument("dst", "Destination UB pointer")
132 .add_argument("src", "Source register")109 .add_argument("src", "Source register")
133 .add_argument("mask", "Mask register")110 .add_argument("mask", "Mask register")
134 .f_deduce_type(DeduceVFUnknownType);111 .f_deduce_type(DeduceVFUnknownType);
@@ -137,96 +114,137 @@ REGISTER_OP("vf.StoreAlign")
137REGISTER_OP("vf.Max")114REGISTER_OP("vf.Max")
138 .set_op_category("VFOp")115 .set_op_category("VFOp")
139 .set_description("Vector maximum")116 .set_description("Vector maximum")
117+ .add_argument("dst", "Destination register")
140 .add_argument("src0", "Source register 0")118 .add_argument("src0", "Source register 0")
141 .add_argument("src1", "Source register 1")119 .add_argument("src1", "Source register 1")
142- .add_argument("dst", "Destination register")
143 .add_argument("mask", "Mask register")120 .add_argument("mask", "Mask register")
144 .f_deduce_type(DeduceVFFromDstArg);121 .f_deduce_type(DeduceVFFromDstArg);
145 122 
146REGISTER_OP("vf.Add")123REGISTER_OP("vf.Add")
147 .set_op_category("VFOp")124 .set_op_category("VFOp")
148 .set_description("Vector addition")125 .set_description("Vector addition")
126+ .add_argument("dst", "Destination register")
149 .add_argument("src0", "Source register 0")127 .add_argument("src0", "Source register 0")
150 .add_argument("src1", "Source register 1")128 .add_argument("src1", "Source register 1")
151- .add_argument("dst", "Destination register")
152 .add_argument("mask", "Mask register")129 .add_argument("mask", "Mask register")
153 .f_deduce_type(DeduceVFFromDstArg);130 .f_deduce_type(DeduceVFFromDstArg);
154 131 
155REGISTER_OP("vf.Sub")132REGISTER_OP("vf.Sub")
156 .set_op_category("VFOp")133 .set_op_category("VFOp")
157 .set_description("Vector subtraction")134 .set_description("Vector subtraction")
135+ .add_argument("dst", "Destination register")
158 .add_argument("src0", "Source register 0")136 .add_argument("src0", "Source register 0")
159 .add_argument("src1", "Source register 1")137 .add_argument("src1", "Source register 1")
138+ .add_argument("mask", "Mask register")
139+ .f_deduce_type(DeduceVFFromDstArg);
140+ 
141+REGISTER_OP("vf.And")
142+ .set_op_category("VFOp")
143+ .set_description("Bitwise AND")
160 .add_argument("dst", "Destination register")144 .add_argument("dst", "Destination register")
145+ .add_argument("src0", "Source register 0")
146+ .add_argument("src1", "Source register 1")
147+ .add_argument("mask", "Mask register")
148+ .f_deduce_type(DeduceVFFromDstArg);
149+ 
150+REGISTER_OP("vf.Xor")
151+ .set_op_category("VFOp")
152+ .set_description("Bitwise XOR")
153+ .add_argument("dst", "Destination register")
154+ .add_argument("src0", "Source register 0")
155+ .add_argument("src1", "Source register 1")
161 .add_argument("mask", "Mask register")156 .add_argument("mask", "Mask register")
162 .f_deduce_type(DeduceVFFromDstArg);157 .f_deduce_type(DeduceVFFromDstArg);
163 158 
164REGISTER_OP("vf.Mul")159REGISTER_OP("vf.Mul")
165 .set_op_category("VFOp")160 .set_op_category("VFOp")
166 .set_description("Vector multiplication")161 .set_description("Vector multiplication")
162+ .add_argument("dst", "Destination register")
167 .add_argument("src0", "Source register 0")163 .add_argument("src0", "Source register 0")
168 .add_argument("src1", "Source register 1")164 .add_argument("src1", "Source register 1")
169- .add_argument("dst", "Destination register")165+ .add_argument("mask", "Mask register")
166+ .f_deduce_type(DeduceVFFromDstArg);
167+ 
168+REGISTER_OP("vf.MulAddDst")
169+ .set_op_category("VFOp")
170+ .set_description("Fused multiply-add (FMA): dst = src0 * src1 + dst (hardware vmadd)")
171+ .add_argument("dst", "Destination/accumulator register (read+write)")
172+ .add_argument("src0", "Source register 0 (multiplicand)")
173+ .add_argument("src1", "Source register 1 (multiplicand)")
170 .add_argument("mask", "Mask register")174 .add_argument("mask", "Mask register")
171 .f_deduce_type(DeduceVFFromDstArg);175 .f_deduce_type(DeduceVFFromDstArg);
172 176 
173REGISTER_OP("vf.Div")177REGISTER_OP("vf.Div")
174 .set_op_category("VFOp")178 .set_op_category("VFOp")
175 .set_description("Vector division")179 .set_description("Vector division")
180+ .add_argument("dst", "Destination register")
176 .add_argument("src0", "Source register 0")181 .add_argument("src0", "Source register 0")
177 .add_argument("src1", "Source register 1")182 .add_argument("src1", "Source register 1")
178- .add_argument("dst", "Destination register")
179 .add_argument("mask", "Mask register")183 .add_argument("mask", "Mask register")
180 .f_deduce_type(DeduceVFFromDstArg);184 .f_deduce_type(DeduceVFFromDstArg);
181 185 
186+REGISTER_OP("vf.ShiftRights")
187+ .set_op_category("VFOp")
188+ .set_description("Right shift")
189+ .add_argument("dst", "Destination register")
190+ .add_argument("src", "Source register")
191+ .add_argument("shift_bits", "Number of bits to shift")
192+ .add_argument("mask", "Mask register")
193+ .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
194+ [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {
195+ if (!args.empty()) return args[0]->GetType();
196+ return std::make_shared<ScalarType>(DataType::UINT32);
197+ });
198+ 
182REGISTER_OP("vf.Muls")199REGISTER_OP("vf.Muls")
183 .set_op_category("VFOp")200 .set_op_category("VFOp")
184 .set_description("Scalar multiplication")201 .set_description("Scalar multiplication")
185- .add_argument("src", "Source register")
186 .add_argument("dst", "Destination register")202 .add_argument("dst", "Destination register")
203+ .add_argument("src", "Source register")
204+ .add_argument("scalar", "Scalar multiplier")
187 .add_argument("mask", "Mask register")205 .add_argument("mask", "Mask register")
188- .f_deduce_type(DeduceVFFromSecondArg);206+ .f_deduce_type(DeduceVFFromDstArg);
189 207 
190REGISTER_OP("vf.Ln")208REGISTER_OP("vf.Ln")
191 .set_op_category("VFOp")209 .set_op_category("VFOp")
192 .set_description("Natural logarithm")210 .set_description("Natural logarithm")
193- .add_argument("src", "Source register")
194 .add_argument("dst", "Destination register")211 .add_argument("dst", "Destination register")
212+ .add_argument("src", "Source register")
195 .add_argument("mask", "Mask register")213 .add_argument("mask", "Mask register")
196- .f_deduce_type(DeduceVFFromSecondArg);214+ .f_deduce_type(DeduceVFFromDstArg);
197 215 
198REGISTER_OP("vf.FusedExpSub")216REGISTER_OP("vf.FusedExpSub")
199 .set_op_category("VFOp")217 .set_op_category("VFOp")
200 .set_description("Fused exp(src - max)")218 .set_description("Fused exp(src - max)")
219+ .add_argument("dst", "Destination register")
201 .add_argument("src", "Source register")220 .add_argument("src", "Source register")
202 .add_argument("max", "Max register")221 .add_argument("max", "Max register")
203- .add_argument("dst", "Destination register")
204 .add_argument("mask", "Mask register")222 .add_argument("mask", "Mask register")
205 .f_deduce_type(DeduceVFFromDstArg);223 .f_deduce_type(DeduceVFFromDstArg);
206 224 
207REGISTER_OP("vf.Cast")225REGISTER_OP("vf.Cast")
208 .set_op_category("VFOp")226 .set_op_category("VFOp")
209 .set_description("Type conversion")227 .set_description("Type conversion")
210- .add_argument("src", "Source register")
211 .add_argument("dst", "Destination register")228 .add_argument("dst", "Destination register")
229+ .add_argument("src", "Source register")
212 .add_argument("mask", "Mask register")230 .add_argument("mask", "Mask register")
213- .f_deduce_type(DeduceVFFromSecondArg);231+ .f_deduce_type(DeduceVFFromDstArg);
214 232 
215REGISTER_OP("vf.DeInterleave")233REGISTER_OP("vf.DeInterleave")
216 .set_op_category("VFOp")234 .set_op_category("VFOp")
217 .set_description("De-interleave")235 .set_description("De-interleave")
218- .add_argument("src0", "Source register 0")
219- .add_argument("src1", "Source register 1")
220 .add_argument("dst0", "Destination register 0")236 .add_argument("dst0", "Destination register 0")
221 .add_argument("dst1", "Destination register 1")237 .add_argument("dst1", "Destination register 1")
238+ .add_argument("src0", "Source register 0")
239+ .add_argument("src1", "Source register 1")
222 .f_deduce_type(DeduceVFFromDstArg);240 .f_deduce_type(DeduceVFFromDstArg);
223 241 
224REGISTER_OP("vf.Select")242REGISTER_OP("vf.Select")
225 .set_op_category("VFOp")243 .set_op_category("VFOp")
226 .set_description("Conditional select")244 .set_description("Conditional select")
245+ .add_argument("dst", "Destination register")
227 .add_argument("src_true", "True branch register")246 .add_argument("src_true", "True branch register")
228 .add_argument("src_false", "False branch register")247 .add_argument("src_false", "False branch register")
229- .add_argument("dst", "Destination register")
230 .add_argument("mask", "Mask register")248 .add_argument("mask", "Mask register")
231 .f_deduce_type(DeduceVFFromDstArg);249 .f_deduce_type(DeduceVFFromDstArg);
232 250 
@@ -242,5 +260,75 @@ REGISTER_OP("vf.MemBar")
242 .no_argument()260 .no_argument()
243 .f_deduce_type(DeduceVFUnknownType);261 .f_deduce_type(DeduceVFUnknownType);
244 262 
245-} // namespace ir263+// TopK VF ops
246-} // namespace pypto264+REGISTER_OP("vf.Histograms")
265+ .set_op_category("VFOp")
266+ .set_description("Histogram accumulation")
267+ .add_argument("dst", "Destination histogram register")
268+ .add_argument("src", "Source register")
269+ .add_argument("mask", "Mask register")
270+ .f_deduce_type(DeduceVFFromDstArg);
271+ 
272+REGISTER_OP("vf.Compare")
273+ .set_op_category("VFOp")
274+ .set_description("Compare and generate mask")
275+ .add_argument("src0", "First source register")
276+ .add_argument("src1", "Second source register")
277+ .add_argument("mask_src", "Source mask register")
278+ .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
279+ [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {
280+ return std::make_shared<ScalarType>(DataType::UINT16);
281+ });
282+ 
283+REGISTER_OP("vf.Squeeze")
284+ .set_op_category("VFOp")
285+ .set_description("Squeeze mask to indices")
286+ .add_argument("dst", "Destination register")
287+ .add_argument("src", "Source register")
288+ .add_argument("mask", "Mask register")
289+ .f_deduce_type(DeduceVFFromDstArg);
290+ 
291+REGISTER_OP("vf.Arange")
292+ .set_op_category("VFOp")
293+ .set_description("Generate incrementing index sequence")
294+ .add_argument("dst", "Destination register")
295+ .f_deduce_type(DeduceVFFromDstArg);
296+ 
297+REGISTER_OP("vf.Gather")
298+ .set_op_category("VFOp")
299+ .set_description("Gather elements by indices")
300+ .add_argument("dst", "Destination register")
301+ .add_argument("src_ub", "Source UB pointer")
302+ .add_argument("indices", "Index register")
303+ .add_argument("mask", "Mask register")
304+ .f_deduce_type(DeduceVFFromDstArg);
305+ 
306+REGISTER_OP("vf.StoreUnAlign")
307+ .set_op_category("VFOp")
308+ .set_description("Store unaligned data with post update")
309+ .add_argument("dst_ptr", "Destination UB pointer")
310+ .add_argument("src", "Source register")
311+ .add_argument("align_reg", "Alignment register")
312+ .f_deduce_type(DeduceVFUnknownType);
313+ 
314+REGISTER_OP("vf.StoreUnAlignPost")
315+ .set_op_category("VFOp")
316+ .set_description("Complete unaligned store")
317+ .add_argument("dst_ptr", "Destination UB pointer")
318+ .add_argument("align_reg", "Alignment register")
319+ .f_deduce_type(DeduceVFUnknownType);
320+ 
321+REGISTER_OP("vf.UnalignRegForStore")
322+ .set_op_category("VFOp")
323+ .set_description("Declare unaligned register for store")
324+ .no_argument()
325+ .f_deduce_type(DeduceVFUnknownType);
326+ 
327+REGISTER_OP("vf.ClearSpr")
328+ .set_op_category("VFOp")
329+ .set_description("Clear special purpose register AR")
330+ .no_argument()
331+ .f_deduce_type(DeduceVFUnknownType);
332+ 
333+} // namespace ir
334+} // namespace pypto
@@ -60,6 +60,10 @@ void ValidateKwargs(
60 CHECK(std::type_index(value.type()) == std::type_index(typeid(std::vector<int>)))60 CHECK(std::type_index(value.type()) == std::type_index(typeid(std::vector<int>)))
61 << "Kwarg '" << key << "' for operator '" << op_name61 << "Kwarg '" << key << "' for operator '" << op_name
62 << "' expects std::vector<int>, but got incompatible type";62 << "' expects std::vector<int>, but got incompatible type";
63+ } else if (it->second == std::type_index(typeid(std::vector<std::string>))) {
64+ CHECK(std::type_index(value.type()) == std::type_index(typeid(std::vector<std::string>)))
65+ << "Kwarg '" << key << "' for operator '" << op_name
66+ << "' expects std::vector<std::string>, but got incompatible type";
63 } else if (std::type_index(value.type()) != it->second) {67 } else if (std::type_index(value.type()) != it->second) {
64 CHECK(false) << "Kwarg '" << key << "' for operator '" << op_name << "' has incompatible type";68 CHECK(false) << "Kwarg '" << key << "' for operator '" << op_name << "' has incompatible type";
65 }69 }
@@ -27,8 +27,8 @@ namespace pypto {
27namespace ir {27namespace ir {
28 28 
29// Vector-based constructor: creates string-keyed map from function names29// Vector-based constructor: creates string-keyed map from function names
30-Program::Program(const std::vector<FunctionPtr>& functions, std::string name, Span span)30+Program::Program(const std::vector<FunctionPtr>& functions, std::string name, Span span, IRDebugInfoPtr debugInfo)
31- : IRNode(std::move(span)), name_(std::move(name))31+ : IRNode(std::move(span)), name_(std::move(name)), debugInfo_(std::move(debugInfo))
32{32{
33 std::set<std::string> function_names;33 std::set<std::string> function_names;
34 for (const auto& func : functions) {34 for (const auto& func : functions) {
@@ -55,7 +55,7 @@ DataType CanonicalizeForSyntaxScalarDtype(const DataType& dtype)
55/**55/**
56 * \brief Hash combine using Boost-inspired algorithm56 * \brief Hash combine using Boost-inspired algorithm
57 */57 */
58-inline uint64_t hash_combine(uint64_t seed, uint64_t value)58+inline uint64_t HashCombine(uint64_t seed, uint64_t value)
59{59{
60 return seed ^ (value + 0x9e3779b9 + (seed << 0x6) + (seed >> 0x2));60 return seed ^ (value + 0x9e3779b9 + (seed << 0x6) + (seed >> 0x2));
61}61}
@@ -104,7 +104,7 @@ public:
104 ResultType h = 0;104 ResultType h = 0;
105 for (size_t i = 0; i < fields.size(); ++i) {105 for (size_t i = 0; i < fields.size(); ++i) {
106 INTERNAL_CHECK(fields[i]) << "structural_hash encountered null IR node in vector at index " << i;106 INTERNAL_CHECK(fields[i]) << "structural_hash encountered null IR node in vector at index " << i;
107- h = hash_combine(h, HashNode(fields[i]));107+ h = HashCombine(h, HashNode(fields[i]));
108 }108 }
109 return h;109 return h;
110 }110 }
@@ -117,9 +117,9 @@ public:
117 INTERNAL_CHECK(key) << "structural_hash encountered null key in map";117 INTERNAL_CHECK(key) << "structural_hash encountered null key in map";
118 INTERNAL_CHECK(value) << "structural_hash encountered null value in map";118 INTERNAL_CHECK(value) << "structural_hash encountered null value in map";
119 // Hash key by name (keys are Op types, not IRNode)119 // Hash key by name (keys are Op types, not IRNode)
120- h = hash_combine(h, static_cast<ResultType>(std::hash<std::string>{}(key->name_)));120+ h = HashCombine(h, static_cast<ResultType>(std::hash<std::string>{}(key->name_)));
121 // Hash value (values are IRNode types)121 // Hash value (values are IRNode types)
122- h = hash_combine(h, HashNode(value));122+ h = HashCombine(h, HashNode(value));
123 }123 }
124 return h;124 return h;
125 }125 }
@@ -131,9 +131,9 @@ public:
131 for (const auto& [key, value] : field) {131 for (const auto& [key, value] : field) {
132 INTERNAL_CHECK(value) << "structural_hash encountered null value in map";132 INTERNAL_CHECK(value) << "structural_hash encountered null value in map";
133 // Hash key string133 // Hash key string
134- h = hash_combine(h, static_cast<ResultType>(std::hash<std::string>{}(key)));134+ h = HashCombine(h, static_cast<ResultType>(std::hash<std::string>{}(key)));
135 // Hash value (values are IRNode types)135 // Hash value (values are IRNode types)
136- h = hash_combine(h, HashNode(value));136+ h = HashCombine(h, HashNode(value));
137 }137 }
138 return h;138 return h;
139 }139 }
@@ -214,7 +214,16 @@ public:
214 ResultType h = 0;214 ResultType h = 0;
215 for (size_t i = 0; i < fields.size(); ++i) {215 for (size_t i = 0; i < fields.size(); ++i) {
216 INTERNAL_CHECK(fields[i]) << "structural_hash encountered null TypePtr in vector at index " << i;216 INTERNAL_CHECK(fields[i]) << "structural_hash encountered null TypePtr in vector at index " << i;
217- h = hash_combine(h, HashType(fields[i]));217+ h = HashCombine(h, HashType(fields[i]));
218+ }
219+ return h;
220+ }
221+ 
222+ ResultType VisitLeafField(const std::vector<std::string>& fields)
223+ {
224+ ResultType h = static_cast<ResultType>(fields.size());
225+ for (const auto& s : fields) {
226+ h = HashCombine(h, std::hash<std::string>{}(s));
218 }227 }
219 return h;228 return h;
220 }229 }
@@ -225,25 +234,30 @@ public:
225 ResultType h = 0;234 ResultType h = 0;
226 // Hash keys and values in order (no need to sort since order is preserved)235 // Hash keys and values in order (no need to sort since order is preserved)
227 for (const auto& [key, value] : kwargs) {236 for (const auto& [key, value] : kwargs) {
228- h = hash_combine(h, std::hash<std::string>{}(key));237+ h = HashCombine(h, std::hash<std::string>{}(key));
229 238 
230 // Hash value based on type239 // Hash value based on type
231 if (value.type() == typeid(int)) {240 if (value.type() == typeid(int)) {
232- h = hash_combine(h, std::hash<int>{}(AnyCast<int>(value, "hashing kwarg: " + key)));241+ h = HashCombine(h, std::hash<int>{}(AnyCast<int>(value, "hashing kwarg: " + key)));
233 } else if (value.type() == typeid(bool)) {242 } else if (value.type() == typeid(bool)) {
234- h = hash_combine(h, std::hash<bool>{}(AnyCast<bool>(value, "hashing kwarg: " + key)));243+ h = HashCombine(h, std::hash<bool>{}(AnyCast<bool>(value, "hashing kwarg: " + key)));
235 } else if (value.type() == typeid(std::string)) {244 } else if (value.type() == typeid(std::string)) {
236- h = hash_combine(h, std::hash<std::string>{}(AnyCast<std::string>(value, "hashing kwarg: " + key)));245+ h = HashCombine(h, std::hash<std::string>{}(AnyCast<std::string>(value, "hashing kwarg: " + key)));
237 } else if (value.type() == typeid(double)) {246 } else if (value.type() == typeid(double)) {
238- h = hash_combine(h, std::hash<double>{}(AnyCast<double>(value, "hashing kwarg: " + key)));247+ h = HashCombine(h, std::hash<double>{}(AnyCast<double>(value, "hashing kwarg: " + key)));
239 } else if (value.type() == typeid(float)) {248 } else if (value.type() == typeid(float)) {
240- h = hash_combine(h, std::hash<float>{}(AnyCast<float>(value, "hashing kwarg: " + key)));249+ h = HashCombine(h, std::hash<float>{}(AnyCast<float>(value, "hashing kwarg: " + key)));
241 } else if (value.type() == typeid(DataType)) {250 } else if (value.type() == typeid(DataType)) {
242- h = hash_combine(h, std::hash<uint8_t>{}(AnyCast<DataType>(value, "hashing kwarg: " + key).Code()));251+ h = HashCombine(h, std::hash<uint8_t>{}(AnyCast<DataType>(value, "hashing kwarg: " + key).Code()));
243 } else if (value.type() == typeid(std::vector<int>)) {252 } else if (value.type() == typeid(std::vector<int>)) {
244 const auto& vec = AnyCast<std::vector<int>>(value, "hashing kwarg: " + key);253 const auto& vec = AnyCast<std::vector<int>>(value, "hashing kwarg: " + key);
245 for (int v : vec) {254 for (int v : vec) {
246- h = hash_combine(h, std::hash<int>{}(v));255+ h = HashCombine(h, std::hash<int>{}(v));
256+ }
257+ } else if (value.type() == typeid(std::vector<std::string>)) {
258+ const auto& vec = AnyCast<std::vector<std::string>>(value, "hashing kwarg: " + key);
259+ for (const auto& s : vec) {
260+ h = HashCombine(h, std::hash<std::string>{}(s));
247 }261 }
248 } else {262 } else {
249 CHECK(false) << "Invalid kwarg type for key: " << key263 CHECK(false) << "Invalid kwarg type for key: " << key
@@ -266,8 +280,8 @@ public:
266 ResultType h = 0;280 ResultType h = 0;
267 for (const auto& ia : fields) {281 for (const auto& ia : fields) {
268 INTERNAL_CHECK(ia) << "structural_hash encountered null IterArgPtr in vector";282 INTERNAL_CHECK(ia) << "structural_hash encountered null IterArgPtr in vector";
269- h = hash_combine(h, HashNode(std::static_pointer_cast<const IRNode>(ia->iterVar_)));283+ h = HashCombine(h, HashNode(std::static_pointer_cast<const IRNode>(ia->iterVar_)));
270- h = hash_combine(h, HashNode(std::static_pointer_cast<const IRNode>(ia->initValue_)));284+ h = HashCombine(h, HashNode(std::static_pointer_cast<const IRNode>(ia->initValue_)));
271 }285 }
272 return h;286 return h;
273 }287 }
@@ -275,7 +289,7 @@ public:
275 template <typename Desc>289 template <typename Desc>
276 void CombineResult(ResultType& accumulator, ResultType field_hash, [[maybe_unused]] const Desc& descriptor)290 void CombineResult(ResultType& accumulator, ResultType field_hash, [[maybe_unused]] const Desc& descriptor)
277 {291 {
278- accumulator = hash_combine(accumulator, field_hash);292+ accumulator = HashCombine(accumulator, field_hash);
279 }293 }
280 294 
281private:295private:
@@ -332,7 +346,7 @@ StructuralHasher::ResultType StructuralHasher::HashNodeImpl(const NodePtr& node)
332 transparent_depth_ = saved_depth;346 transparent_depth_ = saved_depth;
333 node_type_stack_.pop_back();347 node_type_stack_.pop_back();
334 348 
335- return hash_combine(h, fields_hash);349+ return HashCombine(h, fields_hash);
336}350}
337 351 
338StructuralHasher::ResultType StructuralHasher::HashType(const TypePtr& type)352StructuralHasher::ResultType StructuralHasher::HashType(const TypePtr& type)
@@ -344,58 +358,58 @@ StructuralHasher::ResultType StructuralHasher::HashType(const TypePtr& type)
344 if (IsLoopVarFieldContext() || IsConstIntTypeContext()) {358 if (IsLoopVarFieldContext() || IsConstIntTypeContext()) {
345 dtype = CanonicalizeForSyntaxScalarDtype(dtype);359 dtype = CanonicalizeForSyntaxScalarDtype(dtype);
346 }360 }
347- h = hash_combine(h, static_cast<ResultType>(std::hash<uint8_t>{}(dtype.Code())));361+ h = HashCombine(h, static_cast<ResultType>(std::hash<uint8_t>{}(dtype.Code())));
348 } else if (auto tensor_type = As<TensorType>(type)) {362 } else if (auto tensor_type = As<TensorType>(type)) {
349- h = hash_combine(h, static_cast<ResultType>(std::hash<uint8_t>{}(tensor_type->dtype_.Code())));363+ h = HashCombine(h, static_cast<ResultType>(std::hash<uint8_t>{}(tensor_type->dtype_.Code())));
350- h = hash_combine(h, static_cast<ResultType>(tensor_type->shape_.size()));364+ h = HashCombine(h, static_cast<ResultType>(tensor_type->shape_.size()));
351 for (const auto& dim : tensor_type->shape_) {365 for (const auto& dim : tensor_type->shape_) {
352 INTERNAL_CHECK(dim) << "structural_hash encountered null shape dimension in TypePtr";366 INTERNAL_CHECK(dim) << "structural_hash encountered null shape dimension in TypePtr";
353- h = hash_combine(h, HashNode(dim));367+ h = HashCombine(h, HashNode(dim));
354 }368 }
355 } else if (auto tile_type = As<TileType>(type)) {369 } else if (auto tile_type = As<TileType>(type)) {
356 // Hash dtype370 // Hash dtype
357- h = hash_combine(h, static_cast<ResultType>(std::hash<uint8_t>{}(tile_type->dtype_.Code())));371+ h = HashCombine(h, static_cast<ResultType>(std::hash<uint8_t>{}(tile_type->dtype_.Code())));
358 // Hash shape size and dimensions372 // Hash shape size and dimensions
359- h = hash_combine(h, static_cast<ResultType>(tile_type->shape_.size()));373+ h = HashCombine(h, static_cast<ResultType>(tile_type->shape_.size()));
360 for (const auto& dim : tile_type->shape_) {374 for (const auto& dim : tile_type->shape_) {
361 INTERNAL_CHECK(dim) << "structural_hash encountered null shape dimension in TileType";375 INTERNAL_CHECK(dim) << "structural_hash encountered null shape dimension in TileType";
362- h = hash_combine(h, HashNode(dim));376+ h = HashCombine(h, HashNode(dim));
363 }377 }
364 // Hash tile_view if present378 // Hash tile_view if present
365 if (tile_type->tileView_.has_value()) {379 if (tile_type->tileView_.has_value()) {
366 const auto& tv = tile_type->tileView_.value();380 const auto& tv = tile_type->tileView_.value();
367- h = hash_combine(h, static_cast<ResultType>(1)); // indicate presence381+ h = HashCombine(h, static_cast<ResultType>(1)); // indicate presence
368- h = hash_combine(h, static_cast<ResultType>(tv.validShape.size()));382+ h = HashCombine(h, static_cast<ResultType>(tv.validShape.size()));
369 for (const auto& dim : tv.validShape) {383 for (const auto& dim : tv.validShape) {
370 INTERNAL_CHECK(dim) << "structural_hash encountered null valid_shape dimension in TileView";384 INTERNAL_CHECK(dim) << "structural_hash encountered null valid_shape dimension in TileView";
371- h = hash_combine(h, HashNode(dim));385+ h = HashCombine(h, HashNode(dim));
372 }386 }
373- h = hash_combine(h, static_cast<ResultType>(tv.stride.size()));387+ h = HashCombine(h, static_cast<ResultType>(tv.stride.size()));
374 for (const auto& dim : tv.stride) {388 for (const auto& dim : tv.stride) {
375 INTERNAL_CHECK(dim) << "structural_hash encountered null stride dimension in TileView";389 INTERNAL_CHECK(dim) << "structural_hash encountered null stride dimension in TileView";
376- h = hash_combine(h, HashNode(dim));390+ h = HashCombine(h, HashNode(dim));
377 }391 }
378 INTERNAL_CHECK(tv.startOffset) << "structural_hash encountered null start_offset in TileView";392 INTERNAL_CHECK(tv.startOffset) << "structural_hash encountered null start_offset in TileView";
379- h = hash_combine(h, HashNode(tv.startOffset));393+ h = HashCombine(h, HashNode(tv.startOffset));
380 } else {394 } else {
381- h = hash_combine(h, static_cast<ResultType>(0)); // indicate absence395+ h = HashCombine(h, static_cast<ResultType>(0)); // indicate absence
382 }396 }
383 // Hash hardware_info if present397 // Hash hardware_info if present
384 if (tile_type->hardwareInfo_.has_value()) {398 if (tile_type->hardwareInfo_.has_value()) {
385 const auto& hw = tile_type->hardwareInfo_.value();399 const auto& hw = tile_type->hardwareInfo_.value();
386- h = hash_combine(h, static_cast<ResultType>(1));400+ h = HashCombine(h, static_cast<ResultType>(1));
387- h = hash_combine(h, static_cast<ResultType>(hw.blayout));401+ h = HashCombine(h, static_cast<ResultType>(hw.blayout));
388- h = hash_combine(h, static_cast<ResultType>(hw.slayout));402+ h = HashCombine(h, static_cast<ResultType>(hw.slayout));
389- h = hash_combine(h, static_cast<ResultType>(hw.fractal));403+ h = HashCombine(h, static_cast<ResultType>(hw.fractal));
390- h = hash_combine(h, static_cast<ResultType>(hw.pad));404+ h = HashCombine(h, static_cast<ResultType>(hw.pad));
391 } else {405 } else {
392- h = hash_combine(h, static_cast<ResultType>(0));406+ h = HashCombine(h, static_cast<ResultType>(0));
393 }407 }
394 } else if (auto tuple_type = As<TupleType>(type)) {408 } else if (auto tuple_type = As<TupleType>(type)) {
395- h = hash_combine(h, static_cast<ResultType>(tuple_type->types_.size()));409+ h = HashCombine(h, static_cast<ResultType>(tuple_type->types_.size()));
396 for (const auto& t : tuple_type->types_) {410 for (const auto& t : tuple_type->types_) {
397 INTERNAL_CHECK(t) << "structural_hash encountered null type in TupleType";411 INTERNAL_CHECK(t) << "structural_hash encountered null type in TupleType";
398- h = hash_combine(h, HashType(t));412+ h = HashCombine(h, HashType(t));
399 }413 }
400 } else if (IsA<MemRefType>(type) || IsA<UnknownType>(type)) {414 } else if (IsA<MemRefType>(type) || IsA<UnknownType>(type)) {
401 // MemRefType and UnknownType have no fields, only hash type name (already done above)415 // MemRefType and UnknownType have no fields, only hash type name (already done above)
@@ -459,9 +473,9 @@ StructuralHasher::ResultType StructuralHasher::HashNode(const IRNodePtr& node)
459 // here we add the variable identity hash.473 // here we add the variable identity hash.
460 auto hash_var_identity = [&](const Var* var) {474 auto hash_var_identity = [&](const Var* var) {
461 if (enable_auto_mapping_) {475 if (enable_auto_mapping_) {
462- hash_value = hash_combine(hash_value, free_var_counter_++);476+ hash_value = HashCombine(hash_value, free_var_counter_++);
463 } else {477 } else {
464- hash_value = hash_combine(hash_value, std::hash<std::string>{}(var->name_));478+ hash_value = HashCombine(hash_value, std::hash<std::string>{}(var->name_));
465 }479 }
466 };480 };
467 481 
@@ -10,6 +10,7 @@
10 10 
11#include <cmath>11#include <cmath>
12#include <cstddef>12#include <cstddef>
13+#include <any>
13#include <iomanip>14#include <iomanip>
14#include <ios>15#include <ios>
15#include <optional>16#include <optional>
@@ -20,6 +21,7 @@
20#include <utility>21#include <utility>
21#include <vector>22#include <vector>
22 23 
24+#include "core/any_cast.h"
23#include "core/dtype.h"25#include "core/dtype.h"
24#include "core/logging.h"26#include "core/logging.h"
25#include "ir/core.h"27#include "ir/core.h"
@@ -27,6 +29,7 @@
27#include "ir/expr.h"29#include "ir/expr.h"
28#include "ir/function.h"30#include "ir/function.h"
29#include "ir/memref.h"31#include "ir/memref.h"
32+#include "ir/pipe.h"
30#include "ir/stmt.h"33#include "ir/stmt.h"
31#include "ir/kind_traits.h"34#include "ir/kind_traits.h"
32#include "ir/scalar_expr.h"35#include "ir/scalar_expr.h"
@@ -208,6 +211,68 @@ std::string FormatFloatLiteral(double value)
208 }211 }
209}212}
210 213 
214+const char* TileLayoutToPythonName(TileLayout layout)
215+{
216+ switch (layout) {
217+ case TileLayout::none_box:
218+ return "none_box";
219+ case TileLayout::row_major:
220+ return "row_major";
221+ case TileLayout::col_major:
222+ return "col_major";
223+ default:
224+ INTERNAL_CHECK(false) << "Unknown TileLayout in PrintTileView";
225+ return "";
226+ }
227+}
228+ 
229+const char* TilePadToPythonName(TilePad pad)
230+{
231+ switch (pad) {
232+ case TilePad::null:
233+ return "null";
234+ case TilePad::zero:
235+ return "zero";
236+ case TilePad::max:
237+ return "max";
238+ case TilePad::min:
239+ return "min";
240+ default:
241+ INTERNAL_CHECK(false) << "Unknown TilePad in PrintTileView";
242+ return "";
243+ }
244+}
245+ 
246+const char* CompactModeToPythonName(CompactMode compact)
247+{
248+ switch (compact) {
249+ case CompactMode::null:
250+ return "null";
251+ case CompactMode::normal:
252+ return "normal";
253+ case CompactMode::row_plus_one:
254+ return "row_plus_one";
255+ default:
256+ INTERNAL_CHECK(false) << "Unknown CompactMode in PrintTileView";
257+ return "";
258+ }
259+}
260+ 
261+const char* TensorLayoutToPythonName(TensorLayout layout)
262+{
263+ switch (layout) {
264+ case TensorLayout::ND:
265+ return "ND";
266+ case TensorLayout::DN:
267+ return "DN";
268+ case TensorLayout::NZ:
269+ return "NZ";
270+ default:
271+ INTERNAL_CHECK(false) << "Unknown TensorLayout in PrintTensorView";
272+ return "";
273+ }
274+}
275+ 
211void PrintIterArgNames(std::ostringstream& stream, const std::vector<IterArgPtr>& iter_args)276void PrintIterArgNames(std::ostringstream& stream, const std::vector<IterArgPtr>& iter_args)
212{277{
213 stream << "(";278 stream << "(";
@@ -309,6 +374,7 @@ protected:
309 void VisitExpr_(const ScalarExprPtr& op) override;374 void VisitExpr_(const ScalarExprPtr& op) override;
310 void VisitStmt_(const TensorOpStmtPtr& op) override;375 void VisitStmt_(const TensorOpStmtPtr& op) override;
311 void VisitStmt_(const ScalarOpStmtPtr& op) override;376 void VisitStmt_(const ScalarOpStmtPtr& op) override;
377+ void VisitStmt_(const SectionStmtPtr& op) override;
312 378 
313private:379private:
314 std::ostringstream stream_;380 std::ostringstream stream_;
@@ -330,15 +396,21 @@ private:
330 void PrintBinaryOp(const BinaryExprPtr& op, const char* op_symbol);396 void PrintBinaryOp(const BinaryExprPtr& op, const char* op_symbol);
331 void PrintFunctionBinaryOp(const BinaryExprPtr& op, const char* func_name);397 void PrintFunctionBinaryOp(const BinaryExprPtr& op, const char* func_name);
332 void PrintChild(const ExprPtr& parent, const ExprPtr& child, bool is_left);398 void PrintChild(const ExprPtr& parent, const ExprPtr& child, bool is_left);
399+ void PrintCallKwargs(const CallPtr& op, bool need_comma);
400+ void PrintKwargValue(const std::string& key, const std::any& value);
333 401 
334 // Shape printing helper402 // Shape printing helper
335 void PrintShapeDims(std::ostringstream& oss, const std::vector<ExprPtr>& shape);403 void PrintShapeDims(std::ostringstream& oss, const std::vector<ExprPtr>& shape);
404+ void PrintExprList(std::ostringstream& oss, const std::vector<ExprPtr>& exprs);
336 405 
337 // Print an expression for use in type annotations (shapes, views).406 // Print an expression for use in type annotations (shapes, views).
338 std::string PrintExprForType(const ExprPtr& expr);407 std::string PrintExprForType(const ExprPtr& expr);
339 408 
340 // MemRef and TileView printing helpers409 // MemRef and TileView printing helpers
341 std::string PrintMemRef(const MemRef& memref);410 std::string PrintMemRef(const MemRef& memref);
411+ std::string PrintTileView(const TileView& tile_view);
412+ std::string PrintHardwareInfo(const HardwareInfo& hw_info);
413+ std::string PrintTensorView(const TensorView& tensor_view);
342};414};
343 415 
344// DataTypeToPythonString removed — now uses DTypeToString from dtype.h416// DataTypeToPythonString removed — now uses DTypeToString from dtype.h
@@ -367,6 +439,10 @@ std::string IRPrinter::Print(const TypePtr& type)
367 PrintShapeDims(oss, tensor_type->shape_);439 PrintShapeDims(oss, tensor_type->shape_);
368 oss << "], " << prefix_ << "." << DTypeToString(tensor_type->dtype_);440 oss << "], " << prefix_ << "." << DTypeToString(tensor_type->dtype_);
369 441 
442+ if (tensor_type->tensor_view_.has_value()) {
443+ oss << ", tensor_view=" << PrintTensorView(tensor_type->tensor_view_.value());
444+ }
445+ 
370 // Add optional memref as positional arg446 // Add optional memref as positional arg
371 if (tensor_type->memref_.has_value()) {447 if (tensor_type->memref_.has_value()) {
372 oss << ", " << PrintMemRef(*tensor_type->memref_.value());448 oss << ", " << PrintMemRef(*tensor_type->memref_.value());
@@ -383,6 +459,14 @@ std::string IRPrinter::Print(const TypePtr& type)
383 PrintShapeDims(oss, tile_type->shape_);459 PrintShapeDims(oss, tile_type->shape_);
384 oss << "], " << prefix_ << "." << DTypeToString(tile_type->dtype_);460 oss << "], " << prefix_ << "." << DTypeToString(tile_type->dtype_);
385 461 
462+ if (tile_type->tileView_.has_value()) {
463+ oss << ", tile_view=" << PrintTileView(tile_type->tileView_.value());
464+ }
465+ 
466+ if (tile_type->hardwareInfo_.has_value()) {
467+ oss << ", hardware_info=" << PrintHardwareInfo(tile_type->hardwareInfo_.value());
468+ }
469+ 
386 // Add optional memref as positional arg470 // Add optional memref as positional arg
387 if (tile_type->memref_.has_value()) {471 if (tile_type->memref_.has_value()) {
388 oss << ", " << PrintMemRef(*tile_type->memref_.value());472 oss << ", " << PrintMemRef(*tile_type->memref_.value());
@@ -454,6 +538,7 @@ void IRPrinter::VisitExpr_(const CallPtr& op)
454 stream_ << ", ";538 stream_ << ", ";
455 VisitExpr(op->args_[i]);539 VisitExpr(op->args_[i]);
456 }540 }
541+ PrintCallKwargs(op, !op->args_.empty());
457 stream_ << ")";542 stream_ << ")";
458}543}
459 544 
@@ -505,6 +590,75 @@ void IRPrinter::PrintFunctionBinaryOp(const BinaryExprPtr& op, const char* func_
505 stream_ << ")";590 stream_ << ")";
506}591}
507 592 
593+void IRPrinter::PrintKwargValue(const std::string& key, const std::any& value)
594+{
595+ if (value.type() == typeid(int)) {
596+ int int_val = AnyCast<int>(value, "printing kwarg: " + key);
597+ if (key == "set_pipe" || key == "wait_pipe") {
598+ stream_ << prefix_ << ".PipeType." << PipeTypeToString(static_cast<PipeType>(int_val));
599+ } else {
600+ stream_ << int_val;
601+ }
602+ } else if (value.type() == typeid(bool)) {
603+ stream_ << (AnyCast<bool>(value, "printing kwarg: " + key) ? "True" : "False");
604+ } else if (value.type() == typeid(std::string)) {
605+ stream_ << std::quoted(AnyCast<std::string>(value, "printing kwarg: " + key));
606+ } else if (value.type() == typeid(double)) {
607+ stream_ << FormatFloatLiteral(AnyCast<double>(value, "printing kwarg: " + key));
608+ } else if (value.type() == typeid(float)) {
609+ stream_ << FormatFloatLiteral(static_cast<double>(AnyCast<float>(value, "printing kwarg: " + key)));
610+ } else if (value.type() == typeid(DataType)) {
611+ stream_ << prefix_ << "." << DTypeToString(AnyCast<DataType>(value, "printing kwarg: " + key));
612+ } else if (value.type() == typeid(MemorySpace)) {
613+ stream_ << prefix_ << ".MemorySpace."
614+ << MemorySpaceToString(AnyCast<MemorySpace>(value, "printing kwarg: " + key));
615+ } else if (value.type() == typeid(std::vector<int>)) {
616+ const auto& values = AnyCast<std::vector<int>>(value, "printing kwarg: " + key);
617+ stream_ << "[";
618+ for (size_t i = 0; i < values.size(); ++i) {
619+ if (i > 0)
620+ stream_ << ", ";
621+ stream_ << values[i];
622+ }
623+ stream_ << "]";
624+ } else if (value.type() == typeid(std::vector<std::string>)) {
625+ const auto& values = AnyCast<std::vector<std::string>>(value, "printing kwarg: " + key);
626+ stream_ << "[";
627+ for (size_t i = 0; i < values.size(); ++i) {
628+ if (i > 0)
629+ stream_ << ", ";
630+ stream_ << std::quoted(values[i]);
631+ }
632+ stream_ << "]";
633+ } else if (value.type() == typeid(SymbolicScalar)) {
634+ stream_ << AnyCast<SymbolicScalar>(value, "printing kwarg: " + key).Dump();
635+ } else if (value.type() == typeid(std::vector<SymbolicScalar>)) {
636+ const auto& values = AnyCast<std::vector<SymbolicScalar>>(value, "printing kwarg: " + key);
637+ stream_ << "[";
638+ for (size_t i = 0; i < values.size(); ++i) {
639+ if (i > 0)
640+ stream_ << ", ";
641+ stream_ << values[i].Dump();
642+ }
643+ stream_ << "]";
644+ } else {
645+ INTERNAL_CHECK(false) << "Unsupported kwarg value type for key '" << key << "': "
646+ << DemangleTypeName(value.type().name());
647+ }
648+}
649+ 
650+void IRPrinter::PrintCallKwargs(const CallPtr& op, bool need_comma)
651+{
652+ for (const auto& [key, value] : op->kwargs_) {
653+ if (need_comma) {
654+ stream_ << ", ";
655+ }
656+ need_comma = true;
657+ stream_ << key << "=";
658+ PrintKwargValue(key, value);
659+ }
660+}
661+ 
508// Arithmetic binary operators662// Arithmetic binary operators
509void IRPrinter::VisitExpr_(const AddPtr& op) { PrintBinaryOp(op, "+"); }663void IRPrinter::VisitExpr_(const AddPtr& op) { PrintBinaryOp(op, "+"); }
510void IRPrinter::VisitExpr_(const SubPtr& op) { PrintBinaryOp(op, "-"); }664void IRPrinter::VisitExpr_(const SubPtr& op) { PrintBinaryOp(op, "-"); }
@@ -828,6 +982,24 @@ void IRPrinter::VisitStmt_(const ScalarOpStmtPtr& op)
828 stream_ << ")";982 stream_ << ")";
829}983}
830 984 
985+void IRPrinter::VisitStmt_(const SectionStmtPtr& op)
986+{
987+ static const std::unordered_map<SectionKind, std::string> section_kind_to_name = {
988+ {SectionKind::Vector, "section_vector"},
989+ {SectionKind::Cube, "section_cube"},
990+ {SectionKind::VF, "section_vf"},
991+ };
992+ 
993+ auto it = section_kind_to_name.find(op->sectionKind_);
994+ INTERNAL_CHECK(it != section_kind_to_name.end())
995+ << "Internal error: Unknown SectionKind in printer: " << SectionKindToString(op->sectionKind_);
996+ 
997+ stream_ << "with " << prefix_ << "." << it->second << "():\n";
998+ indent_++;
999+ PrintStmtBlock(op->body_);
1000+ indent_--;
1001+}
1002+ 
831void IRPrinter::VisitStmt_(const StmtPtr& op) { stream_ << op->TypeName(); }1003void IRPrinter::VisitStmt_(const StmtPtr& op) { stream_ << op->TypeName(); }
832 1004 
833void IRPrinter::PrintYieldAssignmentVars(const std::vector<VarPtr>& return_vars)1005void IRPrinter::PrintYieldAssignmentVars(const std::vector<VarPtr>& return_vars)
@@ -952,6 +1124,9 @@ void IRPrinter::VisitFunction(const FunctionPtr& func)
952{1124{
953 // Print decorator1125 // Print decorator
954 stream_ << GetIndent() << "@" << prefix_ << ".function";1126 stream_ << GetIndent() << "@" << prefix_ << ".function";
1127+ if (func->funcType_ != FunctionType::OPAQUE) {
1128+ stream_ << "(type=" << prefix_ << ".FunctionType." << FunctionTypeToString(func->funcType_) << ")";
1129+ }
955 stream_ << "\n";1130 stream_ << "\n";
956 1131 
957 // Print function signature1132 // Print function signature
@@ -1014,6 +1189,16 @@ void IRPrinter::PrintShapeDims(std::ostringstream& oss, const std::vector<ExprPt
1014 }1189 }
1015}1190}
1016 1191 
1192+void IRPrinter::PrintExprList(std::ostringstream& oss, const std::vector<ExprPtr>& exprs)
1193+{
1194+ for (size_t i = 0; i < exprs.size(); ++i) {
1195+ if (i > 0)
1196+ oss << ", ";
1197+ IRPrinter temp_printer(prefix_);
1198+ oss << temp_printer.Print(exprs[i]);
1199+ }
1200+}
1201+ 
1017std::string IRPrinter::PrintMemRef(const MemRef& memref)1202std::string IRPrinter::PrintMemRef(const MemRef& memref)
1018{1203{
1019 std::ostringstream oss;1204 std::ostringstream oss;
@@ -1027,6 +1212,49 @@ std::string IRPrinter::PrintMemRef(const MemRef& memref)
1027 return oss.str();1212 return oss.str();
1028}1213}
1029 1214 
1215+std::string IRPrinter::PrintTileView(const TileView& tile_view)
1216+{
1217+ std::ostringstream oss;
1218+ oss << prefix_ << ".TileView(valid_shape=[";
1219+ PrintExprList(oss, tile_view.validShape);
1220+ oss << "], stride=[";
1221+ PrintExprList(oss, tile_view.stride);
1222+ oss << "], start_offset=";
1223+ IRPrinter temp_printer(prefix_);
1224+ oss << temp_printer.Print(tile_view.startOffset);
1225+ oss << ")";
1226+ return oss.str();
1227+}
1228+ 
1229+std::string IRPrinter::PrintHardwareInfo(const HardwareInfo& hw_info)
Jie Yin
Jie YinJie YinJun 11

这个为什么要 print 成 python name?

likedislike
wuzhongxin
wuzhongxin
Jun 11 Comments:
likedislike
1230+{
1231+ std::ostringstream oss;
1232+ oss << prefix_ << ".HardwareInfo(";
1233+ oss << "blayout=" << prefix_ << ".TileLayout." << TileLayoutToPythonName(hw_info.blayout);
1234+ oss << ", slayout=" << prefix_ << ".TileLayout." << TileLayoutToPythonName(hw_info.slayout);
1235+ oss << ", fractal=" << hw_info.fractal;
1236+ oss << ", pad=" << prefix_ << ".TilePad." << TilePadToPythonName(hw_info.pad);
1237+ oss << ", compact=" << prefix_ << ".CompactMode." << CompactModeToPythonName(hw_info.compact);
1238+ oss << ")";
1239+ return oss.str();
1240+}
1241+ 
1242+std::string IRPrinter::PrintTensorView(const TensorView& tensor_view)
1243+{
1244+ std::ostringstream oss;
1245+ oss << prefix_ << ".TensorView(";
1246+ if (!tensor_view.validShape.empty()) {
1247+ oss << "valid_shape=[";
1248+ PrintExprList(oss, tensor_view.validShape);
1249+ oss << "], ";
1250+ }
1251+ oss << "stride=[";
1252+ PrintExprList(oss, tensor_view.stride);
1253+ oss << "], layout=" << prefix_ << ".TensorLayout." << TensorLayoutToPythonName(tensor_view.layout);
1254+ oss << ")";
1255+ return oss.str();
1256+}
1257+ 
1030std::string PythonPrint(const IRNodePtr& node, const std::string& prefix, bool concise)1258std::string PythonPrint(const IRNodePtr& node, const std::string& prefix, bool concise)
1031{1259{
1032 IRPrinter printer(prefix, concise);1260 IRPrinter printer(prefix, concise);
@@ -13,12 +13,15 @@
13#include <cstdint>13#include <cstdint>
14#include <memory>14#include <memory>
15#include <optional>15#include <optional>
16+#include <set>
16#include <utility>17#include <utility>
17#include <vector>18#include <vector>
18 19 
19#include "core/dtype.h"20#include "core/dtype.h"
21+#include "ir/identifier.h"
20#include "ir/scalar_expr.h"22#include "ir/scalar_expr.h"
21#include "ir/span.h"23#include "ir/span.h"
24+#include "tilefwk/error.h"
22 25 
23namespace pypto {26namespace pypto {
24namespace ir {27namespace ir {
@@ -30,5 +33,8 @@ ShapedType::ShapedType(DataType dtype, const std::vector<int64_t>& shape, std::o
30 shape_.push_back(std::make_shared<ConstInt>(dim, DataType::INDEX, Span::Unknown()));33 shape_.push_back(std::make_shared<ConstInt>(dim, DataType::INDEX, Span::Unknown()));
31 }34 }
32}35}
36+ 
37+ 
38+TupleType::TupleType(std::vector<TypePtr> types) : types_(std::move(types)) {}
33} // namespace ir39} // namespace ir
34} // namespace pypto40} // namespace pypto
@@ -266,45 +266,80 @@ TEST_F(BlockOpsMemoryTest, SetVal_NonScalarValue_Throws)
266}266}
267 267 
268// ============================================================================268// ============================================================================
269-// struct_ops.cpp: struct.declare, struct.get, struct.set, struct.ref269+// struct_ops.cpp: struct.create, struct.set
270// ============================================================================270// ============================================================================
271 271 
272class BlockOpsStructTest : public testing::Test {};272class BlockOpsStructTest : public testing::Test {};
273 273 
274-TEST_F(BlockOpsStructTest, StructDeclare_NoArgs_ReturnsIndexScalar)274+TEST_F(BlockOpsStructTest, StructCreate_ReturnsTupleType)
275{275{
276 auto& reg = OpRegistry::GetInstance();276 auto& reg = OpRegistry::GetInstance();
277- auto call = reg.Create("struct.declare", {}, Sp());277+ std::vector<std::pair<std::string, std::any>> kwargs = {
278- auto rt = As<ScalarType>(call->GetType());278+ {"name", std::string("BufferState")},
279+ {"fields", std::vector<std::string>{"cursor", "limit"}},
280+ };
281+ auto call = reg.Create(
282+ "struct.create",
283+ {MakeScalarVar("cursor", DataType::INT64), MakeScalarVar("limit", DataType::INT32)}, kwargs, Sp());
284+ auto rt = As<TupleType>(call->GetType());
279 ASSERT_NE(rt, nullptr);285 ASSERT_NE(rt, nullptr);
280- EXPECT_EQ(rt->dtype_, DataType::INDEX);286+ ASSERT_EQ(rt->types_.size(), 2u);
287+ auto cursor_type = As<ScalarType>(rt->types_[0]);
288+ ASSERT_NE(cursor_type, nullptr);
289+ EXPECT_EQ(cursor_type->dtype_, DataType::INT64);
290+ auto limit_type = As<ScalarType>(rt->types_[1]);
291+ ASSERT_NE(limit_type, nullptr);
292+ EXPECT_EQ(limit_type->dtype_, DataType::INT32);
281}293}
282 294 
283-TEST_F(BlockOpsStructTest, StructGet_ReturnsIndexScalar)295+TEST_F(BlockOpsStructTest, StructCreate_FieldCountMismatch_Throws)
284{296{
285 auto& reg = OpRegistry::GetInstance();297 auto& reg = OpRegistry::GetInstance();
286- auto call = reg.Create("struct.get", {MakeScalarVar("idx", DataType::INT64)}, Sp());298+ std::vector<std::pair<std::string, std::any>> kwargs = {
287- auto rt = As<ScalarType>(call->GetType());299+ {"name", std::string("BufferState")},
288- ASSERT_NE(rt, nullptr);300+ {"fields", std::vector<std::string>{"cursor", "limit"}},
289- EXPECT_EQ(rt->dtype_, DataType::INDEX);301+ };
302+ EXPECT_THROW(
303+ (void)reg.Create("struct.create", {MakeScalarVar("cursor", DataType::INT64)}, kwargs, Sp()),
304+ npu::tile_fwk::Error);
290}305}
291 306 
292-TEST_F(BlockOpsStructTest, StructSet_ReturnsIndexScalar)307+TEST_F(BlockOpsStructTest, StructSet_ReturnsTupleType)
293{308{
294 auto& reg = OpRegistry::GetInstance();309 auto& reg = OpRegistry::GetInstance();
295- auto call = reg.Create("struct.set", {MakeScalarVar("idx", DataType::INT64), MakeScalarVar("val", DataType::INT64)}, Sp());310+ auto struct_type = std::make_shared<TupleType>(std::vector<TypePtr>{
296- auto rt = As<ScalarType>(call->GetType());311+ std::make_shared<ScalarType>(DataType::INT64),
312+ std::make_shared<ScalarType>(DataType::INT32),
313+ });
314+ auto base = std::make_shared<Var>("state", struct_type, Sp());
315+ std::vector<std::pair<std::string, std::any>> kwargs = {{"field", std::string("cursor")}};
316+ auto call = reg.Create("struct.set", {base, MakeScalarVar("cursor", DataType::INT64)}, kwargs, Sp());
317+ auto rt = As<TupleType>(call->GetType());
297 ASSERT_NE(rt, nullptr);318 ASSERT_NE(rt, nullptr);
298- EXPECT_EQ(rt->dtype_, DataType::INDEX);319+ EXPECT_EQ(rt->types_.size(), 2u);
299}320}
300 321 
301-TEST_F(BlockOpsStructTest, StructRef_ReturnsIndexScalar)322+TEST_F(BlockOpsStructTest, StructSet_MissingFieldKwarg_Throws)
302{323{
303 auto& reg = OpRegistry::GetInstance();324 auto& reg = OpRegistry::GetInstance();
304- auto call = reg.Create("struct.ref", {MakeScalarVar("idx", DataType::INT64)}, Sp());325+ auto struct_type = std::make_shared<TupleType>(std::vector<TypePtr>{
305- auto rt = As<ScalarType>(call->GetType());326+ std::make_shared<ScalarType>(DataType::INT64),
306- ASSERT_NE(rt, nullptr);327+ });
307- EXPECT_EQ(rt->dtype_, DataType::INDEX);328+ auto base = std::make_shared<Var>("state", struct_type, Sp());
329+ EXPECT_THROW(
330+ (void)reg.Create("struct.set", {base, MakeScalarVar("cursor", DataType::INT64)}, Sp()),
331+ npu::tile_fwk::Error);
332+}
333+ 
334+TEST_F(BlockOpsStructTest, StructSet_NonTupleBase_Throws)
335+{
336+ auto& reg = OpRegistry::GetInstance();
337+ std::vector<std::pair<std::string, std::any>> kwargs = {{"field", std::string("cursor")}};
338+ EXPECT_THROW(
339+ (void)reg.Create(
340+ "struct.set", {MakeScalarVar("state", DataType::INT64), MakeScalarVar("cursor", DataType::INT64)}, kwargs,
341+ Sp()),
342+ npu::tile_fwk::Error);
308}343}
309 344 
310// ============================================================================345// ============================================================================
@@ -1092,7 +1127,10 @@ TEST_F(BlockOpsOutMemoryTest, BlockFull_ScalarOut_ReturnsOutType)
1092TEST_F(BlockOpsOutMemoryTest, BlockSsbufStore_ReturnsIndexScalar)1127TEST_F(BlockOpsOutMemoryTest, BlockSsbufStore_ReturnsIndexScalar)
1093{1128{
1094 auto& reg = OpRegistry::GetInstance();1129 auto& reg = OpRegistry::GetInstance();
1095- auto call = reg.Create("block.ssbuf_store", {MakeScalarVar("off", DataType::INT32)}, Sp());1130+ auto struct_type = std::make_shared<TupleType>(
1131+ std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::INT64)});
1132+ auto struct_var = std::make_shared<Var>("state", struct_type, Sp());
1133+ auto call = reg.Create("block.ssbuf_store", {struct_var, MakeScalarVar("off", DataType::INT32)}, Sp());
1096 auto rt = As<ScalarType>(call->GetType());1134 auto rt = As<ScalarType>(call->GetType());
1097 ASSERT_NE(rt, nullptr);1135 ASSERT_NE(rt, nullptr);
1098 EXPECT_EQ(rt->dtype_, DataType::INDEX);1136 EXPECT_EQ(rt->dtype_, DataType::INDEX);
@@ -1101,7 +1139,10 @@ TEST_F(BlockOpsOutMemoryTest, BlockSsbufStore_ReturnsIndexScalar)
1101TEST_F(BlockOpsOutMemoryTest, BlockSsbufLoad_ReturnsIndexScalar)1139TEST_F(BlockOpsOutMemoryTest, BlockSsbufLoad_ReturnsIndexScalar)
1102{1140{
1103 auto& reg = OpRegistry::GetInstance();1141 auto& reg = OpRegistry::GetInstance();
1104- auto call = reg.Create("block.ssbuf_load", {MakeScalarVar("off", DataType::INT32)}, Sp());1142+ auto struct_type = std::make_shared<TupleType>(
1143+ std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::INT64)});
1144+ auto struct_var = std::make_shared<Var>("state", struct_type, Sp());
1145+ auto call = reg.Create("block.ssbuf_load", {struct_var, MakeScalarVar("off", DataType::INT32)}, Sp());
1105 auto rt = As<ScalarType>(call->GetType());1146 auto rt = As<ScalarType>(call->GetType());
1106 ASSERT_NE(rt, nullptr);1147 ASSERT_NE(rt, nullptr);
1107 EXPECT_EQ(rt->dtype_, DataType::INDEX);1148 EXPECT_EQ(rt->dtype_, DataType::INDEX);
@@ -35,26 +35,8 @@ namespace ir {
35 35 
36using namespace test_helpers;36using namespace test_helpers;
37 37 
38-// ============================================================================
39-// DeduceVFUnknownType: vf.vf_scope_enter, vf.vf_scope_exit
40-// ============================================================================
41- 
42class VFOpsTest : public testing::Test {};38class VFOpsTest : public testing::Test {};
43 39 
44-TEST_F(VFOpsTest, VfScopeEnter_NoArgs_ReturnsUnknown)
45-{
46- auto& reg = OpRegistry::GetInstance();
47- auto call = reg.Create("vf.vf_scope_enter", {}, Sp());
48- EXPECT_NE(As<UnknownType>(call->GetType()), nullptr);
49-}
50- 
51-TEST_F(VFOpsTest, VfScopeExit_NoArgs_ReturnsUnknown)
52-{
53- auto& reg = OpRegistry::GetInstance();
54- auto call = reg.Create("vf.vf_scope_exit", {}, Sp());
55- EXPECT_NE(As<UnknownType>(call->GetType()), nullptr);
56-}
57- 
58// ============================================================================40// ============================================================================
59// DeduceVFScalarType: vf.RegTensor41// DeduceVFScalarType: vf.RegTensor
60// ============================================================================42// ============================================================================
@@ -82,77 +64,46 @@ TEST_F(VFOpsTest, CreateMask_NoArgs_ReturnsUINT16Scalar)
82}64}
83 65 
84// ============================================================================66// ============================================================================
85-// DeduceVFFromFirstArg: vf.Duplicate67+// DeduceVFFromDstArg: vf.Duplicate
86// ============================================================================68// ============================================================================
87 69 
88-TEST_F(VFOpsTest, Duplicate_WithArg_ReturnsFirstArgType)70+TEST_F(VFOpsTest, Duplicate_WithArgs_ReturnsDstArgType)
89{71{
90 auto& reg = OpRegistry::GetInstance();72 auto& reg = OpRegistry::GetInstance();
91- auto arg = MakeScalarVar("s", DataType::FP16);73+ auto dst = MakeScalarVar("dst", DataType::FP16);
92- auto call = reg.Create("vf.Duplicate", {arg}, Sp());74+ auto scalar = MakeScalarVar("scalar", DataType::FP32);
75+ auto mask = MakeScalarVar("mask", DataType::UINT16);
76+ auto call = reg.Create("vf.Duplicate", {dst, scalar, mask}, Sp());
93 auto rt = As<ScalarType>(call->GetType());77 auto rt = As<ScalarType>(call->GetType());
94 ASSERT_NE(rt, nullptr);78 ASSERT_NE(rt, nullptr);
95 EXPECT_EQ(rt->dtype_, DataType::FP16);79 EXPECT_EQ(rt->dtype_, DataType::FP16);
96}80}
97 81 
98-TEST_F(VFOpsTest, Duplicate_NoArgs_ReturnsFP32Scalar)
99-{
100- auto& reg = OpRegistry::GetInstance();
101- auto call = reg.Create("vf.Duplicate", {}, Sp());
102- auto rt = As<ScalarType>(call->GetType());
103- ASSERT_NE(rt, nullptr);
104- EXPECT_EQ(rt->dtype_, DataType::FP32);
105-}
106- 
107// ============================================================================82// ============================================================================
108-// DeduceVFFromSecondArg: 从第二个参数推导类型83+// DeduceVFFromDstArg: vf.Muls, vf.Add
109// ============================================================================84// ============================================================================
110 85 
111-TEST_F(VFOpsTest, DeduceVFFromSecondArg_WithArgs_ReturnsSecondArgType)86+TEST_F(VFOpsTest, Muls_WithArgs_ReturnsDstArgType)
112{87{
113 auto& reg = OpRegistry::GetInstance();88 auto& reg = OpRegistry::GetInstance();
114- auto src = MakeScalarVar("src", DataType::FP16);
115 auto dst = MakeScalarVar("dst", DataType::FP32);89 auto dst = MakeScalarVar("dst", DataType::FP32);
116- auto mask = MakeScalarVar("mask", DataType::UINT16);
117- auto call = reg.Create("vf.Muls", {src, dst, mask}, Sp());
118- auto rt = As<ScalarType>(call->GetType());
119- ASSERT_NE(rt, nullptr);
120- EXPECT_EQ(rt->dtype_, DataType::FP32);
121-}
122- 
123-TEST_F(VFOpsTest, DeduceVFFromSecondArg_LessThan2Args_ReturnsFP32Scalar)
124-{
125- auto& reg = OpRegistry::GetInstance();
126 auto src = MakeScalarVar("src", DataType::FP16);90 auto src = MakeScalarVar("src", DataType::FP16);
127- auto call = reg.Create("vf.Muls", {src}, Sp());91+ auto scalar = MakeScalarVar("scalar", DataType::FP16);
92+ auto mask = MakeScalarVar("mask", DataType::UINT16);
93+ auto call = reg.Create("vf.Muls", {dst, src, scalar, mask}, Sp());
128 auto rt = As<ScalarType>(call->GetType());94 auto rt = As<ScalarType>(call->GetType());
129 ASSERT_NE(rt, nullptr);95 ASSERT_NE(rt, nullptr);
130 EXPECT_EQ(rt->dtype_, DataType::FP32);96 EXPECT_EQ(rt->dtype_, DataType::FP32);
131}97}
132 98 
133-// ============================================================================99+TEST_F(VFOpsTest, Add_WithArgs_ReturnsDstArgType)
134-// DeduceVFFromDstArg: 从目标参数推导类型
135-// ============================================================================
136- 
137-TEST_F(VFOpsTest, DeduceVFFromDstArg_WithArgs_ReturnsDstArgType)
138{100{
139 auto& reg = OpRegistry::GetInstance();101 auto& reg = OpRegistry::GetInstance();
102+ auto dst = MakeScalarVar("dst", DataType::FP32);
140 auto src0 = MakeScalarVar("src0", DataType::FP16);103 auto src0 = MakeScalarVar("src0", DataType::FP16);
141 auto src1 = MakeScalarVar("src1", DataType::FP16);104 auto src1 = MakeScalarVar("src1", DataType::FP16);
142- auto dst = MakeScalarVar("dst", DataType::FP32);
143 auto mask = MakeScalarVar("mask", DataType::UINT16);105 auto mask = MakeScalarVar("mask", DataType::UINT16);
144- auto call = reg.Create("vf.Add", {src0, src1, dst, mask}, Sp());106+ auto call = reg.Create("vf.Add", {dst, src0, src1, mask}, Sp());
145- auto rt = As<ScalarType>(call->GetType());
146- ASSERT_NE(rt, nullptr);
147- EXPECT_EQ(rt->dtype_, DataType::FP32);
148-}
149- 
150-TEST_F(VFOpsTest, DeduceVFFromDstArg_LessThan3Args_ReturnsFP32Scalar)
151-{
152- auto& reg = OpRegistry::GetInstance();
153- auto src0 = MakeScalarVar("src0", DataType::FP16);
154- auto src1 = MakeScalarVar("src1", DataType::FP16);
155- auto call = reg.Create("vf.Add", {src0, src1}, Sp());
156 auto rt = As<ScalarType>(call->GetType());107 auto rt = As<ScalarType>(call->GetType());
157 ASSERT_NE(rt, nullptr);108 ASSERT_NE(rt, nullptr);
158 EXPECT_EQ(rt->dtype_, DataType::FP32);109 EXPECT_EQ(rt->dtype_, DataType::FP32);
@@ -34,6 +34,7 @@
34#include "ir/transforms/printer.h"34#include "ir/transforms/printer.h"
35#include "ir/transforms/structural_comparison.h"35#include "ir/transforms/structural_comparison.h"
36#include "ir/type.h"36#include "ir/type.h"
37+#include "tilefwk/error.h"
37 38 
38namespace pypto {39namespace pypto {
39namespace ir {40namespace ir {
@@ -67,13 +68,13 @@ class IRTypeStrTest : public testing::Test {};
67TEST_F(IRTypeStrTest, TestUnknownTypeStr)68TEST_F(IRTypeStrTest, TestUnknownTypeStr)
68{69{
69 auto ut = std::make_shared<UnknownType>();70 auto ut = std::make_shared<UnknownType>();
70- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(ut)), "pl.Unknown");71+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(ut)), "ir.Unknown");
71}72}
72 73 
73TEST_F(IRTypeStrTest, TestScalarTypeStr)74TEST_F(IRTypeStrTest, TestScalarTypeStr)
74{75{
75 auto st = std::make_shared<ScalarType>(DataType::INT32);76 auto st = std::make_shared<ScalarType>(DataType::INT32);
76- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(st)), "pl.Scalar[pl.INT32]");77+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(st)), "ir.Scalar[ir.INT32]");
77}78}
78 79 
79TEST_F(IRTypeStrTest, TestTensorTypeStr)80TEST_F(IRTypeStrTest, TestTensorTypeStr)
@@ -81,7 +82,7 @@ TEST_F(IRTypeStrTest, TestTensorTypeStr)
81 auto dim1 = std::make_shared<ConstInt>(16, DataType::INT64, Span::Unknown());82 auto dim1 = std::make_shared<ConstInt>(16, DataType::INT64, Span::Unknown());
82 auto dim2 = std::make_shared<ConstInt>(32, DataType::INT64, Span::Unknown());83 auto dim2 = std::make_shared<ConstInt>(32, DataType::INT64, Span::Unknown());
83 auto tt = std::make_shared<TensorType>(std::vector<ExprPtr>{dim1, dim2}, DataType::FP32);84 auto tt = std::make_shared<TensorType>(std::vector<ExprPtr>{dim1, dim2}, DataType::FP32);
84- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(tt)), "pl.Tensor[[16, 32], pl.FP32]");85+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(tt)), "ir.Tensor[[16, 32], ir.FP32]");
85}86}
86 87 
87TEST_F(IRTypeStrTest, TestTensorTypeWithMemRefStr)88TEST_F(IRTypeStrTest, TestTensorTypeWithMemRefStr)
@@ -93,7 +94,7 @@ TEST_F(IRTypeStrTest, TestTensorTypeWithMemRefStr)
93 auto tt = std::make_shared<TensorType>(std::vector<ExprPtr>{dim1, dim2}, DataType::FP16, memref);94 auto tt = std::make_shared<TensorType>(std::vector<ExprPtr>{dim1, dim2}, DataType::FP16, memref);
94 ASSERT_EQ(95 ASSERT_EQ(
95 PythonPrint(std::static_pointer_cast<const Type>(tt)),96 PythonPrint(std::static_pointer_cast<const Type>(tt)),
96- "pl.Tensor[[16, 32], pl.FP16, pl.MemRef(pl.MemorySpace.DDR, 0, 1024)]");97+ "ir.Tensor[[16, 32], ir.FP16, ir.MemRef(ir.MemorySpace.DDR, 0, 1024)]");
97}98}
98 99 
99TEST_F(IRTypeStrTest, TestTupleTypeStr)100TEST_F(IRTypeStrTest, TestTupleTypeStr)
@@ -102,13 +103,13 @@ TEST_F(IRTypeStrTest, TestTupleTypeStr)
102 auto t2 = std::make_shared<ScalarType>(DataType::FP32);103 auto t2 = std::make_shared<ScalarType>(DataType::FP32);
103 auto tup = std::make_shared<TupleType>(std::vector<TypePtr>{t1, t2});104 auto tup = std::make_shared<TupleType>(std::vector<TypePtr>{t1, t2});
104 ASSERT_EQ(105 ASSERT_EQ(
105- PythonPrint(std::static_pointer_cast<const Type>(tup)), "pl.Tuple[pl.Scalar[pl.INT32], pl.Scalar[pl.FP32]]");106+ PythonPrint(std::static_pointer_cast<const Type>(tup)), "ir.Tuple[ir.Scalar[ir.INT32], ir.Scalar[ir.FP32]]");
106}107}
107 108 
108TEST_F(IRTypeStrTest, TestPtrTypeStr)109TEST_F(IRTypeStrTest, TestPtrTypeStr)
109{110{
110 auto pt = std::make_shared<PtrType>(DataType::FP32);111 auto pt = std::make_shared<PtrType>(DataType::FP32);
111- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(pt)), "pl.Ptr");112+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const Type>(pt)), "ir.Ptr");
112}113}
113 114 
114// ============================================================================115// ============================================================================
@@ -191,10 +192,10 @@ TEST_F(IRExprStrTest, TestMinMaxStr)
191 auto b = std::make_shared<ConstInt>(2, DataType::INT32, sp);192 auto b = std::make_shared<ConstInt>(2, DataType::INT32, sp);
192 193 
193 auto minExpr = std::make_shared<Min>(a, b, DataType::INT32, sp);194 auto minExpr = std::make_shared<Min>(a, b, DataType::INT32, sp);
194- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(minExpr)), "pl.min(1, 2)");195+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(minExpr)), "ir.min(1, 2)");
195 196 
196 auto maxExpr = std::make_shared<Max>(a, b, DataType::INT32, sp);197 auto maxExpr = std::make_shared<Max>(a, b, DataType::INT32, sp);
197- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(maxExpr)), "pl.max(1, 2)");198+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(maxExpr)), "ir.max(1, 2)");
198}199}
199 200 
200TEST_F(IRExprStrTest, TestUnaryOpsStr)201TEST_F(IRExprStrTest, TestUnaryOpsStr)
@@ -209,10 +210,10 @@ TEST_F(IRExprStrTest, TestUnaryOpsStr)
209 ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(notExpr)), "not True");210 ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(notExpr)), "not True");
210 211 
211 auto absExpr = std::make_shared<Abs>(a, DataType::INT32, sp);212 auto absExpr = std::make_shared<Abs>(a, DataType::INT32, sp);
212- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(absExpr)), "pl.abs(1)");213+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(absExpr)), "ir.abs(1)");
213 214 
214 auto cast = std::make_shared<Cast>(a, DataType::FP32, sp);215 auto cast = std::make_shared<Cast>(a, DataType::FP32, sp);
215- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(cast)), "pl.cast(1, pl.FP32)");216+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(cast)), "ir.cast(1, ir.FP32)");
216}217}
217 218 
218TEST_F(IRExprStrTest, TestMakeTupleAndGetItemStr)219TEST_F(IRExprStrTest, TestMakeTupleAndGetItemStr)
@@ -233,14 +234,14 @@ TEST_F(IRExprStrTest, TestCallStr)
233 auto a = std::make_shared<ConstInt>(1, DataType::INT32, sp);234 auto a = std::make_shared<ConstInt>(1, DataType::INT32, sp);
234 auto b = std::make_shared<ConstInt>(2, DataType::INT32, sp);235 auto b = std::make_shared<ConstInt>(2, DataType::INT32, sp);
235 auto call = std::make_shared<Call>("my_op", std::vector<ExprPtr>{a, b}, sp);236 auto call = std::make_shared<Call>("my_op", std::vector<ExprPtr>{a, b}, sp);
236- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(call)), "pl.call @my_op(1, 2)");237+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(call)), "ir.call @my_op(1, 2)");
237}238}
238 239 
239TEST_F(IRExprStrTest, TestMemRefStr)240TEST_F(IRExprStrTest, TestMemRefStr)
240{241{
241 auto offset = std::make_shared<ConstInt>(0, DataType::INT64, sp);242 auto offset = std::make_shared<ConstInt>(0, DataType::INT64, sp);
242 auto memref = std::make_shared<MemRef>(MemorySpace::Vec, offset, 2048, sp);243 auto memref = std::make_shared<MemRef>(MemorySpace::Vec, offset, 2048, sp);
243- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(memref)), "pl.MemRef(pl.MemorySpace.Vec, 0, 2048)");244+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(memref)), "ir.MemRef(ir.MemorySpace.Vec, 0, 2048)");
244}245}
245 246 
246// ============================================================================247// ============================================================================
@@ -258,7 +259,7 @@ TEST_F(IRStmtStrTest, TestAssignStmtStr)
258 auto x = std::make_shared<Var>("x", st, sp);259 auto x = std::make_shared<Var>("x", st, sp);
259 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);260 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);
260 auto assign = std::make_shared<AssignStmt>(x, val, sp);261 auto assign = std::make_shared<AssignStmt>(x, val, sp);
261- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(assign)), "x: pl.Scalar[pl.INT32] = 42");262+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(assign)), "x: ir.Scalar[ir.INT32] = 42");
262}263}
263 264 
264TEST_F(IRStmtStrTest, TestSeqStmtsStr)265TEST_F(IRStmtStrTest, TestSeqStmtsStr)
@@ -270,7 +271,7 @@ TEST_F(IRStmtStrTest, TestSeqStmtsStr)
270 auto seq = std::make_shared<SeqStmts>(std::vector<StmtPtr>{assign_x, assign_y}, sp);271 auto seq = std::make_shared<SeqStmts>(std::vector<StmtPtr>{assign_x, assign_y}, sp);
271 ASSERT_EQ(272 ASSERT_EQ(
272 PythonPrint(std::static_pointer_cast<const IRNode>(seq)),273 PythonPrint(std::static_pointer_cast<const IRNode>(seq)),
273- "x: pl.Scalar[pl.INT32] = 42\ny: pl.Scalar[pl.INT32] = 0");274+ "x: ir.Scalar[ir.INT32] = 42\ny: ir.Scalar[ir.INT32] = 0");
274}275}
275 276 
276TEST_F(IRStmtStrTest, TestIfStmtStr)277TEST_F(IRStmtStrTest, TestIfStmtStr)
@@ -280,7 +281,7 @@ TEST_F(IRStmtStrTest, TestIfStmtStr)
280 auto assign = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(42, DataType::INT32, sp), sp);281 auto assign = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(42, DataType::INT32, sp), sp);
281 282 
282 auto ifStmt = std::make_shared<IfStmt>(cond, assign, std::nullopt, std::vector<VarPtr>{}, sp);283 auto ifStmt = std::make_shared<IfStmt>(cond, assign, std::nullopt, std::vector<VarPtr>{}, sp);
283- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(ifStmt)), "if True:\n x: pl.Scalar[pl.INT32] = 42");284+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(ifStmt)), "if True:\n x: ir.Scalar[ir.INT32] = 42");
284}285}
285 286 
286TEST_F(IRStmtStrTest, TestIfElseStmtStr)287TEST_F(IRStmtStrTest, TestIfElseStmtStr)
@@ -294,7 +295,7 @@ TEST_F(IRStmtStrTest, TestIfElseStmtStr)
294 auto ifElse = std::make_shared<IfStmt>(cond, thenBody, elseBody, std::vector<VarPtr>{}, sp);295 auto ifElse = std::make_shared<IfStmt>(cond, thenBody, elseBody, std::vector<VarPtr>{}, sp);
295 ASSERT_EQ(296 ASSERT_EQ(
296 PythonPrint(std::static_pointer_cast<const IRNode>(ifElse)),297 PythonPrint(std::static_pointer_cast<const IRNode>(ifElse)),
297- "if True:\n x: pl.Scalar[pl.INT32] = 42\nelse:\n y: pl.Scalar[pl.INT32] = 0");298+ "if True:\n x: ir.Scalar[ir.INT32] = 42\nelse:\n y: ir.Scalar[ir.INT32] = 0");
298}299}
299 300 
300TEST_F(IRStmtStrTest, TestForStmtStr)301TEST_F(IRStmtStrTest, TestForStmtStr)
@@ -313,8 +314,8 @@ TEST_F(IRStmtStrTest, TestForStmtStr)
313 314 
314 ASSERT_EQ(315 ASSERT_EQ(
315 PythonPrint(std::static_pointer_cast<const IRNode>(forStmt)),316 PythonPrint(std::static_pointer_cast<const IRNode>(forStmt)),
316- "for i, (sum,) in pl.range(0, 10, 1, init_values=(0,)):\n"317+ "for i, (sum,) in ir.range(0, 10, 1, init_values=(0,)):\n"
317- " sum_out: pl.Scalar[pl.INT32] = pl.yield_(1)");318+ " sum_out: ir.Scalar[ir.INT32] = ir.yield_(1)");
318}319}
319 320 
320TEST_F(IRStmtStrTest, TestWhileStmtStr)321TEST_F(IRStmtStrTest, TestWhileStmtStr)
@@ -325,17 +326,17 @@ TEST_F(IRStmtStrTest, TestWhileStmtStr)
325 326 
326 auto whileStmt = std::make_shared<WhileStmt>(cond, std::vector<IterArgPtr>{}, assign, std::vector<VarPtr>{}, sp);327 auto whileStmt = std::make_shared<WhileStmt>(cond, std::vector<IterArgPtr>{}, assign, std::vector<VarPtr>{}, sp);
327 ASSERT_EQ(328 ASSERT_EQ(
328- PythonPrint(std::static_pointer_cast<const IRNode>(whileStmt)), "while True:\n x: pl.Scalar[pl.INT32] = 42");329+ PythonPrint(std::static_pointer_cast<const IRNode>(whileStmt)), "while True:\n x: ir.Scalar[ir.INT32] = 42");
329}330}
330 331 
331TEST_F(IRStmtStrTest, TestYieldStmtStr)332TEST_F(IRStmtStrTest, TestYieldStmtStr)
332{333{
333 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);334 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);
334 auto yield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{val}, sp);335 auto yield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{val}, sp);
335- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(yield)), "pl.yield_(42)");336+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(yield)), "ir.yield_(42)");
336 337 
337 auto emptyYield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, sp);338 auto emptyYield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, sp);
338- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(emptyYield)), "pl.yield_()");339+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(emptyYield)), "ir.yield_()");
339}340}
340 341 
341TEST_F(IRStmtStrTest, TestReturnStmtStr)342TEST_F(IRStmtStrTest, TestReturnStmtStr)
@@ -362,7 +363,7 @@ TEST_F(IRStmtStrTest, TestEvalStmtStr)
362 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);363 auto val = std::make_shared<ConstInt>(42, DataType::INT32, sp);
363 auto call = std::make_shared<Call>("some_op", std::vector<ExprPtr>{val}, sp);364 auto call = std::make_shared<Call>("some_op", std::vector<ExprPtr>{val}, sp);
364 auto eval = std::make_shared<EvalStmt>(call, sp);365 auto eval = std::make_shared<EvalStmt>(call, sp);
365- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(eval)), "pl.eval(pl.call @some_op(42))");366+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(eval)), "ir.eval(ir.call @some_op(42))");
366}367}
367 368 
368TEST_F(IRStmtStrTest, TestFunctionStr)369TEST_F(IRStmtStrTest, TestFunctionStr)
@@ -373,8 +374,8 @@ TEST_F(IRStmtStrTest, TestFunctionStr)
373 374 
374 ASSERT_EQ(375 ASSERT_EQ(
375 PythonPrint(std::static_pointer_cast<const IRNode>(func)),376 PythonPrint(std::static_pointer_cast<const IRNode>(func)),
376- "@pl.function\ndef test_func(x: pl.Scalar[pl.INT32]) -> pl.Scalar[pl.INT32]:\n"377+ "@ir.function\ndef test_func(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:\n"
377- " x: pl.Scalar[pl.INT32] = 42");378+ " x: ir.Scalar[ir.INT32] = 42");
378}379}
379 380 
380TEST_F(IRStmtStrTest, TestProgramStr)381TEST_F(IRStmtStrTest, TestProgramStr)
@@ -387,12 +388,12 @@ TEST_F(IRStmtStrTest, TestProgramStr)
387 auto prog = std::make_shared<Program>(std::vector<FunctionPtr>{func1, func2}, "test_prog", sp);388 auto prog = std::make_shared<Program>(std::vector<FunctionPtr>{func1, func2}, "test_prog", sp);
388 389 
389 std::string expected = "# ir.program: test_prog\n"390 std::string expected = "# ir.program: test_prog\n"
390- "@pl.function\n"391+ "@ir.function\n"
391- "def test_func(x: pl.Scalar[pl.INT32]) -> pl.Scalar[pl.INT32]:\n"392+ "def test_func(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:\n"
392- " x: pl.Scalar[pl.INT32] = 42\n"393+ " x: ir.Scalar[ir.INT32] = 42\n"
393- "@pl.function\n"394+ "@ir.function\n"
394- "def test_func2(x: pl.Scalar[pl.INT32]) -> pl.Scalar[pl.INT32]:\n"395+ "def test_func2(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:\n"
395- " x: pl.Scalar[pl.INT32] = 42";396+ " x: ir.Scalar[ir.INT32] = 42";
396 ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(prog)), expected);397 ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(prog)), expected);
397 398 
398 ASSERT_NE(prog->GetFunction("test_func"), nullptr);399 ASSERT_NE(prog->GetFunction("test_func"), nullptr);
@@ -405,27 +406,8 @@ TEST_F(IRStmtStrTest, TestProgramStr)
405class IRStructuralTest : public testing::Test {406class IRStructuralTest : public testing::Test {
406protected:407protected:
407 Span sp = Span("test", 1, 1);408 Span sp = Span("test", 1, 1);
408- Span sp2 = Span("other", 5, 6);
409};409};
410 410 
411-TEST_F(IRStructuralTest, TestHashIdenticalNodes)
412-{
413- auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), sp);
414- auto b = std::make_shared<Var>("x", Scalar(DataType::INT32), sp);
415- ASSERT_EQ(
416- structural_hash(std::static_pointer_cast<const IRNode>(a)),
417- structural_hash(std::static_pointer_cast<const IRNode>(b)));
418-}
419- 
420-TEST_F(IRStructuralTest, TestHashDifferentNodes)
421-{
422- auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), sp);
423- auto b = std::make_shared<Var>("y", Scalar(DataType::INT32), sp);
424- ASSERT_NE(
425- structural_hash(std::static_pointer_cast<const IRNode>(a)),
426- structural_hash(std::static_pointer_cast<const IRNode>(b)));
427-}
428- 
429TEST_F(IRStructuralTest, TestHashIgnoresSpan)411TEST_F(IRStructuralTest, TestHashIgnoresSpan)
430{412{
431 auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), Span("file_a", 1, 1));413 auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), Span("file_a", 1, 1));
@@ -499,7 +481,7 @@ TEST_F(IRStructuralTest, TestAssertStructuralEqualFail)
499 auto b = std::make_shared<ConstInt>(99, DataType::INT32, sp);481 auto b = std::make_shared<ConstInt>(99, DataType::INT32, sp);
500 ASSERT_THROW(482 ASSERT_THROW(
501 assert_structural_equal(std::static_pointer_cast<const IRNode>(a), std::static_pointer_cast<const IRNode>(b)),483 assert_structural_equal(std::static_pointer_cast<const IRNode>(a), std::static_pointer_cast<const IRNode>(b)),
502- ValueError);484+ npu::tile_fwk::Error);
503}485}
504 486 
505TEST_F(IRStructuralTest, TestHashType)487TEST_F(IRStructuralTest, TestHashType)
@@ -533,7 +515,7 @@ TEST_F(IRStructuralTest, TestAssertStructuralEqualTypeFail)
533{515{
534 auto t1 = std::make_shared<ScalarType>(DataType::INT32);516 auto t1 = std::make_shared<ScalarType>(DataType::INT32);
535 auto t2 = std::make_shared<ScalarType>(DataType::FP32);517 auto t2 = std::make_shared<ScalarType>(DataType::FP32);
536- ASSERT_THROW(assert_structural_equal(t1, t2), ValueError);518+ ASSERT_THROW(assert_structural_equal(t1, t2), npu::tile_fwk::Error);
537}519}
538 520 
539TEST_F(IRStructuralTest, TestEqualComplexExpressions)521TEST_F(IRStructuralTest, TestEqualComplexExpressions)
@@ -168,7 +168,7 @@ TEST_F(IRBuilderTest, TestAssign)
168 b.EndFunction(sp);168 b.EndFunction(sp);
169 169 
170 ASSERT_NE(stmt, nullptr);170 ASSERT_NE(stmt, nullptr);
171- ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(stmt)), "x: pl.Scalar[pl.INT32] = 42");171+ ASSERT_EQ(PythonPrint(std::static_pointer_cast<const IRNode>(stmt)), "x: ir.Scalar[ir.INT32] = 42");
172}172}
173 173 
174TEST_F(IRBuilderTest, TestReturnWithValues)174TEST_F(IRBuilderTest, TestReturnWithValues)
@@ -401,7 +401,7 @@ TEST_F(IRPrinterTest, TestPrintFunction)
401 auto funcStr = Print(std::make_shared<Function>(401 auto funcStr = Print(std::make_shared<Function>(
402 "f", std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)}, body, Sp()));402 "f", std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)}, body, Sp()));
403 EXPECT_NE(funcStr.find("def f"), std::string::npos);403 EXPECT_NE(funcStr.find("def f"), std::string::npos);
404- EXPECT_NE(funcStr.find("@pl.function"), std::string::npos);404+ EXPECT_NE(funcStr.find("@ir.function"), std::string::npos);
405 405 
406 // Multi params406 // Multi params
407 auto yield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, Sp());407 auto yield = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, Sp());
@@ -18,6 +18,7 @@
18#include "ir/stmt.h"18#include "ir/stmt.h"
19#include "ir/transforms/structural_comparison.h"19#include "ir/transforms/structural_comparison.h"
20#include "op/test_op_helpers.h"20#include "op/test_op_helpers.h"
21+#include "tilefwk/error.h"
21 22 
22namespace pypto {23namespace pypto {
23namespace ir {24namespace ir {
@@ -260,40 +261,41 @@ TEST_F(IRStructEqAssertTest, TestAssertExprMismatches)
260 261 
261 // Type mismatch (ConstInt vs ConstFloat)262 // Type mismatch (ConstInt vs ConstFloat)
262 EXPECT_THROW(263 EXPECT_THROW(
263- assert_structural_equal(Node(a), Node(std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp()))), ValueError);264+ assert_structural_equal(Node(a), Node(std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp()))),
265+ npu::tile_fwk::Error);
264 266 
265 // Null mismatch267 // Null mismatch
266- EXPECT_THROW(assert_structural_equal(Node(a), nullptr), ValueError);268+ EXPECT_THROW(assert_structural_equal(Node(a), nullptr), npu::tile_fwk::Error);
267 269 
268 // Int mismatch270 // Int mismatch
269- EXPECT_THROW(assert_structural_equal(Node(a), Node(b)), ValueError);271+ EXPECT_THROW(assert_structural_equal(Node(a), Node(b)), npu::tile_fwk::Error);
270 272 
271 // Float mismatch273 // Float mismatch
272 EXPECT_THROW(274 EXPECT_THROW(
273 assert_structural_equal(275 assert_structural_equal(
274 Node(std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp())),276 Node(std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp())),
275 Node(std::make_shared<ConstFloat>(2.0, DataType::FP32, Sp()))),277 Node(std::make_shared<ConstFloat>(2.0, DataType::FP32, Sp()))),
276- ValueError);278+ npu::tile_fwk::Error);
277 279 
278 // Bool mismatch280 // Bool mismatch
279 EXPECT_THROW(281 EXPECT_THROW(
280 assert_structural_equal(282 assert_structural_equal(
281 Node(std::make_shared<ConstBool>(true, Sp())), Node(std::make_shared<ConstBool>(false, Sp()))),283 Node(std::make_shared<ConstBool>(true, Sp())), Node(std::make_shared<ConstBool>(false, Sp()))),
282- ValueError);284+ npu::tile_fwk::Error);
283 285 
284 // Call name mismatch286 // Call name mismatch
285 EXPECT_THROW(287 EXPECT_THROW(
286 assert_structural_equal(288 assert_structural_equal(
287 Node(std::make_shared<Call>("op_a", std::vector<ExprPtr>{a}, Sp())),289 Node(std::make_shared<Call>("op_a", std::vector<ExprPtr>{a}, Sp())),
288 Node(std::make_shared<Call>("op_b", std::vector<ExprPtr>{a}, Sp()))),290 Node(std::make_shared<Call>("op_b", std::vector<ExprPtr>{a}, Sp()))),
289- ValueError);291+ npu::tile_fwk::Error);
290 292 
291 // Call arg count mismatch293 // Call arg count mismatch
292 EXPECT_THROW(294 EXPECT_THROW(
293 assert_structural_equal(295 assert_structural_equal(
294 Node(std::make_shared<Call>("op", std::vector<ExprPtr>{a}, Sp())),296 Node(std::make_shared<Call>("op", std::vector<ExprPtr>{a}, Sp())),
295 Node(std::make_shared<Call>("op", std::vector<ExprPtr>{a, b}, Sp()))),297 Node(std::make_shared<Call>("op", std::vector<ExprPtr>{a, b}, Sp()))),
296- ValueError);298+ npu::tile_fwk::Error);
297}299}
298 300 
299TEST_F(IRStructEqAssertTest, TestAssertStmtMismatches)301TEST_F(IRStructEqAssertTest, TestAssertStmtMismatches)
@@ -309,14 +311,14 @@ TEST_F(IRStructEqAssertTest, TestAssertStmtMismatches)
309 assert_structural_equal(311 assert_structural_equal(
310 Node(std::make_shared<Function>("f", std::vector<VarPtr>{x}, std::vector<TypePtr>{}, body1, Sp())),312 Node(std::make_shared<Function>("f", std::vector<VarPtr>{x}, std::vector<TypePtr>{}, body1, Sp())),
311 Node(std::make_shared<Function>("f", std::vector<VarPtr>{x}, std::vector<TypePtr>{}, body2, Sp()))),313 Node(std::make_shared<Function>("f", std::vector<VarPtr>{x}, std::vector<TypePtr>{}, body2, Sp()))),
312- ValueError);314+ npu::tile_fwk::Error);
313 315 
314 // Optional field mismatch (IfStmt with/without else)316 // Optional field mismatch (IfStmt with/without else)
315 EXPECT_THROW(317 EXPECT_THROW(
316 assert_structural_equal(318 assert_structural_equal(
317 Node(std::make_shared<IfStmt>(cond, yield, std::nullopt, std::vector<VarPtr>{}, Sp())),319 Node(std::make_shared<IfStmt>(cond, yield, std::nullopt, std::vector<VarPtr>{}, Sp())),
318 Node(std::make_shared<IfStmt>(cond, yield, yield, std::vector<VarPtr>{}, Sp()))),320 Node(std::make_shared<IfStmt>(cond, yield, yield, std::vector<VarPtr>{}, Sp()))),
319- ValueError);321+ npu::tile_fwk::Error);
320 322 
321 // Vector size mismatch (SeqStmts)323 // Vector size mismatch (SeqStmts)
322 auto a1 = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(1, DataType::INT32, Sp()), Sp());324 auto a1 = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(1, DataType::INT32, Sp()), Sp());
@@ -325,7 +327,7 @@ TEST_F(IRStructEqAssertTest, TestAssertStmtMismatches)
325 assert_structural_equal(327 assert_structural_equal(
326 Node(std::make_shared<SeqStmts>(std::vector<StmtPtr>{a1}, Sp())),328 Node(std::make_shared<SeqStmts>(std::vector<StmtPtr>{a1}, Sp())),
327 Node(std::make_shared<SeqStmts>(std::vector<StmtPtr>{a1, a2}, Sp()))),329 Node(std::make_shared<SeqStmts>(std::vector<StmtPtr>{a1, a2}, Sp()))),
328- ValueError);330+ npu::tile_fwk::Error);
329}331}
330 332 
331TEST_F(IRStructEqAssertTest, TestAssertTypeMismatches)333TEST_F(IRStructEqAssertTest, TestAssertTypeMismatches)
@@ -336,38 +338,38 @@ TEST_F(IRStructEqAssertTest, TestAssertTypeMismatches)
336 EXPECT_THROW(338 EXPECT_THROW(
337 assert_structural_equal(339 assert_structural_equal(
338 std::make_shared<ScalarType>(DataType::INT32), std::make_shared<ScalarType>(DataType::FP32)),340 std::make_shared<ScalarType>(DataType::INT32), std::make_shared<ScalarType>(DataType::FP32)),
339- ValueError);341+ npu::tile_fwk::Error);
340 342 
341 // Tuple elements343 // Tuple elements
342 EXPECT_THROW(344 EXPECT_THROW(
343 assert_structural_equal(345 assert_structural_equal(
344 std::make_shared<TupleType>(std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::INT32)}),346 std::make_shared<TupleType>(std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::INT32)}),
345 std::make_shared<TupleType>(std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::FP32)})),347 std::make_shared<TupleType>(std::vector<TypePtr>{std::make_shared<ScalarType>(DataType::FP32)})),
346- ValueError);348+ npu::tile_fwk::Error);
347 349 
348 // Tensor dtype / shape rank350 // Tensor dtype / shape rank
349 EXPECT_THROW(351 EXPECT_THROW(
350 assert_structural_equal(352 assert_structural_equal(
351 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32),353 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32),
352 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP16)),354 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP16)),
353- ValueError);355+ npu::tile_fwk::Error);
354 EXPECT_THROW(356 EXPECT_THROW(
355 assert_structural_equal(357 assert_structural_equal(
356 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32),358 std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32),
357 std::make_shared<TensorType>(std::vector<ExprPtr>{d, d}, DataType::FP32)),359 std::make_shared<TensorType>(std::vector<ExprPtr>{d, d}, DataType::FP32)),
358- ValueError);360+ npu::tile_fwk::Error);
359 361 
360 // Tile dtype / shape rank362 // Tile dtype / shape rank
361 EXPECT_THROW(363 EXPECT_THROW(
362 assert_structural_equal(364 assert_structural_equal(
363 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32),365 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32),
364 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP16)),366 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP16)),
365- ValueError);367+ npu::tile_fwk::Error);
366 EXPECT_THROW(368 EXPECT_THROW(
367 assert_structural_equal(369 assert_structural_equal(
368 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32),370 std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32),
369 std::make_shared<TileType>(std::vector<ExprPtr>{d, d}, DataType::FP32)),371 std::make_shared<TileType>(std::vector<ExprPtr>{d, d}, DataType::FP32)),
370- ValueError);372+ npu::tile_fwk::Error);
371 373 
372 // Tuple size374 // Tuple size
373 auto s = std::make_shared<ScalarType>(DataType::INT32);375 auto s = std::make_shared<ScalarType>(DataType::INT32);
@@ -375,7 +377,7 @@ TEST_F(IRStructEqAssertTest, TestAssertTypeMismatches)
375 assert_structural_equal(377 assert_structural_equal(
376 std::make_shared<TupleType>(std::vector<TypePtr>{s}),378 std::make_shared<TupleType>(std::vector<TypePtr>{s}),
377 std::make_shared<TupleType>(std::vector<TypePtr>{s, s})),379 std::make_shared<TupleType>(std::vector<TypePtr>{s, s})),
378- ValueError);380+ npu::tile_fwk::Error);
379}381}
380 382 
381// ============================================================================383// ============================================================================
@@ -522,7 +524,7 @@ TEST_F(IRStructEqTypeTest, TestTileTypeWithHardwareInfo)
522 auto tl3 = std::make_shared<TileType>(524 auto tl3 = std::make_shared<TileType>(
523 std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, std::nullopt, hw3);525 std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, std::nullopt, hw3);
524 EXPECT_FALSE(structural_equal(tl1, tl3));526 EXPECT_FALSE(structural_equal(tl1, tl3));
525- EXPECT_THROW(assert_structural_equal(tl1, tl3), ValueError);527+ EXPECT_THROW(assert_structural_equal(tl1, tl3), npu::tile_fwk::Error);
526}528}
527 529 
528TEST_F(IRStructEqTypeTest, TestTileTypeTileViewPresenceMismatch)530TEST_F(IRStructEqTypeTest, TestTileTypeTileViewPresenceMismatch)
@@ -590,12 +592,12 @@ TEST_F(IRStructEqExprTest, TestCallWithKwargsMismatch)
590 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());592 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());
591 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());593 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());
592 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));594 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));
593- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), ValueError);595+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), npu::tile_fwk::Error);
594 596 
595 std::vector<std::pair<std::string, std::any>> kwargs3 = {{"mode", std::any(std::string("round"))}, {"axis", std::any(int(0))}};597 std::vector<std::pair<std::string, std::any>> kwargs3 = {{"mode", std::any(std::string("round"))}, {"axis", std::any(int(0))}};
596 auto c3 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs3, Scalar(DataType::INT32), Sp());598 auto c3 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs3, Scalar(DataType::INT32), Sp());
597 EXPECT_FALSE(structural_equal(Node(c1), Node(c3)));599 EXPECT_FALSE(structural_equal(Node(c1), Node(c3)));
598- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c3)), ValueError);600+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c3)), npu::tile_fwk::Error);
599}601}
600 602 
601TEST_F(IRStructEqExprTest, TestCallKwargsSizeMismatch)603TEST_F(IRStructEqExprTest, TestCallKwargsSizeMismatch)
@@ -607,7 +609,7 @@ TEST_F(IRStructEqExprTest, TestCallKwargsSizeMismatch)
607 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());609 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());
608 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());610 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());
609 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));611 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));
610- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), ValueError);612+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), npu::tile_fwk::Error);
611}613}
612 614 
613TEST_F(IRStructEqExprTest, TestCallKwargsIntValue)615TEST_F(IRStructEqExprTest, TestCallKwargsIntValue)
@@ -679,7 +681,7 @@ TEST_F(IRStructEqExprTest, TestCallKwargsKeyTypeMismatch)
679 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());681 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());
680 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());682 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());
681 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));683 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));
682- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), ValueError);684+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), npu::tile_fwk::Error);
683}685}
684 686 
685TEST_F(IRStructEqExprTest, TestCallKwargsValueTypeMismatch)687TEST_F(IRStructEqExprTest, TestCallKwargsValueTypeMismatch)
@@ -691,7 +693,7 @@ TEST_F(IRStructEqExprTest, TestCallKwargsValueTypeMismatch)
691 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());693 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs1, Scalar(DataType::INT32), Sp());
692 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());694 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs2, Scalar(DataType::INT32), Sp());
693 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));695 EXPECT_FALSE(structural_equal(Node(c1), Node(c2)));
694- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), ValueError);696+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2)), npu::tile_fwk::Error);
695}697}
696 698 
697// ============================================================================699// ============================================================================
@@ -708,7 +710,7 @@ TEST_F(IRStructEqExprTest, TestFunctionReturnTypesSizeMismatch)
708 auto f2 = std::make_shared<Function>(710 auto f2 = std::make_shared<Function>(
709 "f", std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32), Scalar(DataType::FP32)}, body, Sp());711 "f", std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32), Scalar(DataType::FP32)}, body, Sp());
710 EXPECT_FALSE(structural_equal(Node(f1), Node(f2)));712 EXPECT_FALSE(structural_equal(Node(f1), Node(f2)));
711- EXPECT_THROW(assert_structural_equal(Node(f1), Node(f2)), ValueError);713+ EXPECT_THROW(assert_structural_equal(Node(f1), Node(f2)), npu::tile_fwk::Error);
712}714}
713 715 
714TEST_F(IRStructEqExprTest, TestFunctionReturnTypesElementMismatch)716TEST_F(IRStructEqExprTest, TestFunctionReturnTypesElementMismatch)
@@ -742,7 +744,7 @@ TEST_F(IRStructEqExprTest, TestForStmtIterArgSizeMismatch)
742 i, zero, ten, one, std::vector<IterArgPtr>{ia}, yield, std::vector<VarPtr>{}, Sp());744 i, zero, ten, one, std::vector<IterArgPtr>{ia}, yield, std::vector<VarPtr>{}, Sp());
743 745 
744 EXPECT_FALSE(structural_equal(Node(for1), Node(for2)));746 EXPECT_FALSE(structural_equal(Node(for1), Node(for2)));
745- EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), ValueError);747+ EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), npu::tile_fwk::Error);
746}748}
747 749 
748// ============================================================================750// ============================================================================
@@ -777,15 +779,15 @@ TEST_F(IRStructEqAssertTest, TestMemRefMismatch)
777 auto mr1 = std::make_shared<MemRef>(MemorySpace::DDR, off0, 1024, Sp());779 auto mr1 = std::make_shared<MemRef>(MemorySpace::DDR, off0, 1024, Sp());
778 auto mr2 = std::make_shared<MemRef>(MemorySpace::DDR, off100, 1024, Sp());780 auto mr2 = std::make_shared<MemRef>(MemorySpace::DDR, off100, 1024, Sp());
779 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr2)));781 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr2)));
780- EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr2)), ValueError);782+ EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr2)), npu::tile_fwk::Error);
781 783 
782 auto mr3 = std::make_shared<MemRef>(MemorySpace::DDR, off0, 2048, Sp());784 auto mr3 = std::make_shared<MemRef>(MemorySpace::DDR, off0, 2048, Sp());
783 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr3)));785 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr3)));
784- EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr3)), ValueError);786+ EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr3)), npu::tile_fwk::Error);
785 787 
786 auto mr4 = std::make_shared<MemRef>(MemorySpace::Vec, off0, 1024, Sp());788 auto mr4 = std::make_shared<MemRef>(MemorySpace::Vec, off0, 1024, Sp());
787 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr4)));789 EXPECT_FALSE(structural_equal(Node(mr1), Node(mr4)));
788- EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr4)), ValueError);790+ EXPECT_THROW(assert_structural_equal(Node(mr1), Node(mr4)), npu::tile_fwk::Error);
789}791}
790 792 
791// ============================================================================793// ============================================================================
@@ -801,7 +803,7 @@ TEST_F(IRStructEqAssertTest, TestAssertProgramMapMismatch)
801 803 
802 auto p1 = std::make_shared<Program>(std::vector<FunctionPtr>{f1}, "prog", Sp());804 auto p1 = std::make_shared<Program>(std::vector<FunctionPtr>{f1}, "prog", Sp());
803 auto p2 = std::make_shared<Program>(std::vector<FunctionPtr>{f2}, "prog", Sp());805 auto p2 = std::make_shared<Program>(std::vector<FunctionPtr>{f2}, "prog", Sp());
804- EXPECT_THROW(assert_structural_equal(Node(p1), Node(p2)), ValueError);806+ EXPECT_THROW(assert_structural_equal(Node(p1), Node(p2)), npu::tile_fwk::Error);
805}807}
806 808 
807TEST_F(IRStructEqAssertTest, TestAssertProgramMapSizeMismatch)809TEST_F(IRStructEqAssertTest, TestAssertProgramMapSizeMismatch)
@@ -814,7 +816,7 @@ TEST_F(IRStructEqAssertTest, TestAssertProgramMapSizeMismatch)
814 816 
815 auto p1 = std::make_shared<Program>(std::vector<FunctionPtr>{f1}, "prog", Sp());817 auto p1 = std::make_shared<Program>(std::vector<FunctionPtr>{f1}, "prog", Sp());
816 auto p2 = std::make_shared<Program>(std::vector<FunctionPtr>{f1, f2}, "prog", Sp());818 auto p2 = std::make_shared<Program>(std::vector<FunctionPtr>{f1, f2}, "prog", Sp());
817- EXPECT_THROW(assert_structural_equal(Node(p1), Node(p2)), ValueError);819+ EXPECT_THROW(assert_structural_equal(Node(p1), Node(p2)), npu::tile_fwk::Error);
818}820}
819 821 
820 822 
@@ -846,8 +848,8 @@ TEST_F(IRStructEqAssertTest, TestAssertOneNullNode)
846 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());848 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());
847 IRNodePtr null_ptr;849 IRNodePtr null_ptr;
848 850 
849- EXPECT_THROW(assert_structural_equal(Node(x), null_ptr), ValueError);851+ EXPECT_THROW(assert_structural_equal(Node(x), null_ptr), npu::tile_fwk::Error);
850- EXPECT_THROW(assert_structural_equal(null_ptr, Node(x)), ValueError);852+ EXPECT_THROW(assert_structural_equal(null_ptr, Node(x)), npu::tile_fwk::Error);
851}853}
852 854 
853TEST_F(IRStructEqAssertTest, TestAssertNodeTypeMismatch)855TEST_F(IRStructEqAssertTest, TestAssertNodeTypeMismatch)
@@ -855,7 +857,7 @@ TEST_F(IRStructEqAssertTest, TestAssertNodeTypeMismatch)
855 auto ci = std::make_shared<ConstInt>(1, DataType::INT32, Sp());857 auto ci = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
856 auto cf = std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp());858 auto cf = std::make_shared<ConstFloat>(1.0, DataType::FP32, Sp());
857 859 
858- EXPECT_THROW(assert_structural_equal(Node(ci), Node(cf)), ValueError);860+ EXPECT_THROW(assert_structural_equal(Node(ci), Node(cf)), npu::tile_fwk::Error);
859}861}
860 862 
861// ============================================================================863// ============================================================================
@@ -921,7 +923,7 @@ TEST_F(IRStructEqExprTest, TestVarAutoMapping_ReverseInconsistent)
921 }, Sp());923 }, Sp());
922 924 
923 EXPECT_FALSE(structural_equal(Node(seq1), Node(seq2), true));925 EXPECT_FALSE(structural_equal(Node(seq1), Node(seq2), true));
924- EXPECT_THROW(assert_structural_equal(Node(seq1), Node(seq2)), ValueError);926+ EXPECT_THROW(assert_structural_equal(Node(seq1), Node(seq2)), npu::tile_fwk::Error);
925}927}
926 928 
927// ============================================================================929// ============================================================================
@@ -947,7 +949,7 @@ TEST_F(IRStructEqExprTest, TestIterArgInitValueMismatch)
947 i, zero, ten, step, std::vector<IterArgPtr>{ia2}, yield, std::vector<VarPtr>{rv}, Sp());949 i, zero, ten, step, std::vector<IterArgPtr>{ia2}, yield, std::vector<VarPtr>{rv}, Sp());
948 950 
949 EXPECT_FALSE(structural_equal(Node(for1), Node(for2)));951 EXPECT_FALSE(structural_equal(Node(for1), Node(for2)));
950- EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), ValueError);952+ EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), npu::tile_fwk::Error);
951}953}
952 954 
953// ============================================================================955// ============================================================================
@@ -973,9 +975,12 @@ TEST_F(IRStructEqAssertTest, TestAssertConstIntValueMismatch)
973 975 
974 try {976 try {
975 assert_structural_equal(Node(a), Node(b));977 assert_structural_equal(Node(a), Node(b));
976- FAIL() << "Expected ValueError";978+ FAIL() << "Expected npu::tile_fwk::Error";
977- } catch (const ValueError& e) {979+ } catch (const npu::tile_fwk::Error& e) {
978 std::string msg = e.what();980 std::string msg = e.what();
981+ EXPECT_TRUE(msg.find("ASSERT FAILED") != std::string::npos);
982+ EXPECT_TRUE(msg.find("INVALID_VAL") != std::string::npos);
983+ EXPECT_TRUE(msg.find("Structural equality assertion failed") != std::string::npos);
979 EXPECT_TRUE(msg.find("int64_t") != std::string::npos);984 EXPECT_TRUE(msg.find("int64_t") != std::string::npos);
980 }985 }
981}986}
@@ -987,8 +992,8 @@ TEST_F(IRStructEqAssertTest, TestAssertConstFloatValueMismatch)
987 992 
988 try {993 try {
989 assert_structural_equal(Node(a), Node(b));994 assert_structural_equal(Node(a), Node(b));
990- FAIL() << "Expected ValueError";995+ FAIL() << "Expected npu::tile_fwk::Error";
991- } catch (const ValueError& e) {996+ } catch (const npu::tile_fwk::Error& e) {
992 std::string msg = e.what();997 std::string msg = e.what();
993 EXPECT_TRUE(msg.find("double") != std::string::npos);998 EXPECT_TRUE(msg.find("double") != std::string::npos);
994 }999 }
@@ -1003,8 +1008,8 @@ TEST_F(IRStructEqAssertTest, TestAssertSectionKindMismatch)
1003 assert_structural_equal(1008 assert_structural_equal(
1004 Node(std::make_shared<SectionStmt>(SectionKind::Vector, body, Sp())),1009 Node(std::make_shared<SectionStmt>(SectionKind::Vector, body, Sp())),
1005 Node(std::make_shared<SectionStmt>(SectionKind::Cube, body, Sp())));1010 Node(std::make_shared<SectionStmt>(SectionKind::Cube, body, Sp())));
1006- FAIL() << "Expected ValueError";1011+ FAIL() << "Expected npu::tile_fwk::Error";
1007- } catch (const ValueError& e) {1012+ } catch (const npu::tile_fwk::Error& e) {
1008 std::string msg = e.what();1013 std::string msg = e.what();
1009 EXPECT_TRUE(msg.find("SectionKind") != std::string::npos);1014 EXPECT_TRUE(msg.find("SectionKind") != std::string::npos);
1010 }1015 }
@@ -1020,8 +1025,8 @@ TEST_F(IRStructEqAssertTest, TestAssertVarTypeMismatch)
1020 assert_structural_equal(1025 assert_structural_equal(
1021 Node(std::make_shared<AssignStmt>(x, v1, Sp())),1026 Node(std::make_shared<AssignStmt>(x, v1, Sp())),
1022 Node(std::make_shared<AssignStmt>(z, v1, Sp())));1027 Node(std::make_shared<AssignStmt>(z, v1, Sp())));
1023- FAIL() << "Expected ValueError";1028+ FAIL() << "Expected npu::tile_fwk::Error";
1024- } catch (const ValueError& e) {1029+ } catch (const npu::tile_fwk::Error& e) {
1025 std::string msg = e.what();1030 std::string msg = e.what();
1026 EXPECT_TRUE(msg.find("Variable") != std::string::npos || msg.find("type") != std::string::npos);1031 EXPECT_TRUE(msg.find("Variable") != std::string::npos || msg.find("type") != std::string::npos);
1027 }1032 }
@@ -1045,8 +1050,8 @@ TEST_F(IRStructEqAssertTest, TestAssertVarMappingInconsistent)
1045 1050 
1046 try {1051 try {
1047 assert_structural_equal(Node(seq1), Node(seq2));1052 assert_structural_equal(Node(seq1), Node(seq2));
1048- FAIL() << "Expected ValueError";1053+ FAIL() << "Expected npu::tile_fwk::Error";
1049- } catch (const ValueError& e) {1054+ } catch (const npu::tile_fwk::Error& e) {
1050 std::string msg = e.what();1055 std::string msg = e.what();
1051 EXPECT_TRUE(msg.find("Variable") != std::string::npos || msg.find("mapping") != std::string::npos);1056 EXPECT_TRUE(msg.find("Variable") != std::string::npos || msg.find("mapping") != std::string::npos);
1052 }1057 }
@@ -1066,8 +1071,8 @@ TEST_F(IRStructEqAssertTest, TestAssertHardwareInfoSlayoutMismatch)
1066 1071 
1067 try {1072 try {
1068 assert_structural_equal(tl1, tl2);1073 assert_structural_equal(tl1, tl2);
1069- FAIL() << "Expected ValueError";1074+ FAIL() << "Expected npu::tile_fwk::Error";
1070- } catch (const ValueError& e) {1075+ } catch (const npu::tile_fwk::Error& e) {
1071 std::string msg = e.what();1076 std::string msg = e.what();
1072 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("slayout") != std::string::npos);1077 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("slayout") != std::string::npos);
1073 }1078 }
@@ -1085,8 +1090,8 @@ TEST_F(IRStructEqAssertTest, TestAssertHardwareInfoFractalMismatch)
1085 1090 
1086 try {1091 try {
1087 assert_structural_equal(tl1, tl2);1092 assert_structural_equal(tl1, tl2);
1088- FAIL() << "Expected ValueError";1093+ FAIL() << "Expected npu::tile_fwk::Error";
1089- } catch (const ValueError& e) {1094+ } catch (const npu::tile_fwk::Error& e) {
1090 std::string msg = e.what();1095 std::string msg = e.what();
1091 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("fractal") != std::string::npos);1096 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("fractal") != std::string::npos);
1092 }1097 }
@@ -1104,8 +1109,8 @@ TEST_F(IRStructEqAssertTest, TestAssertHardwareInfoPadMismatch)
1104 1109 
1105 try {1110 try {
1106 assert_structural_equal(tl1, tl2);1111 assert_structural_equal(tl1, tl2);
1107- FAIL() << "Expected ValueError";1112+ FAIL() << "Expected npu::tile_fwk::Error";
1108- } catch (const ValueError& e) {1113+ } catch (const npu::tile_fwk::Error& e) {
1109 std::string msg = e.what();1114 std::string msg = e.what();
1110 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("pad") != std::string::npos);1115 EXPECT_TRUE(msg.find("HardwareInfo") != std::string::npos || msg.find("pad") != std::string::npos);
1111 }1116 }
@@ -1125,8 +1130,8 @@ TEST_F(IRStructEqAssertTest, TestAssertTileViewStartOffsetMismatch)
1125 1130 
1126 try {1131 try {
1127 assert_structural_equal(tl1, tl2);1132 assert_structural_equal(tl1, tl2);
1128- FAIL() << "Expected ValueError";1133+ FAIL() << "Expected npu::tile_fwk::Error";
1129- } catch (const ValueError& e) {1134+ } catch (const npu::tile_fwk::Error& e) {
1130 std::string msg = e.what();1135 std::string msg = e.what();
1131 EXPECT_TRUE(msg.find("TileView") != std::string::npos || msg.find("start_offset") != std::string::npos || msg.find("int64_t") != std::string::npos);1136 EXPECT_TRUE(msg.find("TileView") != std::string::npos || msg.find("start_offset") != std::string::npos || msg.find("int64_t") != std::string::npos);
1132 }1137 }
@@ -1140,8 +1145,8 @@ TEST_F(IRStructEqAssertTest, TestAssertCallNameMismatch)
1140 1145 
1141 try {1146 try {
1142 assert_structural_equal(Node(c1), Node(c2));1147 assert_structural_equal(Node(c1), Node(c2));
1143- FAIL() << "Expected ValueError";1148+ FAIL() << "Expected npu::tile_fwk::Error";
1144- } catch (const ValueError& e) {1149+ } catch (const npu::tile_fwk::Error& e) {
1145 std::string msg = e.what();1150 std::string msg = e.what();
1146 EXPECT_TRUE(msg.find("String") != std::string::npos || msg.find("op_a") != std::string::npos);1151 EXPECT_TRUE(msg.find("String") != std::string::npos || msg.find("op_a") != std::string::npos);
1147 }1152 }
@@ -1157,8 +1162,8 @@ TEST_F(IRStructEqAssertTest, TestAssertTupleTypeElementMismatch)
1157 1162 
1158 try {1163 try {
1159 assert_structural_equal(t1, t2);1164 assert_structural_equal(t1, t2);
1160- FAIL() << "Expected ValueError";1165+ FAIL() << "Expected npu::tile_fwk::Error";
1161- } catch (const ValueError& e) {1166+ } catch (const npu::tile_fwk::Error& e) {
1162 std::string msg = e.what();1167 std::string msg = e.what();
1163 EXPECT_TRUE(msg.find("Scalar") != std::string::npos || msg.find("dtype") != std::string::npos);1168 EXPECT_TRUE(msg.find("Scalar") != std::string::npos || msg.find("dtype") != std::string::npos);
1164 }1169 }
@@ -1181,7 +1186,7 @@ TEST_F(IRStructEqAssertTest, TestAssertIterArgIterVarMismatch)
1181 auto for2 = std::make_shared<ForStmt>(1186 auto for2 = std::make_shared<ForStmt>(
1182 i, zero, ten, step, std::vector<IterArgPtr>{ia2}, yield, std::vector<VarPtr>{rv}, Sp());1187 i, zero, ten, step, std::vector<IterArgPtr>{ia2}, yield, std::vector<VarPtr>{rv}, Sp());
1183 1188 
1184- EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), ValueError);1189+ EXPECT_THROW(assert_structural_equal(Node(for1), Node(for2)), npu::tile_fwk::Error);
1185}1190}
1186 1191 
1187TEST_F(IRStructEqAssertTest, TestAssertTileTypeTileViewPresenceMismatch)1192TEST_F(IRStructEqAssertTest, TestAssertTileTypeTileViewPresenceMismatch)
@@ -1192,7 +1197,7 @@ TEST_F(IRStructEqAssertTest, TestAssertTileTypeTileViewPresenceMismatch)
1192 1197 
1193 auto t1 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, tv);1198 auto t1 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, tv);
1194 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32);1199 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32);
1195- EXPECT_THROW(assert_structural_equal(t1, t2), ValueError);1200+ EXPECT_THROW(assert_structural_equal(t1, t2), npu::tile_fwk::Error);
1196}1201}
1197 1202 
1198TEST_F(IRStructEqAssertTest, TestAssertTileTypeHardwareInfoPresenceMismatch)1203TEST_F(IRStructEqAssertTest, TestAssertTileTypeHardwareInfoPresenceMismatch)
@@ -1203,7 +1208,7 @@ TEST_F(IRStructEqAssertTest, TestAssertTileTypeHardwareInfoPresenceMismatch)
1203 auto t1 = std::make_shared<TileType>(1208 auto t1 = std::make_shared<TileType>(
1204 std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, std::nullopt, hw);1209 std::vector<ExprPtr>{d16}, DataType::FP32, std::nullopt, std::nullopt, hw);
1205 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32);1210 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d16}, DataType::FP32);
1206- EXPECT_THROW(assert_structural_equal(t1, t2), ValueError);1211+ EXPECT_THROW(assert_structural_equal(t1, t2), npu::tile_fwk::Error);
1207}1212}
1208 1213 
1209// ============================================================================1214// ============================================================================
@@ -1218,7 +1223,7 @@ TEST_F(IRStructEqAssertTest, TestAssertVarNoAutoMapping_PointerMismatch)
1218 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{x1}, Sp());1223 auto c1 = std::make_shared<Call>("op", std::vector<ExprPtr>{x1}, Sp());
1219 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{x2}, Sp());1224 auto c2 = std::make_shared<Call>("op", std::vector<ExprPtr>{x2}, Sp());
1220 1225 
1221- EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2), false), ValueError);1226+ EXPECT_THROW(assert_structural_equal(Node(c1), Node(c2), false), npu::tile_fwk::Error);
1222}1227}
1223 1228 
1224TEST_F(IRStructEqAssertTest, TestAssertVarDefFieldMappingInconsistent)1229TEST_F(IRStructEqAssertTest, TestAssertVarDefFieldMappingInconsistent)
@@ -1265,7 +1270,7 @@ TEST_F(IRStructEqAssertTest, TestAssertVarDefFieldMappingInconsistent)
1265 std::vector<VarPtr>{rv_rhs1, rv_rhs2}, Sp());1270 std::vector<VarPtr>{rv_rhs1, rv_rhs2}, Sp());
1266 1271 
1267 EXPECT_FALSE(structural_equal(Node(for_lhs), Node(for_rhs), false));1272 EXPECT_FALSE(structural_equal(Node(for_lhs), Node(for_rhs), false));
1268- EXPECT_THROW(assert_structural_equal(Node(for_lhs), Node(for_rhs), false), ValueError);1273+ EXPECT_THROW(assert_structural_equal(Node(for_lhs), Node(for_rhs), false), npu::tile_fwk::Error);
1269}1274}
1270 1275 
1271} // namespace ir1276} // namespace ir
@@ -31,11 +31,11 @@ class IRStructHashTest : public testing::Test {};
31// Var hashing31// Var hashing
32// ============================================================================32// ============================================================================
33 33 
34-TEST_F(IRStructHashTest, TestHashVarDeterministicAndNonZero)34+TEST_F(IRStructHashTest, TestHashVarDeterministic)
35{35{
36 auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());36 auto a = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());
37- EXPECT_EQ(structural_hash(Node(a)), structural_hash(Node(a)));37+ auto b = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());
38- EXPECT_NE(structural_hash(Node(a)), 0u);38+ EXPECT_EQ(structural_hash(Node(a)), structural_hash(Node(b)));
39}39}
40 40 
41TEST_F(IRStructHashTest, TestHashDifferentVarsDifferentHash)41TEST_F(IRStructHashTest, TestHashDifferentVarsDifferentHash)
@@ -117,34 +117,28 @@ TEST_F(IRStructHashTest, TestHashCallWithKwargs)
117TEST_F(IRStructHashTest, TestHashCallKwargsAllTypes)117TEST_F(IRStructHashTest, TestHashCallKwargsAllTypes)
118{118{
119 auto a = std::make_shared<ConstInt>(1, DataType::INT32, Sp());119 auto a = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
120+ auto expect_hash_contract = [&](std::any value, std::any same_value, std::any different_value) {
121+ auto make_call = [&](std::any kwarg_value) {
122+ std::vector<std::pair<std::string, std::any>> kwargs = {{"x", std::move(kwarg_value)}};
123+ return std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kwargs, Scalar(DataType::INT32), Sp());
124+ };
125+ auto lhs = make_call(std::move(value));
126+ auto equal_rhs = make_call(std::move(same_value));
127+ auto different_rhs = make_call(std::move(different_value));
128+ EXPECT_EQ(structural_hash(Node(lhs)), structural_hash(Node(equal_rhs)));
129+ EXPECT_NE(structural_hash(Node(lhs)), structural_hash(Node(different_rhs)));
130+ };
120 131 
121- std::vector<std::pair<std::string, std::any>> kw_int = {{"x", std::any(int(1))}};132+ expect_hash_contract(int(1), int(1), int(2));
122- auto ci = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_int, Scalar(DataType::INT32), Sp());133+ expect_hash_contract(true, true, false);
123- EXPECT_NE(structural_hash(Node(ci)), 0u);134+ expect_hash_contract(std::string("a"), std::string("a"), std::string("b"));
124- 135+ expect_hash_contract(1.5, 1.5, 2.5);
125- std::vector<std::pair<std::string, std::any>> kw_bool = {{"x", std::any(true)}};136+ expect_hash_contract(1.5f, 1.5f, 2.5f);
126- auto cb = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_bool, Scalar(DataType::INT32), Sp());137+ expect_hash_contract(DataType::FP32, DataType::FP32, DataType::FP16);
127- EXPECT_NE(structural_hash(Node(cb)), 0u);138+ expect_hash_contract(std::vector<int>{1, 2, 3}, std::vector<int>{1, 2, 3}, std::vector<int>{1, 2, 4});
128- 139+ expect_hash_contract(
129- std::vector<std::pair<std::string, std::any>> kw_str = {{"x", std::any(std::string("a"))}};140+ std::vector<std::string>{"a", "b"}, std::vector<std::string>{"a", "b"},
130- auto cs = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_str, Scalar(DataType::INT32), Sp());141+ std::vector<std::string>{"a", "c"});
131- EXPECT_NE(structural_hash(Node(cs)), 0u);
132- 
133- std::vector<std::pair<std::string, std::any>> kw_dbl = {{"x", std::any(1.5)}};
134- auto cd = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_dbl, Scalar(DataType::INT32), Sp());
135- EXPECT_NE(structural_hash(Node(cd)), 0u);
136- 
137- std::vector<std::pair<std::string, std::any>> kw_flt = {{"x", std::any(1.5f)}};
138- auto cf = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_flt, Scalar(DataType::INT32), Sp());
139- EXPECT_NE(structural_hash(Node(cf)), 0u);
140- 
141- std::vector<std::pair<std::string, std::any>> kw_dt = {{"x", std::any(DataType::FP32)}};
142- auto cdt = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_dt, Scalar(DataType::INT32), Sp());
143- EXPECT_NE(structural_hash(Node(cdt)), 0u);
144- 
145- std::vector<std::pair<std::string, std::any>> kw_vec = {{"x", std::any(std::vector<int>{1, 2, 3})}};
146- auto cv = std::make_shared<Call>("op", std::vector<ExprPtr>{a}, kw_vec, Scalar(DataType::INT32), Sp());
147- EXPECT_NE(structural_hash(Node(cv)), 0u);
148}142}
149 143 
150TEST_F(IRStructHashTest, TestHashMakeTuple)144TEST_F(IRStructHashTest, TestHashMakeTuple)
@@ -354,7 +348,6 @@ TEST_F(IRStructHashTest, TestHashScalarTypeDeterministicAndDifferent)
354 auto t1 = std::make_shared<ScalarType>(DataType::INT32);348 auto t1 = std::make_shared<ScalarType>(DataType::INT32);
355 auto t2 = std::make_shared<ScalarType>(DataType::INT32);349 auto t2 = std::make_shared<ScalarType>(DataType::INT32);
356 auto t3 = std::make_shared<ScalarType>(DataType::FP32);350 auto t3 = std::make_shared<ScalarType>(DataType::FP32);
357- EXPECT_NE(structural_hash(t1), 0u);
358 EXPECT_EQ(structural_hash(t1), structural_hash(t2));351 EXPECT_EQ(structural_hash(t1), structural_hash(t2));
359 EXPECT_NE(structural_hash(t1), structural_hash(t3));352 EXPECT_NE(structural_hash(t1), structural_hash(t3));
360}353}
@@ -363,8 +356,6 @@ TEST_F(IRStructHashTest, TestHashTensorTypeWithVarShape)
363{356{
364 auto d = std::make_shared<Var>("N", Scalar(DataType::INT64), Sp());357 auto d = std::make_shared<Var>("N", Scalar(DataType::INT64), Sp());
365 auto t = std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32);358 auto t = std::make_shared<TensorType>(std::vector<ExprPtr>{d}, DataType::FP32);
366- EXPECT_NE(structural_hash(t), 0u);
367- 
368 auto d2 = std::make_shared<Var>("N", Scalar(DataType::INT64), Sp());359 auto d2 = std::make_shared<Var>("N", Scalar(DataType::INT64), Sp());
369 auto t2 = std::make_shared<TensorType>(std::vector<ExprPtr>{d2}, DataType::FP32);360 auto t2 = std::make_shared<TensorType>(std::vector<ExprPtr>{d2}, DataType::FP32);
370 EXPECT_EQ(structural_hash(t, false), structural_hash(t2, false));361 EXPECT_EQ(structural_hash(t, false), structural_hash(t2, false));
@@ -375,7 +366,6 @@ TEST_F(IRStructHashTest, TestHashTileType)
375 auto d = std::make_shared<Var>("T", Scalar(DataType::INT64), Sp());366 auto d = std::make_shared<Var>("T", Scalar(DataType::INT64), Sp());
376 auto t1 = std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32);367 auto t1 = std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP32);
377 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP16);368 auto t2 = std::make_shared<TileType>(std::vector<ExprPtr>{d}, DataType::FP16);
378- EXPECT_NE(structural_hash(t1), 0u);
379 EXPECT_NE(structural_hash(t1), structural_hash(t2));369 EXPECT_NE(structural_hash(t1), structural_hash(t2));
380}370}
381 371 
@@ -418,15 +408,19 @@ TEST_F(IRStructHashTest, TestHashTupleType)
418 auto t1 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::INT32)});408 auto t1 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::INT32)});
419 auto t2 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::INT32)});409 auto t2 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::INT32)});
420 auto t3 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::FP32)});410 auto t3 = std::make_shared<TupleType>(std::vector<TypePtr>{Scalar(DataType::FP32)});
421- EXPECT_NE(structural_hash(t1), 0u);
422 EXPECT_EQ(structural_hash(t1), structural_hash(t2));411 EXPECT_EQ(structural_hash(t1), structural_hash(t2));
423 EXPECT_NE(structural_hash(t1), structural_hash(t3));412 EXPECT_NE(structural_hash(t1), structural_hash(t3));
424}413}
425 414 
426TEST_F(IRStructHashTest, TestHashMemRefAndUnknownType)415TEST_F(IRStructHashTest, TestHashMemRefAndUnknownType)
427{416{
428- EXPECT_NE(structural_hash(GetMemRefType()), 0u);417+ auto memref1 = GetMemRefType();
429- EXPECT_NE(structural_hash(std::make_shared<UnknownType>()), 0u);418+ auto memref2 = GetMemRefType();
419+ auto unknown1 = std::make_shared<UnknownType>();
420+ auto unknown2 = std::make_shared<UnknownType>();
421+ EXPECT_EQ(structural_hash(memref1), structural_hash(memref2));
422+ EXPECT_EQ(structural_hash(unknown1), structural_hash(unknown2));
423+ EXPECT_NE(structural_hash(memref1), structural_hash(unknown1));
430}424}
431 425 
432// ============================================================================426// ============================================================================
@@ -380,11 +380,11 @@ void BindTypeClass(py::module_& ir)
380 "__str__", [](const IRNodePtr& self) { return PythonPrint(self, "ir"); },380 "__str__", [](const IRNodePtr& self) { return PythonPrint(self, "ir"); },
381 "IR string representation")381 "IR string representation")
382 .def(382 .def(
383- "as_python", [](const IRNodePtr& self, const std::string& prefix) { return PythonDslPrint(self, prefix); },383+ "as_python", [](const IRNodePtr& self, const std::string& prefix) { return PythonPrint(self, prefix); },
384- py::arg("prefix") = "pl",384+ py::arg("prefix") = "ir",
385 "Convert to Python-style string representation.\n\n"385 "Convert to Python-style string representation.\n\n"
386 "Args:\n"386 "Args:\n"
387- " prefix: Module prefix (default 'pl' for 'import pypto.language as pl')");387+ " prefix: Module prefix (default 'ir' for 'import pypto_pro.ir as ir')");
388 388 
389 // Expr - abstract base, const shared_ptr389 // Expr - abstract base, const shared_ptr
390 auto expr_class = py::class_<Expr, IRNode, std::shared_ptr<Expr>>(390 auto expr_class = py::class_<Expr, IRNode, std::shared_ptr<Expr>>(
@@ -640,6 +640,10 @@ void BindExpr(py::module_& ir)
640 .def_readonly("memory_space", &MemRef::memorySpace_, "Memory space (DDR, Vec, Mat, Left, Right, Scaling, Acc)")640 .def_readonly("memory_space", &MemRef::memorySpace_, "Memory space (DDR, Vec, Mat, Left, Right, Scaling, Acc)")
641 .def_readonly("addr", &MemRef::addr_, "Starting address expression")641 .def_readonly("addr", &MemRef::addr_, "Starting address expression")
642 .def_readonly("size", &MemRef::size_, "Size in bytes (64-bit unsigned)")642 .def_readonly("size", &MemRef::size_, "Size in bytes (64-bit unsigned)")
643+ .def_readwrite(
644+ "memory_space_", &MemRef::memorySpace_, "Memory space (DDR, Vec, Mat, Left, Right, Scaling, Acc)")
645+ .def_readwrite("addr_", &MemRef::addr_, "Starting address expression")
646+ .def_readwrite("size_", &MemRef::size_, "Size in bytes (64-bit unsigned)")
643 .def_static(647 .def_static(
644 "same_allocation", &MemRef::SameAllocation, py::arg("a"), py::arg("b"),648 "same_allocation", &MemRef::SameAllocation, py::arg("a"), py::arg("b"),
645 "Check if two MemRefs share the same allocation (same base pointer)")649 "Check if two MemRefs share the same allocation (same base pointer)")
@@ -881,7 +885,8 @@ void BindExpr(py::module_& ir)
881 static_cast<void (*)(const IRNodePtr&, const IRNodePtr&, bool)>(&assert_structural_equal), py::arg("lhs"),885 static_cast<void (*)(const IRNodePtr&, const IRNodePtr&, bool)>(&assert_structural_equal), py::arg("lhs"),
882 py::arg("rhs"), py::arg("enable_auto_mapping") = false,886 py::arg("rhs"), py::arg("enable_auto_mapping") = false,
883 "Assert two IR nodes are structurally equal. "887 "Assert two IR nodes are structurally equal. "
884- "Raises ValueError with detailed error message showing the first mismatch location if they differ. "888+ "Raises RuntimeError with FE error code and detailed error message showing the first mismatch location "
889+ "if they differ. "
885 "Ignores source location (Span). "890 "Ignores source location (Span). "
886 "If enable_auto_mapping=True, automatically map variables (e.g., x+1 equals y+1). "891 "If enable_auto_mapping=True, automatically map variables (e.g., x+1 equals y+1). "
887 "If enable_auto_mapping=False (default), variable objects must be exactly the same (not just same "892 "If enable_auto_mapping=False (default), variable objects must be exactly the same (not just same "
@@ -891,7 +896,8 @@ void BindExpr(py::module_& ir)
891 static_cast<void (*)(const TypePtr&, const TypePtr&, bool)>(&assert_structural_equal), py::arg("lhs"),896 static_cast<void (*)(const TypePtr&, const TypePtr&, bool)>(&assert_structural_equal), py::arg("lhs"),
892 py::arg("rhs"), py::arg("enable_auto_mapping") = false,897 py::arg("rhs"), py::arg("enable_auto_mapping") = false,
893 "Assert two types are structurally equal. "898 "Assert two types are structurally equal. "
894- "Raises ValueError with detailed error message showing the first mismatch location if they differ. "899+ "Raises RuntimeError with FE error code and detailed error message showing the first mismatch location "
900+ "if they differ. "
895 "Ignores source location (Span). "901 "Ignores source location (Span). "
896 "If enable_auto_mapping=True, automatically map variables (e.g., x+1 equals y+1). "902 "If enable_auto_mapping=True, automatically map variables (e.g., x+1 equals y+1). "
897 "If enable_auto_mapping=False (default), variable objects must be exactly the same (not just same "903 "If enable_auto_mapping=False (default), variable objects must be exactly the same (not just same "
@@ -968,6 +974,7 @@ void BindStmt(py::module_& ir)
968 py::enum_<SectionKind>(ir, "SectionKind", "Section kind classification")974 py::enum_<SectionKind>(ir, "SectionKind", "Section kind classification")
969 .value("Vector", SectionKind::Vector, "Vector section for vector operations")975 .value("Vector", SectionKind::Vector, "Vector section for vector operations")
970 .value("Cube", SectionKind::Cube, "Cube section for cube operations")976 .value("Cube", SectionKind::Cube, "Cube section for cube operations")
977+ .value("VF", SectionKind::VF, "VF section for A5 VF API code (__VEC_SCOPE__)")
971 .export_values();978 .export_values();
972 979 
973 // SectionStmt - const shared_ptr980 // SectionStmt - const shared_ptr
@@ -1080,16 +1087,55 @@ void BindProgram(py::module_& ir)
1080 py::arg("type") = FunctionType::OPAQUE, "Create a function definition");1087 py::arg("type") = FunctionType::OPAQUE, "Create a function definition");
1081 BindFields<Function>(function_class);1088 BindFields<Function>(function_class);
1082 1089 
1090+ // IRDebugInfo - compilation-session side table for tuple/struct field names.
1091+ auto debug_info_class = py::class_<IRDebugInfo, std::shared_ptr<IRDebugInfo>>(
1092+ ir, "IRDebugInfo",
1093+ "Side table mapping a tuple type to its ordered field-name list. "
1094+ "Populated by the parser, carried on Program, read by codegen.");
1095+ debug_info_class.def(py::init<>());
1096+ debug_info_class.def(
1097+ "register_tuple_fields", &IRDebugInfo::RegisterTupleFields, py::arg("type"), py::arg("fields"),
1098+ "Record the ordered field-name list for a named tuple / struct type.");
1099+ debug_info_class.def(
1100+ "get_tuple_fields",
1101+ [](const IRDebugInfo& self, const TupleTypePtr& type) -> py::object {
1102+ const auto* fields = self.GetTupleFields(type.get());
1103+ if (fields == nullptr) {
1104+ return py::none();
1105+ }
1106+ return py::cast(*fields);
1107+ },
1108+ py::arg("type"), "Look up field names by type, returns None if not registered.");
1109+ debug_info_class.def(
1110+ "register_tuple_name", &IRDebugInfo::RegisterTupleName, py::arg("type"), py::arg("name"),
1111+ "Record the C++ struct type name for a named tuple / struct type.");
1112+ debug_info_class.def(
1113+ "get_tuple_name",
1114+ [](const IRDebugInfo& self, const TupleTypePtr& type) -> py::object {
1115+ const auto* name = self.GetTupleName(type.get());
1116+ if (name == nullptr) {
1117+ return py::none();
1118+ }
1119+ return py::cast(*name);
1120+ },
1121+ py::arg("type"), "Look up struct type name by type, returns None if not registered.");
1122+ 
1083 // Program - const shared_ptr1123 // Program - const shared_ptr
1084 auto program_class = py::class_<Program, IRNode, std::shared_ptr<Program>>(1124 auto program_class = py::class_<Program, IRNode, std::shared_ptr<Program>>(
1085 ir, "Program",1125 ir, "Program",
1086 "Program definition with functions mapped by name. "1126 "Program definition with functions mapped by name. "
1087 "Functions are automatically sorted by name for deterministic ordering.");1127 "Functions are automatically sorted by name for deterministic ordering.");
1088 program_class.def(1128 program_class.def(
1089- py::init<const std::vector<FunctionPtr>&, const std::string&, const Span&>(), py::arg("functions"),1129+ py::init([](const std::vector<FunctionPtr>& functions, const std::string& name, const Span& span,
1090- py::arg("name"), py::arg("span"),1130+ IRDebugInfoPtr debug_info) {
1131+ return std::make_shared<Program>(functions, name, span, std::move(debug_info));
1132+ }),
1133+ py::arg("functions"), py::arg("name"), py::arg("span"), py::arg("debug_info") = nullptr,
1091 "Create a program from a list of functions. "1134 "Create a program from a list of functions. "
1092 "Functions are keyed by their names automatically.");1135 "Functions are keyed by their names automatically.");
1136+ program_class.def_property_readonly(
1137+ "debug_info", [](const ProgramPtr& self) { return self->debugInfo_; },
1138+ "Tuple/struct field-name side table; None if the Program was built without one.");
1093 program_class.def(1139 program_class.def(
1094 "get_function", &Program::GetFunction, py::arg("name"), "Get a function by name, returns None if not found");1140 "get_function", &Program::GetFunction, py::arg("name"), "Get a function by name, returns None if not found");
1095 program_class.def(1141 program_class.def(
@@ -1111,22 +1157,22 @@ void BindProgram(py::module_& ir)
1111 1157 
1112 // Python-style printer function - unified API for IRNode1158 // Python-style printer function - unified API for IRNode
1113 ir.def(1159 ir.def(
1114- "python_print", [](const IRNodePtr& node, const std::string& prefix) { return PythonDslPrint(node, prefix); },1160+ "python_print", [](const IRNodePtr& node, const std::string& prefix) { return PythonPrint(node, prefix); },
1115- py::arg("node"), py::arg("prefix") = "pl",1161+ py::arg("node"), py::arg("prefix") = "ir",
1116 "Print IR node (Expr, Stmt, Function, or Program) in Python IR syntax.\n\n"1162 "Print IR node (Expr, Stmt, Function, or Program) in Python IR syntax.\n\n"
1117 "Args:\n"1163 "Args:\n"
1118 " node: IR node to print\n"1164 " node: IR node to print\n"
1119- " prefix: Module prefix (default 'pl' for 'import pypto.language as pl')");1165+ " prefix: Module prefix (default 'ir' for 'import pypto_pro.ir as ir')");
1120 1166 
1121 // Python-style printer function for Type objects1167 // Python-style printer function for Type objects
1122 ir.def(1168 ir.def(
1123 "python_print_type",1169 "python_print_type",
1124- [](const TypePtr& type, const std::string& prefix) { return PythonDslPrint(type, prefix); }, py::arg("type"),1170+ [](const TypePtr& type, const std::string& prefix) { return PythonPrint(type, prefix); }, py::arg("type"),
1125- py::arg("prefix") = "pl",1171+ py::arg("prefix") = "ir",
1126 "Print Type object in Python IR syntax.\n\n"1172 "Print Type object in Python IR syntax.\n\n"
1127 "Args:\n"1173 "Args:\n"
1128 " type: Type to print\n"1174 " type: Type to print\n"
1129- " prefix: Module prefix (default 'pl' for 'import pypto.language as pl')");1175+ " prefix: Module prefix (default 'ir' for 'import pypto_pro.ir as ir')");
1130}1176}
1131 1177 
1132void BindHelpers(py::module_& ir)1178void BindHelpers(py::module_& ir)
@@ -17,6 +17,7 @@
17 17 
18#include "core/error.h"18#include "core/error.h"
19#include "bindings/ir/bindings.h"19#include "bindings/ir/bindings.h"
20+#include "tilefwk/error.h"
20 21 
21namespace py = pybind11;22namespace py = pybind11;
22 23 
@@ -70,6 +71,8 @@ void BindError(py::module_& m)
70 PyErr_SetString(exc_internal_error.ptr(), e.GetFullMessage().c_str());71 PyErr_SetString(exc_internal_error.ptr(), e.GetFullMessage().c_str());
71 } catch (const ir::Error& e) {72 } catch (const ir::Error& e) {
72 PyErr_SetString(PyExc_Exception, e.GetFullMessage().c_str());73 PyErr_SetString(PyExc_Exception, e.GetFullMessage().c_str());
74+ } catch (const npu::tile_fwk::Error& e) {
75+ PyErr_SetString(PyExc_RuntimeError, e.what());
73 }76 }
74 });77 });
75}78}
@@ -29,5 +29,9 @@ void BindPlatform(py::module_& m)
29 .def("SetNPUArch", [](const std::string& value) {29 .def("SetNPUArch", [](const std::string& value) {
30 Platform::Instance().GetSoc().SetNPUArch(value);30 Platform::Instance().GetSoc().SetNPUArch(value);
31 });31 });
32+ 
33+ m.def("GetAICoreNum", []() -> size_t {
34+ return Platform::Instance().GetSoc().GetAICoreNum();
35+ });
32}36}
33} // namespace pypto37} // namespace pypto
@@ -36,6 +36,22 @@ def test_error_types():
36 pypto.raise_error("UnknownType", "should fail")36 pypto.raise_error("UnknownType", "should fail")
37 37 
38 38 
39+def test_assert_structural_equal_raises_runtime_error_with_fe_code():
40+ from pypto import pypto_impl
41+ 
42+ span = ir.Span("test", 1, 1)
43+ lhs = ir.ConstInt(1, ir.INT32, span)
44+ rhs = ir.ConstInt(2, ir.INT32, span)
45+ 
46+ with pytest.raises(RuntimeError) as exc_info:
47+ pypto_impl.ir.assert_structural_equal(lhs, rhs)
48+ 
49+ msg = str(exc_info.value)
50+ assert "ASSERT FAILED" in msg
51+ assert "INVALID_VAL" in msg
52+ assert "Structural equality assertion failed" in msg
53+ 
54+ 
39def test_dtypes():55def test_dtypes():
40 dtypes = [56 dtypes = [
41 # bits, is_signed, is_unsigned, is_float, name, c_type57 # bits, is_signed, is_unsigned, is_float, name, c_type
@@ -84,6 +100,9 @@ def test_span():
84 assert span.end_column == -1100 assert span.end_column == -1
85 assert not span.is_unknown()101 assert not span.is_unknown()
86 102 
103+ span = ir.Span.unknown()
104+ assert span.is_unknown()
105+ 
87 106 
88def test_logging(capfd):107def test_logging(capfd):
89 pypto.set_log_level(pypto.LogLevel.INFO)108 pypto.set_log_level(pypto.LogLevel.INFO)
@@ -172,6 +191,22 @@ def test_basic_types():
172 lt = ir.LogicalTensorType()191 lt = ir.LogicalTensorType()
173 assert str(lt) == "ir.Tensor"192 assert str(lt) == "ir.Tensor"
174 193 
194+ # Struct debug info
195+ from pypto import pypto_impl
196+ span = ir.Span("test", 1, 1)
197+ struct_type = ir.TupleType([ir.ScalarType(ir.INT64), ir.ScalarType(ir.INT32)])
198+ debug_info = pypto_impl.ir.IRDebugInfo()
199+ debug_info.register_tuple_fields(struct_type, ["cursor", "limit"])
200+ debug_info.register_tuple_name(struct_type, "BufferState")
201+ assert debug_info.get_tuple_fields(struct_type) == ["cursor", "limit"]
202+ assert debug_info.get_tuple_name(struct_type) == "BufferState"
203+ assert debug_info.get_tuple_fields(ir.TupleType([ir.ScalarType(ir.INT32)])) is None
204+ 
205+ prog = ir.Program([], "test_prog", span, debug_info)
206+ assert prog.debug_info.get_tuple_fields(struct_type) == ["cursor", "limit"]
207+ assert prog.debug_info.get_tuple_name(struct_type) == "BufferState"
208+ assert ir.Program([], "empty_prog", span).debug_info is None
209+ 
175 210 
176def test_basic_expr():211def test_basic_expr():
177 span = ir.Span("test", 1, 1)212 span = ir.Span("test", 1, 1)
@@ -248,6 +283,9 @@ def test_basic_expr():
248 not_expr = ir.Not(cb, ir.BOOL, span)283 not_expr = ir.Not(cb, ir.BOOL, span)
249 assert str(not_expr) == "not True"284 assert str(not_expr) == "not True"
250 285 
286+ bit_not = ir.BitNot(a, ir.INT32, span)
287+ assert str(bit_not) == "~1"
288+ 
251 abs_expr = ir.Abs(a, ir.INT32, span)289 abs_expr = ir.Abs(a, ir.INT32, span)
252 assert str(abs_expr) == "ir.abs(1)"290 assert str(abs_expr) == "ir.abs(1)"
253 291 
@@ -259,6 +297,8 @@ def test_basic_expr():
259 assert str(mt) == "[1, 2]"297 assert str(mt) == "[1, 2]"
260 tgi = ir.TupleGetItem(mt, 0, span)298 tgi = ir.TupleGetItem(mt, 0, span)
261 assert str(tgi) == "[1, 2][0]"299 assert str(tgi) == "[1, 2][0]"
300+ get_item = ir.GetItemExpr(mt, ir.ConstInt(1, ir.INDEX, span), span)
301+ assert str(get_item) == "[1, 2][1]"
262 302 
263 # Call with Op303 # Call with Op
264 call = ir.Call("my_op", [a, b], span)304 call = ir.Call("my_op", [a, b], span)
@@ -271,6 +311,8 @@ def test_basic_expr():
271 311 
272 312 
273def test_basic_stmt():313def test_basic_stmt():
314+ from pypto import pypto_impl
315+ 
274 span = ir.Span("test", 1, 1)316 span = ir.Span("test", 1, 1)
275 st = ir.ScalarType(ir.INT32)317 st = ir.ScalarType(ir.INT32)
276 318 
@@ -330,6 +372,18 @@ def test_basic_stmt():
330 " x: ir.Scalar[ir.INT32] = 42"372 " x: ir.Scalar[ir.INT32] = 42"
331 ])373 ])
332 374 
375+ # SectionStmt
376+ for section_kind, section_name in [
377+ (pypto_impl.ir.SectionKind.Vector, "section_vector"),
378+ (pypto_impl.ir.SectionKind.Cube, "section_cube"),
379+ (pypto_impl.ir.SectionKind.VF, "section_vf"),
380+ ]:
381+ section = pypto_impl.ir.SectionStmt(section_kind, assign_x, span)
382+ assert str(section) == "\n".join([
383+ f"with ir.{section_name}():",
384+ " x: ir.Scalar[ir.INT32] = 42",
385+ ])
386+ 
333 # YieldStmt and ReturnStmt387 # YieldStmt and ReturnStmt
334 yield_stmt = ir.YieldStmt([val42], span)388 yield_stmt = ir.YieldStmt([val42], span)
335 assert str(yield_stmt) == "ir.yield_(42)"389 assert str(yield_stmt) == "ir.yield_(42)"
@@ -344,14 +398,25 @@ def test_basic_stmt():
344 # BreakStmt and ContinueStmt398 # BreakStmt and ContinueStmt
345 break_stmt = ir.BreakStmt(span)399 break_stmt = ir.BreakStmt(span)
346 assert str(break_stmt) == "break"400 assert str(break_stmt) == "break"
401+ break_with_value = ir.BreakStmt([val1], span)
402+ assert str(break_with_value) == "break 1"
347 continue_stmt = ir.ContinueStmt(span)403 continue_stmt = ir.ContinueStmt(span)
348 assert str(continue_stmt) == "continue"404 assert str(continue_stmt) == "continue"
405+ continue_with_value = ir.ContinueStmt([val1], span)
406+ assert str(continue_with_value) == "continue 1"
349 407 
350 # EvalStmt408 # EvalStmt
351 call = ir.Call("some_op", [val42], span)409 call = ir.Call("some_op", [val42], span)
352 eval_stmt = ir.EvalStmt(call, span)410 eval_stmt = ir.EvalStmt(call, span)
353 assert str(eval_stmt) == "ir.eval(ir.call @some_op(42))"411 assert str(eval_stmt) == "ir.eval(ir.call @some_op(42))"
354 412 
413+ # ScalarOpStmt and TensorOpStmt
414+ token = ir.Var("tok", st, span)
415+ scalar_op = pypto_impl.ir.ScalarOpStmt(x, token, "add", [val1], span)
416+ assert str(scalar_op) == "x, tok = add(1)"
417+ tensor_op = ir.TensorOpStmt([x], token, "matmul", [val1], [], {}, span)
418+ assert str(tensor_op) == "x, tok = matmul(1)"
419+ 
355 # Function420 # Function
356 func = ir.Function("test_func", [x], [st], assign_x, span)421 func = ir.Function("test_func", [x], [st], assign_x, span)
357 assert str(func) == "\n".join([422 assert str(func) == "\n".join([
@@ -359,6 +424,12 @@ def test_basic_stmt():
359 "def test_func(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:",424 "def test_func(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:",
360 " x: ir.Scalar[ir.INT32] = 42"425 " x: ir.Scalar[ir.INT32] = 42"
361 ])426 ])
427+ helper_func = ir.Function("helper", [x], [st], ir.YieldStmt([x], span), span, ir.FunctionType.Helper)
428+ assert str(helper_func) == "\n".join([
429+ "@ir.function(type=ir.FunctionType.Helper)",
430+ "def helper(x: ir.Scalar[ir.INT32]) -> ir.Scalar[ir.INT32]:",
431+ " return x",
432+ ])
362 433 
363 # Program434 # Program
364 func2 = ir.Function("test_func2", [x], [st], assign_x, span)435 func2 = ir.Function("test_func2", [x], [st], assign_x, span)
@@ -174,6 +174,78 @@ def test_builder_emit():
174 assert isinstance(func.body[0], ir.EvalStmt)174 assert isinstance(func.body[0], ir.EvalStmt)
175 175 
176 176 
177+def test_builder_emit_struct_ops():
178+ from pypto import pypto_impl
179+ 
180+ b = ir.IRBuilder()
181+ sp = _span()
182+ 
183+ cursor = ir.Var("cursor", ir.ScalarType(ir.INT64), sp)
184+ limit = ir.Var("limit", ir.ScalarType(ir.INT32), sp)
185+ struct_create = pypto_impl.ir.create_op_call(
186+ "struct.create",
187+ [cursor, limit],
188+ {"name": "BufferState", "fields": ["cursor", "limit"]},
189+ sp,
190+ )
191+ state = ir.Var("state", struct_create.type, sp)
192+ struct_set = pypto_impl.ir.create_op_call("struct.set", [state, cursor], {"field": "cursor"}, sp)
193+ 
194+ b.begin_function("f", sp)
195+ for call in [struct_create, struct_set]:
196+ b.emit(ir.EvalStmt(call, sp))
197+ func = b.end_function(sp)
198+ 
199+ assert [func.body[i].expr.name for i in range(2)] == ["struct.create", "struct.set"]
200+ assert isinstance(func.body[0].expr.type, ir.TupleType)
201+ assert isinstance(func.body[1].expr.type, ir.TupleType)
202+ 
203+ 
204+def test_builder_emit_block_ops():
205+ from pypto import pypto_impl
206+ 
207+ b = ir.IRBuilder()
208+ sp = _span()
209+ 
210+ src = ir.Var("src", pypto_impl.ir.TileType([16, 32], ir.FP16), sp)
211+ dst = ir.Var("dst", pypto_impl.ir.TileType([16, 32], ir.FP32), sp)
212+ out = ir.Var("out", ir.TensorType([16, 32], ir.FP16), sp)
213+ offsets = ir.MakeTuple([ir.ConstInt(0, ir.INT64, sp), ir.ConstInt(0, ir.INT64, sp)], sp)
214+ block_store = pypto_impl.ir.create_op_call("block.store", [src, offsets, out], {"phase": "final"}, sp)
215+ block_move = pypto_impl.ir.create_op_call("block.move", [src, dst, offsets], sp)
216+ 
217+ b.begin_function("f", sp)
218+ for call in [block_store, block_move]:
219+ b.emit(ir.EvalStmt(call, sp))
220+ func = b.end_function(sp)
221+ 
222+ assert [func.body[i].expr.name for i in range(2)] == ["block.store", "block.move"]
223+ assert isinstance(func.body[0].expr.type, ir.TensorType)
224+ assert func.body[0].expr.kwargs["phase"] == "final"
225+ assert isinstance(func.body[1].expr.type, pypto_impl.ir.TileType)
226+ assert func.body[1].expr.type.dtype == ir.FP32
227+ 
228+ 
229+def test_builder_emit_vf_op():
230+ from pypto import pypto_impl
231+ 
232+ b = ir.IRBuilder()
233+ sp = _span()
234+ 
235+ dst_reg = ir.Var("dst", ir.ScalarType(ir.FP32), sp)
236+ src0 = ir.Var("src0", ir.ScalarType(ir.FP16), sp)
237+ src1 = ir.Var("src1", ir.ScalarType(ir.FP16), sp)
238+ mask = ir.Var("mask", ir.ScalarType(ir.UINT16), sp)
239+ vf_add = pypto_impl.ir.create_op_call("vf.Add", [dst_reg, src0, src1, mask], sp)
240+ 
241+ b.begin_function("f", sp)
242+ b.emit(ir.EvalStmt(vf_add, sp))
243+ func = b.end_function(sp)
244+ 
245+ assert func.body[0].expr.name == "vf.Add"
246+ assert func.body[0].expr.type.dtype == ir.FP32
247+ 
248+ 
177# ---------- For loop building ----------249# ---------- For loop building ----------
178 250 
179 251 
@@ -411,6 +483,25 @@ def test_builder_if_with_return_vars():
411 b.end_function(sp)483 b.end_function(sp)
412 484 
413 485 
486+def test_builder_if_with_runtime_op():
487+ from pypto import pypto_impl
488+ 
489+ b = ir.IRBuilder()
490+ sp = _span()
491+ 
492+ b.begin_function("f", sp)
493+ b.begin_if(ir.ConstBool(True, sp), sp)
494+ sync = pypto_impl.ir.create_op_call("system.sync_all", [], {"mode": "hard", "core_type": "mix"}, sp)
495+ b.emit(ir.EvalStmt(sync, sp))
496+ if_stmt = b.end_if(sp)
497+ func = b.end_function(sp)
498+ 
499+ assert isinstance(func.body[0], ir.IfStmt)
500+ assert isinstance(if_stmt.then_body[0], ir.EvalStmt)
501+ assert if_stmt.then_body[0].expr.name == "system.sync_all"
502+ assert isinstance(if_stmt.then_body[0].expr.type, ir.UnknownType)
503+ 
504+ 
414def test_builder_if_else_str():505def test_builder_if_else_str():
415 """Builder-constructed if-else should match manually constructed one."""506 """Builder-constructed if-else should match manually constructed one."""
416 b = ir.IRBuilder()507 b = ir.IRBuilder()
@@ -437,6 +528,31 @@ def test_builder_if_else_str():
437 assert str(built_if) == str(manual_if)528 assert str(built_if) == str(manual_if)
438 529 
439 530 
531+# ---------- Section building ----------
532+ 
533+ 
534+def test_builder_section():
535+ from pypto import pypto_impl
536+ 
537+ b = ir.IRBuilder()
538+ sp = _span()
539+ st = ir.ScalarType(ir.INT32)
540+ 
541+ b.begin_function("f", sp)
542+ x = b.func_arg("x", st, sp)
543+ b.begin_section(pypto_impl.ir.SectionKind.Vector, sp)
544+ b.assign(x, ir.ConstInt(1, ir.INT32, sp), sp)
545+ section = b.end_section(sp)
546+ func = b.end_function(sp)
547+ 
548+ assert isinstance(section, pypto_impl.ir.SectionStmt)
549+ assert str(func.body[0]) == str(section)
550+ assert str(section) == "\n".join([
551+ "with ir.section_vector():",
552+ " x: ir.Scalar[ir.INT32] = 1",
553+ ])
554+ 
555+ 
440# ---------- Program building ----------556# ---------- Program building ----------
441 557 
442 558