Merged
fix(pypto-pro): lower loop target and classify tuple #6321
poorwillAdd on Sep 15
fix(pypto-pro): lower loop target and classify tuple #6321
Merged
Merged fromwangbing110/pypto9.2.0intocann/pypto9.2.0
Total: 41 files changed+884-270
| @@ -553,6 +553,7 @@ | |||
| 553 | - [pypto_pro.language.simt.atomic_xor](pro_api/SIMT-API/atomic/atomic_xor.md) | 553 | - [pypto_pro.language.simt.atomic_xor](pro_api/SIMT-API/atomic/atomic_xor.md) |
| 554 | - [Utils API](pro_api/Utils-API/index.md) | 554 | - [Utils API](pro_api/Utils-API/index.md) |
| 555 | - [Python语法糖](pro_api/Utils-API/python_syntax_sugar/index.md) | 555 | - [Python语法糖](pro_api/Utils-API/python_syntax_sugar/index.md) |
| 556 | + - [pypto_pro.language.astype](pro_api/Utils-API/python_syntax_sugar/astype.md) | ||
| 556 | - [pypto_pro.language.const](pro_api/Utils-API/python_syntax_sugar/const.md) | 557 | - [pypto_pro.language.const](pro_api/Utils-API/python_syntax_sugar/const.md) |
| 557 | - [pypto_pro.language.max](pro_api/Utils-API/python_syntax_sugar/max.md) | 558 | - [pypto_pro.language.max](pro_api/Utils-API/python_syntax_sugar/max.md) |
| 558 | - [pypto_pro.language.min](pro_api/Utils-API/python_syntax_sugar/min.md) | 559 | - [pypto_pro.language.min](pro_api/Utils-API/python_syntax_sugar/min.md) |
| @@ -0,0 +1,54 @@ | |||
| 1 | +# pypto_pro.language.astype | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | +- Ascend 950PR/Ascend 950DT:支持 | ||
| 7 | +<!-- end id1 --> | ||
| 8 | +<!-- npu="A3" id2 --> | ||
| 9 | +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持 | ||
| 10 | +<!-- end id2 --> | ||
| 11 | +<!-- npu="910b" id3 --> | ||
| 12 | +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持 | ||
| 13 | +<!-- end id3 --> | ||
| 14 | + | ||
| 15 | +## 功能说明 | ||
| 16 | + | ||
| 17 | +将标量表达式的结果转换为指定数据类型。 | ||
| 18 | + | ||
| 19 | +## 函数原型 | ||
| 20 | + | ||
| 21 | +```python | ||
| 22 | +result = pypto_pro.language.astype(x, dtype) | ||
| 23 | +``` | ||
| 24 | + | ||
| 25 | +## 参数说明 | ||
| 26 | + | ||
| 27 | +| 参数 | 输入/输出 | 说明 | | ||
| 28 | +|---|---|---| | ||
| 29 | +| x | 输入 | 源标量表达式,Scalar类型,按位置传递。 | | ||
| 30 | +| dtype | 输入 | 目标数据类型,DataType类型,按位置传递。 | | ||
| 31 | + | ||
| 32 | +## 约束说明 | ||
| 33 | + | ||
| 34 | +无。 | ||
| 35 | + | ||
| 36 | +## 返回值说明 | ||
| 37 | + | ||
| 38 | +返回数据类型为dtype的Scalar。 | ||
| 39 | + | ||
| 40 | +## 调用示例 | ||
| 41 | + | ||
| 42 | +```python | ||
| 43 | +import pypto_pro.language as pl | ||
| 44 | + | ||
| 45 | +# 将INT32标量转换为INT64 | ||
| 46 | +source = pl.const(1, pl.DT_INT32) | ||
| 47 | +converted = pl.astype(source, pl.DT_INT64) | ||
| 48 | + | ||
| 49 | +# 显式统一控制流两个分支的标量类型 | ||
| 50 | +if flag: | ||
| 51 | + value = pl.astype(lhs, pl.DT_INT64) | ||
| 52 | +else: | ||
| 53 | + value = pl.astype(rhs, pl.DT_INT64) | ||
| 54 | +``` | ||
| @@ -4,7 +4,8 @@ | |||
| 4 | :maxdepth: 1 | 4 | :maxdepth: 1 |
| 5 | :titlesonly: | 5 | :titlesonly: |
| 6 | 6 | ||
| 7 | -const | 7 | +const |
| 8 | -max | 8 | +astype |
| 9 | -min | 9 | +max |
| 10 | -``` | 10 | +min |
| 11 | +``` | ||
| @@ -10,6 +10,7 @@ | |||
| 10 | 10 | ||
| 11 | #pragma once | 11 | #pragma once |
| 12 | #include <memory> | 12 | #include <memory> |
| 13 | +#include <optional> | ||
| 13 | #include <string> | 14 | #include <string> |
| 14 | #include <unordered_map> | 15 | #include <unordered_map> |
| 15 | #include <vector> | 16 | #include <vector> |
| @@ -20,74 +21,68 @@ namespace ir { | |||
| 20 | class TupleType; | 21 | class TupleType; |
| 21 | using TupleTypePtr = std::shared_ptr<const TupleType>; | 22 | using TupleTypePtr = std::shared_ptr<const TupleType>; |
| 22 | 23 | ||
| 24 | +enum class TupleTypeKind { | ||
| 25 | + TUPLE, | ||
| 26 | + NAMED_TUPLE, | ||
| 27 | + STRUCT, | ||
| 28 | +}; | ||
| 29 | + | ||
| 30 | +struct TupleTypeInfo { | ||
| 31 | + TupleTypeKind kind = TupleTypeKind::TUPLE; | ||
| 32 | + std::optional<std::string> name; | ||
| 33 | + std::vector<std::string> fields; | ||
| 34 | + | ||
| 35 | + bool operator==(const TupleTypeInfo& other) const | ||
| 36 | + { | ||
| 37 | + return kind == other.kind && name == other.name && fields == other.fields; | ||
| 38 | + } | ||
| 39 | + bool operator!=(const TupleTypeInfo& other) const { return !(*this == other); } | ||
| 40 | +}; | ||
| 41 | + | ||
| 23 | /** | 42 | /** |
| 24 | - * \brief Compilation-session side table for tuple field names. | 43 | + * \brief Compilation-session side table for semantic tuple metadata. |
| 25 | * | 44 | * |
| 26 | - * Field names of named tuples / structs are *not* part of the tuple type's core | 45 | + * Tuple kind, name, and fields are *not* part of the tuple type's core semantics |
| 27 | - * semantics (positional element types and order are). They are only needed by | 46 | + * (positional element types and order are). The parser records this metadata for |
| 28 | - * codegen during the struct-compat transition (to emit `a.field`) and for dump / | 47 | + * named tuples and structs. An absent entry denotes a plain positional tuple. |
| 29 | - * error display. This side table keeps that metadata out of both the IR nodes and | ||
| 30 | - * the TupleType structural identity. | ||
| 31 | * | 48 | * |
| 32 | * The key is the `TupleType` pointer. TupleType is never structurally interned -- | 49 | * The key is the `TupleType` pointer. TupleType is never structurally interned -- |
| 33 | - * each `struct.create` / `MakeTuple` allocates a fresh instance (`make_shared`), | 50 | + * each `struct.create` allocates a fresh instance (`make_shared`), |
| 34 | * so same-shape-different-name structs get distinct keys. IR passes copy `TypePtr` | 51 | * 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 | 52 | * by shared_ptr (types are immutable and never rebuilt via reflection), so the |
| 36 | * pointer stays valid and identical while IR transformation passes rebuild the | 53 | * pointer stays valid and identical while IR transformation passes rebuild the |
| 37 | * surrounding nodes. | 54 | * surrounding nodes. |
| 38 | * | 55 | * |
| 39 | - * The parser populates this (via `makeNamedTuple` / struct.create lowering); the | 56 | + * The instance rides on `Program` so codegen can capture it at its entry point. |
| 40 | - * instance rides on `Program` so codegen can capture it at its entry point. | ||
| 41 | */ | 57 | */ |
| 42 | class IRDebugInfo { | 58 | class IRDebugInfo { |
| 43 | public: | 59 | public: |
| 44 | - /// Record the ordered field-name list for a named tuple / struct type. | 60 | + /// Record semantic metadata for a named tuple or struct type. |
| 45 | - void RegisterTupleFields(const TupleTypePtr& type, std::vector<std::string> fields) | 61 | + void RegisterTupleTypeInfo(const TupleTypePtr& type, TupleTypeInfo info) |
| 46 | { | 62 | { |
| 47 | if (type == nullptr) { | 63 | if (type == nullptr) { |
| 48 | return; | 64 | return; |
| 49 | } | 65 | } |
| 50 | - tupleFields_[type.get()] = std::move(fields); | 66 | + tupleTypeInfos_[type.get()] = std::move(info); |
| 51 | } | 67 | } |
| 52 | 68 | ||
| 53 | - /// Look up field names by type pointer. Returns nullptr if not registered. | 69 | + /// Look up semantic tuple metadata by type pointer. Returns nullptr for a plain tuple. |
| 54 | - [[nodiscard]] const std::vector<std::string>* GetTupleFields(const TupleType* type) const | 70 | + [[nodiscard]] const TupleTypeInfo* GetTupleTypeInfo(const TupleType* type) const |
| 55 | { | 71 | { |
| 56 | - auto it = tupleFields_.find(type); | 72 | + auto it = tupleTypeInfos_.find(type); |
| 57 | - return it == tupleFields_.end() ? nullptr : &it->second; | 73 | + return it == tupleTypeInfos_.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 | } | 74 | } |
| 76 | 75 | ||
| 77 | /// Merge another table's entries into this one (later registrations win). | 76 | /// Merge another table's entries into this one (later registrations win). |
| 78 | void Merge(const IRDebugInfo& other) | 77 | void Merge(const IRDebugInfo& other) |
| 79 | { | 78 | { |
| 80 | - for (const auto& [type, fields] : other.tupleFields_) { | 79 | + for (const auto& [type, info] : other.tupleTypeInfos_) { |
| 81 | - tupleFields_[type] = fields; | 80 | + tupleTypeInfos_[type] = info; |
| 82 | - } | ||
| 83 | - for (const auto& [type, name] : other.tupleNames_) { | ||
| 84 | - tupleNames_[type] = name; | ||
| 85 | } | 81 | } |
| 86 | } | 82 | } |
| 87 | 83 | ||
| 88 | private: | 84 | private: |
| 89 | - std::unordered_map<const TupleType*, std::vector<std::string>> tupleFields_; | 85 | + std::unordered_map<const TupleType*, TupleTypeInfo> tupleTypeInfos_; |
| 90 | - std::unordered_map<const TupleType*, std::string> tupleNames_; | ||
| 91 | }; | 86 | }; |
| 92 | 87 | ||
| 93 | using IRDebugInfoPtr = std::shared_ptr<IRDebugInfo>; | 88 | using IRDebugInfoPtr = std::shared_ptr<IRDebugInfo>; |
| @@ -53,7 +53,7 @@ public: | |||
| 53 | 53 | ||
| 54 | [[nodiscard]] FunctionPtr GetFunction(const std::string& name) const; | 54 | [[nodiscard]] FunctionPtr GetFunction(const std::string& name) const; |
| 55 | 55 | ||
| 56 | - /// Tuple/struct field-name side table; owned by the Program, supplied by the parser. | 56 | + /// Semantic tuple metadata side table; owned by the Program, supplied by the parser. |
| 57 | /// May be null when a Program is built without one (e.g. rebuilt by a pass). Excluded | 57 | /// May be null when a Program is built without one (e.g. rebuilt by a pass). Excluded |
| 58 | /// from GetFieldDescriptors -> not part of structural equality / hash / serialization. | 58 | /// from GetFieldDescriptors -> not part of structural equality / hash / serialization. |
| 59 | [[nodiscard]] const IRDebugInfo* GetDebugInfo() const { return debugInfo_.get(); } | 59 | [[nodiscard]] const IRDebugInfo* GetDebugInfo() const { return debugInfo_.get(); } |
| @@ -477,9 +477,9 @@ public: | |||
| 477 | /** | 477 | /** |
| 478 | * \brief Create a (positional) tuple type | 478 | * \brief Create a (positional) tuple type |
| 479 | * | 479 | * |
| 480 | - * Field names of named tuples / structs are NOT part of the tuple type. They are | 480 | + * Semantic tuple classification is not part of the core type. The parser records |
| 481 | - * carried by the parser-populated IRDebugInfo side table (see ir/debug_info.h), | 481 | + * tuple kind/name/fields in IRDebugInfo; an absent entry denotes a plain positional |
| 482 | - * keyed by the TupleType pointer, so they do not affect structural identity. | 482 | + * tuple. This metadata does not affect structural identity. |
| 483 | * | 483 | * |
| 484 | * \param types List of types in the tuple | 484 | * \param types List of types in the tuple |
| 485 | */ | 485 | */ |
| @@ -249,7 +249,7 @@ public: | |||
| 249 | [[nodiscard]] bool HasTileAddress(const std::string& tile_name) const; | 249 | [[nodiscard]] bool HasTileAddress(const std::string& tile_name) const; |
| 250 | 250 | ||
| 251 | /** | 251 | /** |
| 252 | - * \brief Register a named TupleType definition for deferred class emission. | 252 | + * \brief Register a struct TupleType definition for deferred class emission. |
| 253 | */ | 253 | */ |
| 254 | void RegisterStructDefinition(const ir::TupleTypePtr& tuple_type, const std::string& type_name, | 254 | void RegisterStructDefinition(const ir::TupleTypePtr& tuple_type, const std::string& type_name, |
| 255 | const std::vector<std::string>& fields, bool is_tiling); | 255 | const std::vector<std::string>& fields, bool is_tiling); |
| @@ -575,7 +575,7 @@ private: | |||
| 575 | std::string current_expr_value_; ///< OUTPUT: Inline C++ value for scalar / tile expressions | 575 | std::string current_expr_value_; ///< OUTPUT: Inline C++ value for scalar / tile expressions |
| 576 | ir::MakeTuplePtr current_tuple_; ///< OUTPUT: underlying MakeTuple for tuple-typed expressions | 576 | ir::MakeTuplePtr current_tuple_; ///< OUTPUT: underlying MakeTuple for tuple-typed expressions |
| 577 | std::vector<ir::ExprPtr> yield_buffer_; ///< If-branch Yield expressions awaiting phi assignment | 577 | std::vector<ir::ExprPtr> yield_buffer_; ///< If-branch Yield expressions awaiting phi assignment |
| 578 | - const ir::IRDebugInfo* debug_info_ = nullptr; ///< Tuple/struct field names, captured at GenerateSingle entry | 578 | + const ir::IRDebugInfo* debug_info_ = nullptr; ///< Program tuple metadata, required at codegen entry |
| 579 | std::map<std::string, std::string> tiling_headers_; ///< Tiling struct headers (filename -> content) | 579 | std::map<std::string, std::string> tiling_headers_; ///< Tiling struct headers (filename -> content) |
| 580 | std::map<std::string, StructDefinition> struct_definitions_; ///< Struct type name ->definition | 580 | std::map<std::string, StructDefinition> struct_definitions_; ///< Struct type name ->definition |
| 581 | 581 | ||
| @@ -662,6 +662,9 @@ private: | |||
| 662 | */ | 662 | */ |
| 663 | bool IsHomogeneousTuple(const ir::TupleTypePtr& tt) const; | 663 | bool IsHomogeneousTuple(const ir::TupleTypePtr& tt) const; |
| 664 | 664 | ||
| 665 | + /// Semantic metadata registered for one exact tuple type, or null for a plain tuple. | ||
| 666 | + const ir::TupleTypeInfo* GetTupleTypeInfo(const ir::TupleTypePtr& tuple_type) const; | ||
| 667 | + | ||
| 665 | /// The C++ struct type name registered for a tuple type, or null if it is not a struct. | 668 | /// The C++ struct type name registered for a tuple type, or null if it is not a struct. |
| 666 | /// Reads the parser's side table, so the answer does not depend on how far codegen has | 669 | /// Reads the parser's side table, so the answer does not depend on how far codegen has |
| 667 | /// walked the body. | 670 | /// walked the body. |
| @@ -674,8 +677,8 @@ private: | |||
| 674 | * captured once at GenerateSingle entry, so it does not depend on how far codegen has | 677 | * captured once at GenerateSingle entry, so it does not depend on how far codegen has |
| 675 | * walked the body. | 678 | * walked the body. |
| 676 | * | 679 | * |
| 677 | - * Named tuples (structs / named tuples) render as `base.field` and are excluded; | 680 | + * A tuple gets an array only when it is homogeneous and has no TupleTypeInfo |
| 678 | - * every other homogeneous tuple gets an array, which is what dynamic indexing needs. | 681 | + * registration. Named tuples and structs are emitted as aggregate leaf slots. |
| 679 | */ | 682 | */ |
| 680 | bool IsArrayTuple(const ir::TupleTypePtr& tt) const; | 683 | bool IsArrayTuple(const ir::TupleTypePtr& tt) const; |
| 681 | 684 | ||
| @@ -12,9 +12,9 @@ | |||
| 12 | * @file block_ops/struct_ops.cpp | 12 | * @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 | - * - struct.create: Expression op that returns a named TupleType. Lowered by | 15 | + * - struct.create: Expression op that returns a struct-classified TupleType. Lowered by |
| 16 | * the CCE backend to ``Name var = {.f0=v0, ...};``. | 16 | * the CCE backend to ``Name var = {.f0=v0, ...};``. |
| 17 | - * - struct.create_array: Expression op that returns TupleType(N × named tuple). | 17 | + * - struct.create_array: Expression op that returns TupleType(N × struct TupleType). |
| 18 | * Lowered to ``Name var[N] = {};`` plus per-slot field-init lines. | 18 | * Lowered to ``Name var[N] = {};`` plus per-slot field-init lines. |
| 19 | */ | 19 | */ |
| 20 | 20 | ||
| @@ -36,9 +36,10 @@ namespace ir { | |||
| 36 | 36 | ||
| 37 | REGISTER_OP("struct.create") | 37 | REGISTER_OP("struct.create") |
| 38 | .set_op_category("StructOp") | 38 | .set_op_category("StructOp") |
| 39 | - .set_description("Materialize a named tuple into a C++ struct. args are field values; kwargs `name` " | 39 | + .set_description("Materialize a TupleType into a C++ struct. args are field values; kwargs `name` " |
| 40 | "is the C++ struct type name and `fields` is the list of field names. Result type is " | 40 | "is the C++ struct type name and `fields` is the list of field names. Result type is " |
| 41 | - "TupleType(field_types, dbgName=fields). Must be let-bound to a Var by the producer.") | 41 | + "TupleType(field_types); the parser registers its struct metadata. Must be let-bound to a Var " |
| 42 | + "by the producer.") | ||
| 42 | .add_argument("...", "Field value expressions in declaration order") | 43 | .add_argument("...", "Field value expressions in declaration order") |
| 43 | .set_attr<std::string>("name") | 44 | .set_attr<std::string>("name") |
| 44 | .set_attr<std::vector<std::string>>("fields") | 45 | .set_attr<std::vector<std::string>>("fields") |
| @@ -87,7 +88,7 @@ REGISTER_OP("struct.set") | |||
| 87 | "name (same naming convention as struct.create's `fields`). Lowered by the CCE backend to " | 88 | "name (same naming convention as struct.create's `fields`). Lowered by the CCE backend to " |
| 88 | "`base.field = value;` or `base.field[index] = value;`. Must be used inside an EvalStmt, " | 89 | "`base.field = value;` or `base.field[index] = value;`. Must be used inside an EvalStmt, " |
| 89 | "not as an RHS value.") | 90 | "not as an RHS value.") |
| 90 | - .add_argument("base", "Struct instance (named TupleType)") | 91 | + .add_argument("base", "Struct instance (struct-classified TupleType)") |
| 91 | .add_argument("value", "New field value expression (or index for array field writes)") | 92 | .add_argument("value", "New field value expression (or index for array field writes)") |
| 92 | .set_attr<std::string>("field") | 93 | .set_attr<std::string>("field") |
| 93 | .f_deduce_type([](const std::vector<ExprPtr>& args, | 94 | .f_deduce_type([](const std::vector<ExprPtr>& args, |
| @@ -623,8 +623,11 @@ std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std: | |||
| 623 | ResetFunctionGenerationState(); | 623 | ResetFunctionGenerationState(); |
| 624 | arch_ = arch; | 624 | arch_ = arch; |
| 625 | 625 | ||
| 626 | - // Capture the tuple/struct field-name side table from the input program. | 626 | + // Parser-produced Programs always carry the tuple metadata table created at |
| 627 | + // the top-level parse entry. Codegen relies on absence *within* that table to | ||
| 628 | + // distinguish a plain tuple from named tuples and structs. | ||
| 627 | debug_info_ = program->GetDebugInfo(); | 629 | debug_info_ = program->GetDebugInfo(); |
| 630 | + INTERNAL_CHECK(debug_info_ != nullptr) << "CCE codegen requires Program IRDebugInfo"; | ||
| 628 | 631 | ||
| 629 | ir::FunctionPtr kernel_func; | 632 | ir::FunctionPtr kernel_func; |
| 630 | std::vector<ir::FunctionPtr> simt_funcs; | 633 | std::vector<ir::FunctionPtr> simt_funcs; |
| @@ -1341,10 +1344,7 @@ bool CCECodegen::IsArrayTuple(const ir::TupleTypePtr& tt) const | |||
| 1341 | { | 1344 | { |
| 1342 | if (!tt || tt->types_.empty()) | 1345 | if (!tt || tt->types_.empty()) |
| 1343 | return false; | 1346 | return false; |
| 1344 | - // Named tuples / structs render as `base.field`; see VisitExpr_(GetItemExprPtr) case 1. | 1347 | + return GetTupleTypeInfo(tt) == nullptr && IsHomogeneousTuple(tt); |
| 1345 | - if (debug_info_ != nullptr && debug_info_->GetTupleFields(tt.get()) != nullptr) | ||
| 1346 | - return false; | ||
| 1347 | - return IsHomogeneousTuple(tt); | ||
| 1348 | } | 1348 | } |
| 1349 | 1349 | ||
| 1350 | void CCECodegen::EmitFullPhiIf(const ir::IfStmtPtr& op) | 1350 | void CCECodegen::EmitFullPhiIf(const ir::IfStmtPtr& op) |
| @@ -1843,23 +1843,21 @@ void CCECodegen::VisitExpr_(const ir::GetItemExprPtr& op) | |||
| 1843 | current_expr_value_ = ""; | 1843 | current_expr_value_ = ""; |
| 1844 | VisitExpr(op->value_); | 1844 | VisitExpr(op->value_); |
| 1845 | 1845 | ||
| 1846 | - // Case 1: the value is already a materialized expression. Named TupleTypes | 1846 | + // Case 1: the value is already a materialized expression. Struct TupleTypes |
| 1847 | - // represent structs and require a constant field ordinal. Other TupleTypes | 1847 | + // require a constant field ordinal. Other TupleTypes represent indexable |
| 1848 | - // represent indexable expressions such as an array-valued struct field. | 1848 | + // expressions such as an array-valued struct field. |
| 1849 | if (current_tuple_ == nullptr) { | 1849 | if (current_tuple_ == nullptr) { |
| 1850 | std::string base_code = current_expr_value_; | 1850 | std::string base_code = current_expr_value_; |
| 1851 | auto tuple_type = ir::As<ir::TupleType>(value_type); | 1851 | auto tuple_type = ir::As<ir::TupleType>(value_type); |
| 1852 | - const std::vector<std::string>* fields = debug_info_ != nullptr ? | 1852 | + const ir::TupleTypeInfo* info = GetTupleTypeInfo(tuple_type); |
| 1853 | - debug_info_->GetTupleFields(tuple_type.get()) : | 1853 | + if (info != nullptr && info->kind == ir::TupleTypeKind::STRUCT) { |
| 1854 | - nullptr; | ||
| 1855 | - if (fields != nullptr) { | ||
| 1856 | auto const_idx = ir::As<ir::ConstInt>(op->slice_); | 1854 | auto const_idx = ir::As<ir::ConstInt>(op->slice_); |
| 1857 | CHECK(const_idx != nullptr) << "GetItemExpr struct field requires a constant index at " | 1855 | CHECK(const_idx != nullptr) << "GetItemExpr struct field requires a constant index at " |
| 1858 | << op->span_.ToString(); | 1856 | << op->span_.ToString(); |
| 1859 | int idx = static_cast<int>(const_idx->value_); | 1857 | int idx = static_cast<int>(const_idx->value_); |
| 1860 | - CHECK(idx >= 0 && idx < static_cast<int>(fields->size())) | 1858 | + CHECK(idx >= 0 && idx < static_cast<int>(info->fields.size())) |
| 1861 | << "GetItemExpr struct field index " << idx << " out of bounds"; | 1859 | << "GetItemExpr struct field index " << idx << " out of bounds"; |
| 1862 | - current_expr_value_ = base_code + "." + (*fields)[idx]; | 1860 | + current_expr_value_ = base_code + "." + info->fields[idx]; |
| 1863 | } else { | 1861 | } else { |
| 1864 | current_expr_value_ = base_code + "[" + index_code + "]"; | 1862 | current_expr_value_ = base_code + "[" + index_code + "]"; |
| 1865 | } | 1863 | } |
| @@ -2782,7 +2780,7 @@ std::string CppTypeForField(const ir::TypePtr& t) | |||
| 2782 | // Tile fields are stored as opaque tile references; v1 emits as auto-deduced. | 2780 | // Tile fields are stored as opaque tile references; v1 emits as auto-deduced. |
| 2783 | return "auto"; | 2781 | return "auto"; |
| 2784 | } | 2782 | } |
| 2785 | - // Nested named tuple ->the field stores another C++ struct; we have to look up its | 2783 | + // Nested registered struct -> the field stores another C++ struct; look up its |
| 2786 | // type name. For v1 we fall back to int64_t and rely on CCE flat expansion if the | 2784 | // type name. For v1 we fall back to int64_t and rely on CCE flat expansion if the |
| 2787 | // nested tuple type isn't already materialized; full nested support is a follow-up. | 2785 | // nested tuple type isn't already materialized; full nested support is a follow-up. |
| 2788 | return "int64_t"; | 2786 | return "int64_t"; |
| @@ -2850,9 +2848,20 @@ void CCECodegen::RegisterStructDefinition(const ir::TupleTypePtr& tuple_type, co | |||
| 2850 | } | 2848 | } |
| 2851 | } | 2849 | } |
| 2852 | 2850 | ||
| 2851 | +const ir::TupleTypeInfo* CCECodegen::GetTupleTypeInfo(const ir::TupleTypePtr& tuple_type) const | ||
| 2852 | +{ | ||
| 2853 | + INTERNAL_CHECK(debug_info_ != nullptr) << "CCE codegen requires IRDebugInfo"; | ||
| 2854 | + return tuple_type != nullptr ? debug_info_->GetTupleTypeInfo(tuple_type.get()) : nullptr; | ||
| 2855 | +} | ||
| 2856 | + | ||
| 2853 | const std::string* CCECodegen::GetStructName(const ir::TupleTypePtr& tuple_type) const | 2857 | const std::string* CCECodegen::GetStructName(const ir::TupleTypePtr& tuple_type) const |
| 2854 | { | 2858 | { |
| 2855 | - return debug_info_ != nullptr ? debug_info_->GetTupleName(tuple_type.get()) : nullptr; | 2859 | + const ir::TupleTypeInfo* info = GetTupleTypeInfo(tuple_type); |
| 2860 | + if (info == nullptr || info->kind != ir::TupleTypeKind::STRUCT) { | ||
| 2861 | + return nullptr; | ||
| 2862 | + } | ||
| 2863 | + CHECK(info->name.has_value()) << "Struct TupleTypeInfo has no type name"; | ||
| 2864 | + return &info->name.value(); | ||
| 2856 | } | 2865 | } |
| 2857 | 2866 | ||
| 2858 | void CCECodegen::MarkStructVolatile(const ir::TypePtr& type) | 2867 | void CCECodegen::MarkStructVolatile(const ir::TypePtr& type) |
| @@ -2870,16 +2879,13 @@ void CCECodegen::RegisterTilingStructTypes(const ir::FunctionPtr& func) | |||
| 2870 | auto tuple_type = ir::As<ir::TupleType>(param->GetType()); | 2879 | auto tuple_type = ir::As<ir::TupleType>(param->GetType()); |
| 2871 | if (tuple_type == nullptr) | 2880 | if (tuple_type == nullptr) |
| 2872 | continue; | 2881 | continue; |
| 2873 | - const std::vector<std::string>* fields = debug_info_ != nullptr ? | 2882 | + const ir::TupleTypeInfo* info = GetTupleTypeInfo(tuple_type); |
| 2874 | - debug_info_->GetTupleFields(tuple_type.get()) : | 2883 | + CHECK(info != nullptr && info->kind == ir::TupleTypeKind::STRUCT) |
| 2875 | - nullptr; | 2884 | + << "Tiling param '" << param->name_ << "' has no struct TupleTypeInfo in IRDebugInfo"; |
| 2876 | - CHECK(fields != nullptr) << "Tiling struct param '" << param->name_ | 2885 | + CHECK(info->fields.size() == tuple_type->types_.size()) |
| 2877 | - << "' has no field names registered in IRDebugInfo"; | ||
| 2878 | - CHECK(fields->size() == tuple_type->types_.size()) | ||
| 2879 | << "Tiling struct field count mismatch for param '" << param->name_ << "'"; | 2886 | << "Tiling struct field count mismatch for param '" << param->name_ << "'"; |
| 2880 | - const std::string* registered_name = debug_info_->GetTupleName(tuple_type.get()); | 2887 | + CHECK(info->name.has_value()) << "Tiling struct param '" << param->name_ << "' has no type name"; |
| 2881 | - const std::string struct_name = registered_name != nullptr ? *registered_name : "Tiling"; | 2888 | + RegisterStructDefinition(tuple_type, info->name.value(), info->fields, true); |
| 2882 | - RegisterStructDefinition(tuple_type, struct_name, *fields, true); | ||
| 2883 | } | 2889 | } |
| 2884 | } | 2890 | } |
| 2885 | 2891 | ||
| @@ -2903,8 +2909,10 @@ void CCECodegen::EmitTilingStructCopy(const ir::FunctionPtr& func) | |||
| 2903 | if (tuple_type == nullptr) | 2909 | if (tuple_type == nullptr) |
| 2904 | continue; | 2910 | continue; |
| 2905 | std::string name = context_.GetVarName(param); | 2911 | std::string name = context_.GetVarName(param); |
| 2906 | - const std::string* registered_name = debug_info_->GetTupleName(tuple_type.get()); | 2912 | + const std::string* registered_name = GetStructName(tuple_type); |
| 2907 | - const std::string struct_name = registered_name != nullptr ? *registered_name : "Tiling"; | 2913 | + CHECK(registered_name != nullptr) |
| 2914 | + << "Tiling param '" << param->name_ << "' has no struct TupleTypeInfo in IRDebugInfo"; | ||
| 2915 | + const std::string& struct_name = *registered_name; | ||
| 2908 | emitter_.EmitLine("constexpr uint32_t " + name + "_all_bytes = sizeof(" + struct_name + ");"); | 2916 | emitter_.EmitLine("constexpr uint32_t " + name + "_all_bytes = sizeof(" + struct_name + ");"); |
| 2909 | emitter_.EmitLine(struct_name + " " + name + ";"); | 2917 | emitter_.EmitLine(struct_name + " " + name + ";"); |
| 2910 | auto emit_cube_copy = [&]() { | 2918 | auto emit_cube_copy = [&]() { |
| @@ -115,6 +115,9 @@ ir::MemRefPtr MakeMemRef(ir::MemorySpace space) | |||
| 115 | ir::ProgramPtr MakeProgram(const ir::StmtPtr& body, const std::vector<ir::VarPtr>& params = {}, | 115 | ir::ProgramPtr MakeProgram(const ir::StmtPtr& body, const std::vector<ir::VarPtr>& params = {}, |
| 116 | ir::IRDebugInfoPtr debug_info = nullptr) | 116 | ir::IRDebugInfoPtr debug_info = nullptr) |
| 117 | { | 117 | { |
| 118 | + if (debug_info == nullptr) { | ||
| 119 | + debug_info = std::make_shared<ir::IRDebugInfo>(); | ||
| 120 | + } | ||
| 118 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, | 121 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, |
| 119 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); | 122 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); |
| 120 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", | 123 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", |
| @@ -139,8 +142,7 @@ std::string RunSsbufCodegen(const std::string& op_name) | |||
| 139 | // What makes this tuple a struct is the parser's side table, which codegen reads to resolve | 142 | // What makes this tuple a struct is the parser's side table, which codegen reads to resolve |
| 140 | // the C++ type name. A hand-built program has to supply it the same way the parser does. | 143 | // the C++ type name. A hand-built program has to supply it the same way the parser does. |
| 141 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); | 144 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); |
| 142 | - debug_info->RegisterTupleName(tuple_type, "SsbufStruct"); | 145 | + debug_info->RegisterTupleTypeInfo(tuple_type, {ir::TupleTypeKind::STRUCT, std::string("SsbufStruct"), {"value"}}); |
| 143 | - debug_info->RegisterTupleFields(tuple_type, {"value"}); | ||
| 144 | auto struct_var = MakeVar("struct_var", tuple_type); | 146 | auto struct_var = MakeVar("struct_var", tuple_type); |
| 145 | auto create = std::make_shared<const ir::Call>("struct.create", std::vector<ir::ExprPtr>{MakeVar("value", scalar)}, | 147 | auto create = std::make_shared<const ir::Call>("struct.create", std::vector<ir::ExprPtr>{MakeVar("value", scalar)}, |
| 146 | std::vector<std::pair<std::string, std::any>>{ | 148 | std::vector<std::pair<std::string, std::any>>{ |
| @@ -85,7 +85,7 @@ ir::ProgramPtr MakeProgram(const ir::StmtPtr& body, const std::vector<ir::VarPtr | |||
| 85 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, | 85 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, |
| 86 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); | 86 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); |
| 87 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", | 87 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", |
| 88 | - ir::Span::Unknown()); | 88 | + ir::Span::Unknown(), std::make_shared<ir::IRDebugInfo>()); |
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | ir::TileTypePtr MakeTileType(const std::vector<int64_t>& shape, ir::DataType dtype, | 91 | ir::TileTypePtr MakeTileType(const std::vector<int64_t>& shape, ir::DataType dtype, |
| @@ -28,12 +28,6 @@ namespace pypto { | |||
| 28 | namespace codegen { | 28 | namespace codegen { |
| 29 | namespace { | 29 | namespace { |
| 30 | 30 | ||
| 31 | -class TestableCCECodegen : public CCECodegen { | ||
| 32 | -public: | ||
| 33 | - using CCECodegen::CCECodegen; | ||
| 34 | - void SetDebugInfo(const ir::IRDebugInfo* debug_info) { debug_info_ = debug_info; } | ||
| 35 | -}; | ||
| 36 | - | ||
| 37 | ir::ExprPtr MakeConstInt(int64_t value) | 31 | ir::ExprPtr MakeConstInt(int64_t value) |
| 38 | { | 32 | { |
| 39 | return std::make_shared<const ir::ConstInt>(value, ir::DataType::INT64, ir::Span::Unknown()); | 33 | return std::make_shared<const ir::ConstInt>(value, ir::DataType::INT64, ir::Span::Unknown()); |
| @@ -56,6 +50,9 @@ ir::VarPtr MakeTensorVar(const std::string& name, const std::vector<int64_t>& sh | |||
| 56 | ir::ProgramPtr MakeProgram(const ir::StmtPtr& body, const std::vector<ir::VarPtr>& params = {}, | 50 | ir::ProgramPtr MakeProgram(const ir::StmtPtr& body, const std::vector<ir::VarPtr>& params = {}, |
| 57 | ir::IRDebugInfoPtr debug_info = nullptr) | 51 | ir::IRDebugInfoPtr debug_info = nullptr) |
| 58 | { | 52 | { |
| 53 | + if (debug_info == nullptr) { | ||
| 54 | + debug_info = std::make_shared<ir::IRDebugInfo>(); | ||
| 55 | + } | ||
| 59 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, | 56 | auto function = std::make_shared<const ir::Function>("kernel", params, std::vector<ir::TypePtr>{}, body, |
| 60 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); | 57 | ir::Span::Unknown(), ir::FunctionType::IN_CORE, true); |
| 61 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", | 58 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", |
| @@ -161,8 +158,8 @@ TEST(CCECodegenTest, EmitsTargetSpecificTilingStructCopy) | |||
| 161 | auto tuple_type = std::make_shared<const ir::TupleType>(field_types); | 158 | auto tuple_type = std::make_shared<const ir::TupleType>(field_types); |
| 162 | auto tiling = MakeVar("tiling", tuple_type); | 159 | auto tiling = MakeVar("tiling", tuple_type); |
| 163 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); | 160 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); |
| 164 | - debug_info->RegisterTupleFields(tuple_type, {"rows", "cols"}); | 161 | + debug_info->RegisterTupleTypeInfo(tuple_type, |
| 165 | - debug_info->RegisterTupleName(tuple_type, "TestTiling"); | 162 | + {ir::TupleTypeKind::STRUCT, std::string("TestTiling"), {"rows", "cols"}}); |
| 166 | auto body = std::make_shared<const ir::ReturnStmt>(ir::Span::Unknown()); | 163 | auto body = std::make_shared<const ir::ReturnStmt>(ir::Span::Unknown()); |
| 167 | auto program = MakeProgram(body, {tiling}, debug_info); | 164 | auto program = MakeProgram(body, {tiling}, debug_info); |
| 168 | 165 | ||
| @@ -190,6 +187,19 @@ TEST(CCECodegenTest, RejectsUnprojectedOrWrongTargetSections) | |||
| 190 | EXPECT_THROW((void)cube_codegen.GenerateSingle(MakeProgram(vf_section), "a5"), pypto::ir::InternalError); | 187 | EXPECT_THROW((void)cube_codegen.GenerateSingle(MakeProgram(vf_section), "a5"), pypto::ir::InternalError); |
| 191 | } | 188 | } |
| 192 | 189 | ||
| 190 | +TEST(CCECodegenTest, RejectsProgramWithoutDebugInfo) | ||
| 191 | +{ | ||
| 192 | + auto body = std::make_shared<const ir::ReturnStmt>(ir::Span::Unknown()); | ||
| 193 | + auto function = std::make_shared<const ir::Function>("kernel", std::vector<ir::VarPtr>{}, | ||
| 194 | + std::vector<ir::TypePtr>{}, body, ir::Span::Unknown(), | ||
| 195 | + ir::FunctionType::IN_CORE, true); | ||
| 196 | + auto program = std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{function}, "test_program", | ||
| 197 | + ir::Span::Unknown()); | ||
| 198 | + | ||
| 199 | + CCECodegen codegen(ir::SectionKind::Vector); | ||
| 200 | + EXPECT_THROW((void)codegen.GenerateSingle(program, "a5"), pypto::ir::InternalError); | ||
| 201 | +} | ||
| 202 | + | ||
| 193 | TEST(CCECodegenHeaderTest, CoversPointerAndBasicCodegenHelpers) | 203 | TEST(CCECodegenHeaderTest, CoversPointerAndBasicCodegenHelpers) |
| 194 | { | 204 | { |
| 195 | CCECodegen codegen(ir::SectionKind::Vector); | 205 | CCECodegen codegen(ir::SectionKind::Vector); |
| @@ -538,21 +548,26 @@ TEST(CCECodegenTest, EmitsArrayAccessForUnmaterializedTupleVar) | |||
| 538 | auto tuple_var = MakeVar("values", tuple_type); | 548 | auto tuple_var = MakeVar("values", tuple_type); |
| 539 | auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); | 549 | auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); |
| 540 | 550 | ||
| 551 | + auto body = std::make_shared<const ir::ReturnStmt>(ir::Span::Unknown()); | ||
| 552 | + auto program = MakeProgram(body); | ||
| 541 | CCECodegen codegen(ir::SectionKind::Vector); | 553 | CCECodegen codegen(ir::SectionKind::Vector); |
| 554 | + (void)codegen.GenerateSingle(program, "a5"); | ||
| 542 | EXPECT_EQ(codegen.GetExprAsCode(item), "values[1]"); | 555 | EXPECT_EQ(codegen.GetExprAsCode(item), "values[1]"); |
| 543 | } | 556 | } |
| 544 | 557 | ||
| 545 | -TEST(CCECodegenTest, EmitsFieldAccessForUnmaterializedNamedTupleVar) | 558 | +TEST(CCECodegenTest, EmitsFieldAccessForUnmaterializedStructVar) |
| 546 | { | 559 | { |
| 547 | auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | 560 | auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); |
| 548 | auto tuple_type = std::make_shared<const ir::TupleType>(std::vector<ir::TypePtr>{scalar_type, scalar_type}); | 561 | auto tuple_type = std::make_shared<const ir::TupleType>(std::vector<ir::TypePtr>{scalar_type, scalar_type}); |
| 549 | auto tuple_var = MakeVar("config", tuple_type); | 562 | auto tuple_var = MakeVar("config", tuple_type); |
| 550 | auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); | 563 | auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); |
| 551 | - ir::IRDebugInfo debug_info; | 564 | + auto debug_info = std::make_shared<ir::IRDebugInfo>(); |
| 552 | - debug_info.RegisterTupleFields(tuple_type, {"rows", "cols"}); | 565 | + debug_info->RegisterTupleTypeInfo(tuple_type, {ir::TupleTypeKind::STRUCT, std::string("Config"), {"rows", "cols"}}); |
| 553 | 566 | ||
| 554 | - TestableCCECodegen codegen(ir::SectionKind::Vector); | 567 | + auto body = std::make_shared<const ir::ReturnStmt>(ir::Span::Unknown()); |
| 555 | - codegen.SetDebugInfo(&debug_info); | 568 | + auto program = MakeProgram(body, {}, debug_info); |
| 569 | + CCECodegen codegen(ir::SectionKind::Vector); | ||
| 570 | + (void)codegen.GenerateSingle(program, "a5"); | ||
| 556 | EXPECT_EQ(codegen.GetExprAsCode(item), "config.cols"); | 571 | EXPECT_EQ(codegen.GetExprAsCode(item), "config.cols"); |
| 557 | } | 572 | } |
| 558 | 573 | ||
| @@ -675,7 +690,8 @@ TEST(CCECodegenTest, FlattensAggregateTuplePhiIntoLeafSlots) | |||
| 675 | if_stmt, read_selected}, | 690 | if_stmt, read_selected}, |
| 676 | ir::Span::Unknown()); | 691 | ir::Span::Unknown()); |
| 677 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); | 692 | auto debug_info = std::make_shared<ir::IRDebugInfo>(); |
| 678 | - debug_info->RegisterTupleFields(aggregate_type, {"first", "second"}); | 693 | + debug_info->RegisterTupleTypeInfo(aggregate_type, |
| 694 | + {ir::TupleTypeKind::NAMED_TUPLE, std::nullopt, {"first", "second"}}); | ||
| 679 | 695 | ||
| 680 | CCECodegen codegen(ir::SectionKind::Vector); | 696 | CCECodegen codegen(ir::SectionKind::Vector); |
| 681 | std::string generated = codegen.GenerateSingle(MakeProgram(body, {condition}, debug_info), "a5"); | 697 | std::string generated = codegen.GenerateSingle(MakeProgram(body, {condition}, debug_info), "a5"); |
| @@ -223,7 +223,8 @@ ir::ProgramPtr MakeSimtProgram() | |||
| 223 | std::vector<ir::FunctionPtr> functions = {MakeScalarAddCallee(fp32), MakeStoreCallee(tile_type, u32, fp32), | 223 | std::vector<ir::FunctionPtr> functions = {MakeScalarAddCallee(fp32), MakeStoreCallee(tile_type, u32, fp32), |
| 224 | MakeApplyCallee(tile_type, u32, fp32), | 224 | MakeApplyCallee(tile_type, u32, fp32), |
| 225 | MakeSimtEntry(tile_type, tensor_type, u32, i32, fp32), kernel}; | 225 | MakeSimtEntry(tile_type, tensor_type, u32, i32, fp32), kernel}; |
| 226 | - return std::make_shared<const ir::Program>(std::move(functions), "simt_program", Sp()); | 226 | + return std::make_shared<const ir::Program>(std::move(functions), "simt_program", Sp(), |
| 227 | + std::make_shared<ir::IRDebugInfo>()); | ||
| 227 | } | 228 | } |
| 228 | 229 | ||
| 229 | ir::ProgramPtr MakeSimtCalleeNameCollisionProgram() | 230 | ir::ProgramPtr MakeSimtCalleeNameCollisionProgram() |
| @@ -248,7 +249,7 @@ ir::ProgramPtr MakeSimtCalleeNameCollisionProgram() | |||
| 248 | kernel_body, Sp(), ir::FunctionType::IN_CORE, true); | 249 | kernel_body, Sp(), ir::FunctionType::IN_CORE, true); |
| 249 | 250 | ||
| 250 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{callee, simt_entry, kernel}, | 251 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{callee, simt_entry, kernel}, |
| 251 | - "simt_callee_name_collision", Sp()); | 252 | + "simt_callee_name_collision", Sp(), std::make_shared<ir::IRDebugInfo>()); |
| 252 | } | 253 | } |
| 253 | 254 | ||
| 254 | ir::ProgramPtr MakeSimtScalarOpsProgram() | 255 | ir::ProgramPtr MakeSimtScalarOpsProgram() |
| @@ -351,7 +352,7 @@ ir::ProgramPtr MakeSimtScalarOpsProgram() | |||
| 351 | Sp(), ir::FunctionType::IN_CORE, true); | 352 | Sp(), ir::FunctionType::IN_CORE, true); |
| 352 | 353 | ||
| 353 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{simt_function, kernel}, "simt_scalar_ops", | 354 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{simt_function, kernel}, "simt_scalar_ops", |
| 354 | - Sp()); | 355 | + Sp(), std::make_shared<ir::IRDebugInfo>()); |
| 355 | } | 356 | } |
| 356 | 357 | ||
| 357 | ir::ProgramPtr MakeSimtAtomicOpsProgram() | 358 | ir::ProgramPtr MakeSimtAtomicOpsProgram() |
| @@ -422,7 +423,7 @@ ir::ProgramPtr MakeSimtAtomicOpsProgram() | |||
| 422 | Sp(), ir::FunctionType::IN_CORE, true); | 423 | Sp(), ir::FunctionType::IN_CORE, true); |
| 423 | 424 | ||
| 424 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{simt_function, kernel}, "simt_atomic_ops", | 425 | return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{simt_function, kernel}, "simt_atomic_ops", |
| 425 | - Sp()); | 426 | + Sp(), std::make_shared<ir::IRDebugInfo>()); |
| 426 | } | 427 | } |
| 427 | 428 | ||
| 428 | } // namespace | 429 | } // namespace |
| @@ -1128,6 +1128,43 @@ class TupleType(Type): | |||
| 1128 | """ | 1128 | """ |
| 1129 | 1129 | ||
| 1130 | 1130 | ||
| 1131 | +class TupleTypeKind(enum.IntEnum): | ||
| 1132 | + """Semantic classification for a TupleType.""" | ||
| 1133 | + | ||
| 1134 | + TUPLE = ... | ||
| 1135 | + NAMED_TUPLE = ... | ||
| 1136 | + STRUCT = ... | ||
| 1137 | + | ||
| 1138 | + | ||
| 1139 | +class TupleTypeInfo: | ||
| 1140 | + """Semantic metadata associated with one exact TupleType.""" | ||
| 1141 | + | ||
| 1142 | + kind: Final[TupleTypeKind] | ||
| 1143 | + name: Final[str | None] | ||
| 1144 | + fields: Final[list[str]] | ||
| 1145 | + | ||
| 1146 | + def __init__( | ||
| 1147 | + self, | ||
| 1148 | + kind: TupleTypeKind, | ||
| 1149 | + name: str | None = None, | ||
| 1150 | + fields: Sequence[str] = (), | ||
| 1151 | + ) -> None: ... | ||
| 1152 | + | ||
| 1153 | + def __eq__(self, other: TupleTypeInfo) -> bool: ... | ||
| 1154 | + | ||
| 1155 | + def __ne__(self, other: TupleTypeInfo) -> bool: ... | ||
| 1156 | + | ||
| 1157 | + | ||
| 1158 | +class IRDebugInfo: | ||
| 1159 | + """Program-owned side table for semantic tuple metadata.""" | ||
| 1160 | + | ||
| 1161 | + def __init__(self) -> None: ... | ||
| 1162 | + | ||
| 1163 | + def register_tuple_type_info(self, type: TupleType, info: TupleTypeInfo) -> None: ... | ||
| 1164 | + | ||
| 1165 | + def get_tuple_type_info(self, type: TupleType) -> TupleTypeInfo | None: ... | ||
| 1166 | + | ||
| 1167 | + | ||
| 1131 | class MakeTuple(Expr): | 1168 | class MakeTuple(Expr): |
| 1132 | """Tuple construction expression.""" | 1169 | """Tuple construction expression.""" |
| 1133 | 1170 | ||
| @@ -1660,6 +1697,7 @@ class Program(IRNode): | |||
| 1660 | functions: list[Function], | 1697 | functions: list[Function], |
| 1661 | name: str, | 1698 | name: str, |
| 1662 | span: Span, | 1699 | span: Span, |
| 1700 | + debug_info: IRDebugInfo | None = None, | ||
| 1663 | ) -> None: | 1701 | ) -> None: |
| 1664 | """Create a program from a list of functions. | 1702 | """Create a program from a list of functions. |
| 1665 | 1703 | ||
| @@ -1669,6 +1707,7 @@ class Program(IRNode): | |||
| 1669 | functions: List of functions | 1707 | functions: List of functions |
| 1670 | name: Program name (optional) | 1708 | name: Program name (optional) |
| 1671 | span: Source location | 1709 | span: Source location |
| 1710 | + debug_info: Semantic tuple metadata side table | ||
| 1672 | """ | 1711 | """ |
| 1673 | 1712 | ||
| 1674 | def __getitem__(self, name: str) -> Function | None: | 1713 | def __getitem__(self, name: str) -> Function | None: |
| @@ -24,6 +24,7 @@ from .._utils import _get_span_or_capture, _normalize_expr | |||
| 24 | from ._op_registry import op_impl | 24 | from ._op_registry import op_impl |
| 25 | 25 | ||
| 26 | _DIM3_FIELDS = ("x", "y", "z") | 26 | _DIM3_FIELDS = ("x", "y", "z") |
| 27 | +_DIM3_CONTEXT_NAME = "dim3_context" | ||
| 27 | 28 | ||
| 28 | 29 | ||
| 29 | def _make_dim3_components(op_name: str, span: Span) -> list[Call]: | 30 | def _make_dim3_components(op_name: str, span: Span) -> list[Call]: |
| @@ -350,7 +351,12 @@ def _parse_dim3_context(parser: Any, call: ast.Call, op_name: str) -> Expr: | |||
| 350 | """Parse a SIMT context query as an IR named tuple.""" | 351 | """Parse a SIMT context query as an IR named tuple.""" |
| 351 | _validate_simt_body_op(parser, call, {}) | 352 | _validate_simt_body_op(parser, call, {}) |
| 352 | span = parser.span_tracker.get_span(call) | 353 | span = parser.span_tracker.get_span(call) |
| 353 | - return parser.make_named_tuple(_make_dim3_components(op_name, span), _DIM3_FIELDS, span) | 354 | + return parser.make_named_tuple( |
| 355 | + _make_dim3_components(op_name, span), | ||
| 356 | + _DIM3_FIELDS, | ||
| 357 | + span, | ||
| 358 | + name=_DIM3_CONTEXT_NAME, | ||
| 359 | + ) | ||
| 354 | 360 | ||
| 355 | 361 | ||
| 356 | @op_impl("simt.thread_idx") | 362 | @op_impl("simt.thread_idx") |
| @@ -448,9 +448,10 @@ def make_tuple(**kwargs: Any) -> Any: | |||
| 448 | 448 | ||
| 449 | Unlike ``pl.struct``, ``pl.make_tuple`` aggregates IR variables under field names | 449 | Unlike ``pl.struct``, ``pl.make_tuple`` aggregates IR variables under field names |
| 450 | without forcing a C++ struct to be generated. The parser lowers it to a | 450 | without forcing a C++ struct to be generated. The parser lowers it to a |
| 451 | - ``MakeTuple(elements, dbgName=fields)``; subsequent ``t.field`` accesses | 451 | + ``MakeTuple(elements)`` and records its field names in the parser's tuple type |
| 452 | - become ``GetItem(t, index)`` and parser-side constant propagation resolves | 452 | + registry; subsequent ``t.field`` accesses become ``GetItem(t, index)`` and |
| 453 | - constant indices to the original elements (no struct definition emitted). | 453 | + parser-side constant propagation resolves constant indices to the original |
| 454 | + elements (no struct definition emitted). | ||
| 454 | """ | 455 | """ |
| 455 | return SimpleNamespace(**kwargs) | 456 | return SimpleNamespace(**kwargs) |
| 456 | 457 | ||
| @@ -16,6 +16,7 @@ import ast | |||
| 16 | from pypto.pypto_impl import ir | 16 | from pypto.pypto_impl import ir |
| 17 | from pypto.pypto_impl.ir import DataType | 17 | from pypto.pypto_impl.ir import DataType |
| 18 | 18 | ||
| 19 | +from ._tuple_type_registry import TupleTypeKind | ||
| 19 | from .diagnostics import ParserSyntaxError, ParserTypeError, UnsupportedFeatureError | 20 | from .diagnostics import ParserSyntaxError, ParserTypeError, UnsupportedFeatureError |
| 20 | 21 | ||
| 21 | 22 | ||
| @@ -397,7 +398,7 @@ class AssignmentParserMixin: | |||
| 397 | field_name = target.value.attr | 398 | field_name = target.value.attr |
| 398 | fields = self.named_fields(base) | 399 | fields = self.named_fields(base) |
| 399 | if fields: | 400 | if fields: |
| 400 | - if self.debug_info.get_tuple_name(base.type) is None: | 401 | + if self.classify_tuple_type(base.type).kind != TupleTypeKind.STRUCT: |
| 401 | raise ParserSyntaxError( | 402 | raise ParserSyntaxError( |
| 402 | f"Cannot assign to immutable named tuple field '{ast.unparse(target)}'", | 403 | f"Cannot assign to immutable named tuple field '{ast.unparse(target)}'", |
| 403 | span=span, | 404 | span=span, |
| @@ -410,13 +411,11 @@ class AssignmentParserMixin: | |||
| 410 | ) | 411 | ) |
| 411 | field_idx = fields.index(field_name) | 412 | field_idx = fields.index(field_name) |
| 412 | field_type = base.type.types[field_idx] | 413 | field_type = base.type.types[field_idx] |
| 413 | - # An array field is a nested TupleType that carries no struct type | 414 | + # An array field is a plain nested TupleType. A nested named tuple or |
| 414 | - # name in IRDebugInfo; a nested struct field is also a TupleType but | 415 | + # struct has a TupleTypeInfo entry and is not subscript-writable. |
| 415 | - # registers its C++ name at creation. Only the former is subscript | ||
| 416 | - # writable — subscripting the latter would emit a bogus struct.set. | ||
| 417 | is_array_field = ( | 416 | is_array_field = ( |
| 418 | isinstance(field_type, ir.TupleType) | 417 | isinstance(field_type, ir.TupleType) |
| 419 | - and self.debug_info.get_tuple_name(field_type) is None | 418 | + and self.classify_tuple_type(field_type).kind == TupleTypeKind.TUPLE |
| 420 | ) | 419 | ) |
| 421 | if not is_array_field: | 420 | if not is_array_field: |
| 422 | raise ParserTypeError( | 421 | raise ParserTypeError( |
| @@ -32,6 +32,7 @@ from ._expression_parser import ExpressionParserMixin | |||
| 32 | from ._scope_manager import JumpKind, ScopeManager | 32 | from ._scope_manager import JumpKind, ScopeManager |
| 33 | from ._span_tracker import SpanTracker | 33 | from ._span_tracker import SpanTracker |
| 34 | from ._struct_parser import StructParserMixin | 34 | from ._struct_parser import StructParserMixin |
| 35 | +from ._tuple_type_registry import TupleTypeRegistry | ||
| 35 | from ._type_resolver import TypeResolver | 36 | from ._type_resolver import TypeResolver |
| 36 | from .diagnostics import ( | 37 | from .diagnostics import ( |
| 37 | ParserSyntaxError, | 38 | ParserSyntaxError, |
| @@ -109,6 +110,7 @@ class ASTParser( | |||
| 109 | Args: | 110 | Args: |
| 110 | source_file: Path to source file | 111 | source_file: Path to source file |
| 111 | source_lines: Lines of source code (dedented for parsing) | 112 | source_lines: Lines of source code (dedented for parsing) |
| 113 | + debug_info: Program-owned semantic tuple metadata table | ||
| 112 | line_offset: Line number offset to add to AST line numbers (for dedented code) | 114 | line_offset: Line number offset to add to AST line numbers (for dedented code) |
| 113 | col_offset: Column offset to add to AST column numbers (for dedented code) | 115 | col_offset: Column offset to add to AST column numbers (for dedented code) |
| 114 | strict_ssa: If True, enforce SSA (single assignment). If False (default), allow reassignment. | 116 | strict_ssa: If True, enforce SSA (single assignment). If False (default), allow reassignment. |
| @@ -162,10 +164,12 @@ class ASTParser( | |||
| 162 | bound_signature=bound_signature, | 164 | bound_signature=bound_signature, |
| 163 | ) | 165 | ) |
| 164 | self.builder = IRBuilder() | 166 | self.builder = IRBuilder() |
| 165 | - # Tuple/struct field-name side table; owned by the Program being built and passed in | 167 | + if debug_info is None: |
| 166 | - # by the caller (kernel / decorator). Not created here; may be None for parses that | 168 | + raise ValueError("ASTParser requires a non-null IRDebugInfo") |
| 167 | - # do not feed a Program. | 169 | + # Tuple metadata is owned by the Program being built. Nested parsers share |
| 170 | + # this same IRDebugInfo instance. | ||
| 168 | self.debug_info = debug_info | 171 | self.debug_info = debug_info |
| 172 | + self.tuple_type_registry = TupleTypeRegistry(self.debug_info) | ||
| 169 | self.external_funcs: dict[str, ir.Function] = {} # Track external functions referenced | 173 | self.external_funcs: dict[str, ir.Function] = {} # Track external functions referenced |
| 170 | 174 | ||
| 171 | # Track active control-flow builders while parsing nested statements. | 175 | # Track active control-flow builders while parsing nested statements. |
| @@ -192,9 +196,6 @@ class ASTParser( | |||
| 192 | self._ifexpr_tmp_counter: int = 0 | 196 | self._ifexpr_tmp_counter: int = 0 |
| 193 | # Maps group Expr objects -> (depth, per-tile mutex IDs, memory). | 197 | # Maps group Expr objects -> (depth, per-tile mutex IDs, memory). |
| 194 | self.tile_group_meta: dict[ir.Expr, tuple] = {} | 198 | self.tile_group_meta: dict[ir.Expr, tuple] = {} |
| 195 | - # Tile-group handles use TupleType in IR. Retain their exact types so | ||
| 196 | - # control-flow merging can reject handles nested inside other tuples. | ||
| 197 | - self._tile_group_types: list[ir.TupleType] = [] | ||
| 198 | # Parser-only constant environment. Runtime bindings remain exclusively in | 199 | # Parser-only constant environment. Runtime bindings remain exclusively in |
| 199 | # ScopeManager as Vars; this map records constants by physical SSA name. | 200 | # ScopeManager as Vars; this map records constants by physical SSA name. |
| 200 | self.const_env: dict[str, ir.Expr] = {} | 201 | self.const_env: dict[str, ir.Expr] = {} |
| @@ -585,14 +586,13 @@ class ASTParser( | |||
| 585 | tiling_cls = self.resolve_tiling_class(arg.annotation) if arg.annotation else None | 586 | tiling_cls = self.resolve_tiling_class(arg.annotation) if arg.annotation else None |
| 586 | if tiling_cls is not None: | 587 | if tiling_cls is not None: |
| 587 | fields = get_tiling_fields(tiling_cls) | 588 | fields = get_tiling_fields(tiling_cls) |
| 588 | - # Single struct parameter: the tiling class is lowered to a named TupleType whose | 589 | + # Single struct parameter: the tiling class is lowered to a TupleType whose |
| 589 | - # field names live in the IRDebugInfo side table (codegen emits `struct <ClassName>`). | 590 | + # STRUCT TupleTypeInfo is recorded in IRDebugInfo. |
| 590 | tuple_type = get_tiling_tuple_type(tiling_cls) | 591 | tuple_type = get_tiling_tuple_type(tiling_cls) |
| 591 | tiling_var = f.param(param_name, tuple_type, param_span) | 592 | tiling_var = f.param(param_name, tuple_type, param_span) |
| 592 | # A tiling param is a struct: register its fields and the Python class name, so | 593 | # A tiling param is a struct: register its fields and the Python class name, so |
| 593 | # codegen emits `struct <ClassName>` (matching the host-side struct). | 594 | # codegen emits `struct <ClassName>` (matching the host-side struct). |
| 594 | - self.register_tuple_name(tiling_var, tiling_cls.__name__) | 595 | + self.register_struct_type(tiling_var, tiling_cls.__name__, list(fields.keys())) |
| 595 | - self.register_tuple_fields(tiling_var, list(fields.keys())) | ||
| 596 | self.scope_manager.define_var(param_name, tiling_var, allow_redef=True) | 596 | self.scope_manager.define_var(param_name, tiling_var, allow_redef=True) |
| 597 | return | 597 | return |
| 598 | 598 | ||
| @@ -38,8 +38,11 @@ from pypto_pro.ir.op.block_ops import make_tile_expr as _make_tile_expr | |||
| 38 | from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size | 38 | from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size |
| 39 | from pypto_pro.ir.op.system_ops import MAX_MUTEX_ID | 39 | from pypto_pro.ir.op.system_ops import MAX_MUTEX_ID |
| 40 | 40 | ||
| 41 | +from ._tuple_type_registry import TupleTypeKind | ||
| 41 | from .diagnostics import ParserSyntaxError, ParserTypeError, check_in_range | 42 | from .diagnostics import ParserSyntaxError, ParserTypeError, check_in_range |
| 42 | 43 | ||
| 44 | +_TILE_GROUP_TYPE_NAME = "tile_group" | ||
| 45 | + | ||
| 43 | 46 | ||
| 44 | def _is_int_sequence(value) -> bool: | 47 | def _is_int_sequence(value) -> bool: |
| 45 | """Whether *value* is a non-empty tuple of plain integers.""" | 48 | """Whether *value* is a non-empty tuple of plain integers.""" |
| @@ -106,22 +109,20 @@ class BufferParserMixin: | |||
| 106 | except ValueError as exc: | 109 | except ValueError as exc: |
| 107 | raise ParserTypeError(f"make_tile_group() {exc}") from exc | 110 | raise ParserTypeError(f"make_tile_group() {exc}") from exc |
| 108 | 111 | ||
| 109 | - def is_tile_group(self, expr) -> bool: | 112 | + def is_tile_group_type(self, value_type: ir.Type) -> bool: |
| 110 | - return "tiles" in self.named_fields(expr) | 113 | + if not isinstance(value_type, ir.TupleType): |
| 114 | + return False | ||
| 115 | + info = self.classify_tuple_type(value_type) | ||
| 116 | + return info.kind == TupleTypeKind.NAMED_TUPLE and info.name == _TILE_GROUP_TYPE_NAME | ||
| 111 | 117 | ||
| 112 | - def _mark_tile_group_type(self, expr: ir.Expr) -> None: | 118 | + def is_tile_group(self, expr) -> bool: |
| 113 | - group_type = expr.type | 119 | + return isinstance(expr, ir.Expr) and self.is_tile_group_type(expr.type) |
| 114 | - if not isinstance(group_type, ir.TupleType): | ||
| 115 | - raise TypeError("tile group must have TupleType") | ||
| 116 | - if not any(group_type is known_type for known_type in self._tile_group_types): | ||
| 117 | - self._tile_group_types.append(group_type) | ||
| 118 | 120 | ||
| 119 | def _contains_tile_group_type(self, value_type: ir.Type) -> bool: | 121 | def _contains_tile_group_type(self, value_type: ir.Type) -> bool: |
| 120 | - if any(value_type is group_type for group_type in self._tile_group_types): | 122 | + if self.is_tile_group_type(value_type): |
| 121 | return True | 123 | return True |
| 122 | return isinstance(value_type, ir.TupleType) and any( | 124 | return isinstance(value_type, ir.TupleType) and any( |
| 123 | - self._contains_tile_group_type(element_type) | 125 | + self._contains_tile_group_type(element_type) for element_type in value_type.types |
| 124 | - for element_type in value_type.types | ||
| 125 | ) | 126 | ) |
| 126 | 127 | ||
| 127 | # --- factory -------------------------------------------------------------- | 128 | # --- factory -------------------------------------------------------------- |
| @@ -255,8 +256,12 @@ class BufferParserMixin: | |||
| 255 | ) | 256 | ) |
| 256 | mut_fields.append(f"mutex_ids{suffix}") | 257 | mut_fields.append(f"mutex_ids{suffix}") |
| 257 | if depth == 1: | 258 | if depth == 1: |
| 258 | - result = self.make_named_tuple([tiles_tuple, *mut_tuples], ["tiles", *mut_fields], span) | 259 | + result = self.make_named_tuple( |
| 259 | - self._mark_tile_group_type(result) | 260 | + [tiles_tuple, *mut_tuples], |
| 261 | + ["tiles", *mut_fields], | ||
| 262 | + span, | ||
| 263 | + name=_TILE_GROUP_TYPE_NAME, | ||
| 264 | + ) | ||
| 260 | self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory) | 265 | self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory) |
| 261 | return result | 266 | return result |
| 262 | cursor_call = ir.create_op_call( | 267 | cursor_call = ir.create_op_call( |
| @@ -265,13 +270,14 @@ class BufferParserMixin: | |||
| 265 | {"name": "_TileGroupCursor", "fields": ["cursor"]}, | 270 | {"name": "_TileGroupCursor", "fields": ["cursor"]}, |
| 266 | span, | 271 | span, |
| 267 | ) | 272 | ) |
| 268 | - self.register_tuple_name(cursor_call, "_TileGroupCursor") | 273 | + self.register_struct_type(cursor_call, "_TileGroupCursor", ["cursor"]) |
| 269 | - self.register_tuple_fields(cursor_call, ["cursor"]) | ||
| 270 | cursor = self.builder.let(f"_tg_{var_name}_cursor", cursor_call, span=span) | 274 | cursor = self.builder.let(f"_tg_{var_name}_cursor", cursor_call, span=span) |
| 271 | result = self.make_named_tuple( | 275 | result = self.make_named_tuple( |
| 272 | - [tiles_tuple, *mut_tuples, cursor], ["tiles", *mut_fields, "cursor"], span | 276 | + [tiles_tuple, *mut_tuples, cursor], |
| 277 | + ["tiles", *mut_fields, "cursor"], | ||
| 278 | + span, | ||
| 279 | + name=_TILE_GROUP_TYPE_NAME, | ||
| 273 | ) | 280 | ) |
| 274 | - self._mark_tile_group_type(result) | ||
| 275 | self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory) | 281 | self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory) |
| 276 | return result | 282 | return result |
| 277 | 283 | ||
| @@ -340,13 +346,21 @@ class BufferParserMixin: | |||
| 340 | # ③ cursor: reused from the original handle so the rotation position | 346 | # ③ cursor: reused from the original handle so the rotation position |
| 341 | # (the original group keeps its own independent cursor) is preserved. | 347 | # (the original group keeps its own independent cursor) is preserved. |
| 342 | if n_slots == 1: | 348 | if n_slots == 1: |
| 343 | - result = self.make_named_tuple([tiles_tuple, *mut_tuples], ["tiles", *mut_fields], span) | 349 | + result = self.make_named_tuple( |
| 344 | - self._mark_tile_group_type(result) | 350 | + [tiles_tuple, *mut_tuples], |
| 351 | + ["tiles", *mut_fields], | ||
| 352 | + span, | ||
| 353 | + name=_TILE_GROUP_TYPE_NAME, | ||
| 354 | + ) | ||
| 345 | self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space) | 355 | self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space) |
| 346 | return result | 356 | return result |
| 347 | cursor = self.lower_attr_access(group, "cursor", span) | 357 | cursor = self.lower_attr_access(group, "cursor", span) |
| 348 | - result = self.make_named_tuple([tiles_tuple, *mut_tuples, cursor], ["tiles", *mut_fields, "cursor"], span) | 358 | + result = self.make_named_tuple( |
| 349 | - self._mark_tile_group_type(result) | 359 | + [tiles_tuple, *mut_tuples, cursor], |
| 360 | + ["tiles", *mut_fields, "cursor"], | ||
| 361 | + span, | ||
| 362 | + name=_TILE_GROUP_TYPE_NAME, | ||
| 363 | + ) | ||
| 350 | self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space) | 364 | self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space) |
| 351 | return result | 365 | return result |
| 352 | 366 | ||
| @@ -333,7 +333,7 @@ class ControlFlowParserMixin: | |||
| 333 | if not info.jumps: | 333 | if not info.jumps: |
| 334 | return [] | 334 | return [] |
| 335 | output_count = len(info.jumps[0].outputs) | 335 | output_count = len(info.jumps[0].outputs) |
| 336 | - states = [PhiState() for _ in range(output_count)] | 336 | + states = [PhiState(type_equal=self.tuple_type_registry.types_equal) for _ in range(output_count)] |
| 337 | for jump in info.jumps: | 337 | for jump in info.jumps: |
| 338 | if len(jump.outputs) != output_count: | 338 | if len(jump.outputs) != output_count: |
| 339 | raise TypeError("control-flow jump output counts must match") | 339 | raise TypeError("control-flow jump output counts must match") |
| @@ -454,8 +454,11 @@ class ControlFlowParserMixin: | |||
| 454 | slots: list[_LoopMergeSlot] = [] | 454 | slots: list[_LoopMergeSlot] = [] |
| 455 | for name, init_value in merge_inputs: | 455 | for name, init_value in merge_inputs: |
| 456 | state = LoopVarState( | 456 | state = LoopVarState( |
| 457 | - PhiState(constant_state=ConstantState.NONCONSTANT), | 457 | + PhiState( |
| 458 | - PhiState(), | 458 | + constant_state=ConstantState.NONCONSTANT, |
| 459 | + type_equal=self.tuple_type_registry.types_equal, | ||
| 460 | + ), | ||
| 461 | + PhiState(type_equal=self.tuple_type_registry.types_equal), | ||
| 459 | ) | 462 | ) |
| 460 | if self._is_empty_control_flow_value(init_value): | 463 | if self._is_empty_control_flow_value(init_value): |
| 461 | iter_var = self.builder.var(name, init_value.type, span) | 464 | iter_var = self.builder.var(name, init_value.type, span) |
| @@ -624,6 +627,7 @@ class ControlFlowParserMixin: | |||
| 624 | """Parse a natural ``for`` directly into an SSA ForStmt.""" | 627 | """Parse a natural ``for`` directly into an SSA ForStmt.""" |
| 625 | self._validate_loop_orelse(stmt) | 628 | self._validate_loop_orelse(stmt) |
| 626 | iter_call = self._validate_for_loop_iterator(stmt) | 629 | iter_call = self._validate_for_loop_iterator(stmt) |
| 630 | + stmt = self._lower_for_loop(stmt) | ||
| 627 | loop_var_name = self._parse_for_loop_target(stmt) | 631 | loop_var_name = self._parse_for_loop_target(stmt) |
| 628 | range_args = self._parse_range_call(iter_call) | 632 | range_args = self._parse_range_call(iter_call) |
| 629 | span = self.span_tracker.get_span(stmt) | 633 | span = self.span_tracker.get_span(stmt) |
| @@ -951,6 +955,27 @@ class ControlFlowParserMixin: | |||
| 951 | ) | 955 | ) |
| 952 | return stmt.target.id | 956 | return stmt.target.id |
| 953 | 957 | ||
| 958 | + def _lower_for_loop(self, stmt: ast.For) -> ast.For: | ||
| 959 | + """Lower the Python-visible target to an assignment from an internal iterator.""" | ||
| 960 | + loop_var_name = self._parse_for_loop_target(stmt) | ||
| 961 | + iterator_name = f"{loop_var_name}__iterator" | ||
| 962 | + | ||
| 963 | + target = ast.copy_location(ast.Name(id=loop_var_name, ctx=ast.Store()), stmt.target) | ||
| 964 | + iterator = ast.copy_location(ast.Name(id=iterator_name, ctx=ast.Load()), stmt.target) | ||
| 965 | + bind_target = ast.copy_location(ast.Assign(targets=[target], value=iterator), stmt.target) | ||
| 966 | + lowered = ast.copy_location( | ||
| 967 | + ast.For( | ||
| 968 | + target=ast.copy_location(ast.Name(id=iterator_name, ctx=ast.Store()), stmt.target), | ||
| 969 | + iter=stmt.iter, | ||
| 970 | + body=[bind_target, *stmt.body], | ||
| 971 | + orelse=stmt.orelse, | ||
| 972 | + type_comment=stmt.type_comment, | ||
| 973 | + ), | ||
| 974 | + stmt, | ||
| 975 | + ) | ||
| 976 | + ast.fix_missing_locations(lowered) | ||
| 977 | + return lowered | ||
| 978 | + | ||
| 954 | def _parse_range_call(self, call: ast.Call) -> dict[str, Any]: | 979 | def _parse_range_call(self, call: ast.Call) -> dict[str, Any]: |
| 955 | """Parse pl.range() call arguments. | 980 | """Parse pl.range() call arguments. |
| 956 | 981 | ||
| @@ -21,6 +21,7 @@ from pypto_pro.ir._operators import make_binary as _make_binary | |||
| 21 | from pypto_pro.ir._utils import _normalize_expr | 21 | from pypto_pro.ir._utils import _normalize_expr |
| 22 | 22 | ||
| 23 | from ._expr_evaluator import ExprEvaluator | 23 | from ._expr_evaluator import ExprEvaluator |
| 24 | +from ._tuple_type_registry import TupleTypeInfo | ||
| 24 | from ._utils import _const_int_value, _is_const_expr | 25 | from ._utils import _const_int_value, _is_const_expr |
| 25 | from .diagnostics import ( | 26 | from .diagnostics import ( |
| 26 | FinalRejectionError, | 27 | FinalRejectionError, |
| @@ -81,12 +82,6 @@ class ExpressionParserMixin: | |||
| 81 | value = self.lookup_expr_by_name(name) | 82 | value = self.lookup_expr_by_name(name) |
| 82 | if value is None: | 83 | if value is None: |
| 83 | return None | 84 | return None |
| 84 | - if isinstance(value, ir.Expr) and isinstance(value.type, ir.NoneType): | ||
| 85 | - raise ParserTypeError( | ||
| 86 | - f"Variable '{name}' has no valid type on every reachable control-flow path", | ||
| 87 | - span=self._current_span(), | ||
| 88 | - hint="Define the variable with one compatible type on every path before using it.", | ||
| 89 | - ) | ||
| 90 | if _is_const_expr(value): | 85 | if _is_const_expr(value): |
| 91 | return ("const", value) | 86 | return ("const", value) |
| 92 | return ("runtime", value) if isinstance(value, ir.Expr) else ("parse_time", value) | 87 | return ("runtime", value) if isinstance(value, ir.Expr) else ("parse_time", value) |
| @@ -287,12 +282,14 @@ class ExpressionParserMixin: | |||
| 287 | # cannot silently capture a caller IR variable. | 282 | # cannot silently capture a caller IR variable. |
| 288 | binding = self.local_binding(var_name) | 283 | binding = self.local_binding(var_name) |
| 289 | if binding is not None: | 284 | if binding is not None: |
| 290 | - return binding[1] | 285 | + value = binding[1] |
| 286 | + if not (isinstance(value, ir.Expr) and isinstance(value.type, ir.NoneType)): | ||
| 287 | + return value | ||
| 291 | 288 | ||
| 292 | raise UndefinedVariableError( | 289 | raise UndefinedVariableError( |
| 293 | - f"Undefined variable '{var_name}'", | 290 | + f"Use of potentially undefined variable '{var_name}'", |
| 294 | span=self.span_tracker.get_span(name), | 291 | span=self.span_tracker.get_span(name), |
| 295 | - hint="Check if the variable is defined before using it or is available in the enclosing scope", | 292 | + hint="Ensure the variable is defined before using it.", |
| 296 | ) | 293 | ) |
| 297 | 294 | ||
| 298 | def none_with_mutex_meta(self, span: ir.Span) -> ir.Expr: | 295 | def none_with_mutex_meta(self, span: ir.Span) -> ir.Expr: |
| @@ -675,58 +672,42 @@ class ExpressionParserMixin: | |||
| 675 | self._reject_ternary_branch(result, branch, "runtime", expr.test) | 672 | self._reject_ternary_branch(result, branch, "runtime", expr.test) |
| 676 | return result | 673 | return result |
| 677 | 674 | ||
| 678 | - def make_named_tuple(self, elements: list, field_names, span: ir.Span) -> ir.Expr: | 675 | + def make_named_tuple( |
| 679 | - """Build a named ``MakeTuple`` and record its type's field names. | 676 | + self, |
| 680 | - | 677 | + elements: list, |
| 681 | - Single chokepoint for named-tuple construction: the field names are not stored | 678 | + field_names, |
| 682 | - on the expression or the type; they are registered into the Program's | 679 | + span: ir.Span, |
| 683 | - ``IRDebugInfo`` keyed by the resulting TupleType pointer, so codegen can recover | 680 | + *, |
| 684 | - ``a.field`` even when the read does not fold to the MakeTuple. | 681 | + name: str | None = None, |
| 685 | - """ | 682 | + ) -> ir.Expr: |
| 686 | - field_names = list(field_names) | 683 | + """Build a named ``MakeTuple`` and register its semantic tuple metadata.""" |
| 684 | + field_names = tuple(field_names) | ||
| 687 | mt = ir.MakeTuple(elements, span) | 685 | mt = ir.MakeTuple(elements, span) |
| 688 | - return self.register_tuple_fields(mt, field_names) | 686 | + self.tuple_type_registry.register_named_tuple(mt.type, field_names, name=name) |
| 687 | + return mt | ||
| 688 | + | ||
| 689 | + def classify_tuple_type(self, tuple_type: ir.TupleType) -> TupleTypeInfo: | ||
| 690 | + """Classify a tuple type by its parser-session kind, name, and fields.""" | ||
| 691 | + return self.tuple_type_registry.classify(tuple_type) | ||
| 689 | 692 | ||
| 690 | def named_fields(self, expr) -> list[str]: | 693 | def named_fields(self, expr) -> list[str]: |
| 691 | - """Field names of a named tuple / struct expr, from the IRDebugInfo side table. | 694 | + """Return parser-registered field names for a named tuple or struct expression.""" |
| 692 | - | ||
| 693 | - Single source of truth: the TupleType no longer carries field names. One parser | ||
| 694 | - builds each Program and registers field names at the construction site. | ||
| 695 | - Returns [] for non-tuples or unregistered/positional tuples. | ||
| 696 | - """ | ||
| 697 | - if self.debug_info is None: | ||
| 698 | - return [] | ||
| 699 | if not (isinstance(expr, ir.Expr) and isinstance(expr.type, ir.TupleType)): | 695 | if not (isinstance(expr, ir.Expr) and isinstance(expr.type, ir.TupleType)): |
| 700 | return [] | 696 | return [] |
| 701 | - return list(self.debug_info.get_tuple_fields(expr.type) or []) | 697 | + return list(self.classify_tuple_type(expr.type).fields) |
| 702 | 698 | ||
| 703 | - def register_tuple_fields(self, expr: ir.Expr, field_names) -> ir.Expr: | 699 | + def register_struct_type(self, expr: ir.Expr, struct_name: str, field_names) -> ir.Expr: |
| 704 | - """Record the field names of a named tuple / struct result type. | 700 | + """Register a struct's semantic tuple metadata in IRDebugInfo.""" |
| 705 | - | ||
| 706 | - Every named tuple registers its fields; a struct additionally registers its C++ type | ||
| 707 | - name via :meth:`register_tuple_name`. | ||
| 708 | - """ | ||
| 709 | expr_type = expr.type | 701 | expr_type = expr.type |
| 710 | - if self.debug_info is not None and isinstance(expr_type, ir.TupleType) and field_names: | 702 | + if not isinstance(expr_type, ir.TupleType): |
| 711 | - self.debug_info.register_tuple_fields(expr_type, list(field_names)) | 703 | + raise TypeError(f"Struct '{struct_name}' must have TupleType") |
| 712 | - return expr | 704 | + self.tuple_type_registry.register_struct(expr_type, struct_name, field_names) |
| 713 | - | ||
| 714 | - def register_tuple_name(self, expr: ir.Expr, struct_name: str) -> ir.Expr: | ||
| 715 | - """Record the C++ struct type name of a struct result type. | ||
| 716 | - | ||
| 717 | - Codegen seeds its type -> C++ name map from this at entry, so a struct type resolves | ||
| 718 | - without having traversed the statement that produces it. | ||
| 719 | - """ | ||
| 720 | - expr_type = expr.type | ||
| 721 | - if self.debug_info is not None and isinstance(expr_type, ir.TupleType) and struct_name: | ||
| 722 | - self.debug_info.register_tuple_name(expr_type, struct_name) | ||
| 723 | return expr | 705 | return expr |
| 724 | 706 | ||
| 725 | def lower_attr_access(self, base: ir.Expr, field_name: str, span: ir.Span): | 707 | def lower_attr_access(self, base: ir.Expr, field_name: str, span: ir.Span): |
| 726 | """Lower attribute read ``base.field`` to its named tuple element. | 708 | """Lower attribute read ``base.field`` to its named tuple element. |
| 727 | 709 | ||
| 728 | - Resolves the field index from the base's named TupleType and records the | 710 | + Resolves the field index from the parser's tuple type registry. When *base* is a parse-time |
| 729 | - type's field names in ``IRDebugInfo``. When *base* is a parse-time | ||
| 730 | constant ``MakeTuple`` (never for struct_array, whose elements are | 711 | constant ``MakeTuple`` (never for struct_array, whose elements are |
| 731 | mutable structs with backing-array alias semantics), constant-folds the | 712 | mutable structs with backing-array alias semantics), constant-folds the |
| 732 | read to the static element instead of emitting a ``GetItemExpr``. | 713 | read to the static element instead of emitting a ``GetItemExpr``. |
| @@ -29,7 +29,7 @@ from collections.abc import Iterator | |||
| 29 | from contextlib import contextmanager | 29 | from contextlib import contextmanager |
| 30 | from dataclasses import dataclass, field | 30 | from dataclasses import dataclass, field |
| 31 | import enum | 31 | import enum |
| 32 | -from typing import Any | 32 | +from typing import Any, Callable |
| 33 | 33 | ||
| 34 | from pypto.pypto_impl import ir | 34 | from pypto.pypto_impl import ir |
| 35 | 35 | ||
| @@ -83,6 +83,7 @@ class PhiState: | |||
| 83 | last_span: ir.Span | None = None | 83 | last_span: ir.Span | None = None |
| 84 | constant_state: ConstantState = ConstantState.UNSET | 84 | constant_state: ConstantState = ConstantState.UNSET |
| 85 | constant_value: ir.Expr | None = None | 85 | constant_value: ir.Expr | None = None |
| 86 | + type_equal: Callable[[ir.Type, ir.Type], bool] = field(default=_type_equal, repr=False, compare=False) | ||
| 86 | 87 | ||
| 87 | def propagate( | 88 | def propagate( |
| 88 | self, | 89 | self, |
| @@ -103,11 +104,12 @@ class PhiState: | |||
| 103 | ) | 104 | ) |
| 104 | self.ty = src_ty | 105 | self.ty = src_ty |
| 105 | elif not isinstance(self.ty, ir.NoneType): | 106 | elif not isinstance(self.ty, ir.NoneType): |
| 106 | - if not _type_equal(self.ty, src_ty): | 107 | + if not self.type_equal(self.ty, src_ty): |
| 107 | if fail_eagerly: | 108 | if fail_eagerly: |
| 108 | raise ParserTypeError( | 109 | raise ParserTypeError( |
| 109 | - f"Type depends on path taken: {src_ty} vs. {self.ty}", | 110 | + "Inconsistent types in control flow", |
| 110 | span=src.span, | 111 | span=src.span, |
| 112 | + hint="Check that the variable types are compatible. Use astype to ensure consistent types.", | ||
| 111 | ) | 113 | ) |
| 112 | self.ty = ir.NoneType.get() | 114 | self.ty = ir.NoneType.get() |
| 113 | self.last_span = src.span | 115 | self.last_span = src.span |
| @@ -141,8 +141,7 @@ class StructParserMixin: | |||
| 141 | {"name": struct_name, "fields": field_names}, | 141 | {"name": struct_name, "fields": field_names}, |
| 142 | span, | 142 | span, |
| 143 | ) | 143 | ) |
| 144 | - self.register_tuple_name(call, struct_name) | 144 | + return self.register_struct_type(call, struct_name, field_names) |
| 145 | - return self.register_tuple_fields(call, field_names) | ||
| 146 | 145 | ||
| 147 | @op_impl("struct_array") | 146 | @op_impl("struct_array") |
| 148 | def _parse_struct_array_expr(self, call: ast.Call) -> ir.Expr: | 147 | def _parse_struct_array_expr(self, call: ast.Call) -> ir.Expr: |
| @@ -209,8 +208,7 @@ class StructParserMixin: | |||
| 209 | {"name": struct_name, "fields": field_names}, | 208 | {"name": struct_name, "fields": field_names}, |
| 210 | span, | 209 | span, |
| 211 | ) | 210 | ) |
| 212 | - self.register_tuple_name(slot_call, struct_name) | 211 | + self.register_struct_type(slot_call, struct_name, field_names) |
| 213 | - self.register_tuple_fields(slot_call, field_names) | ||
| 214 | slot_var = self.builder.let(f"{var_name}_{i}", slot_call, span=span) | 212 | slot_var = self.builder.let(f"{var_name}_{i}", slot_call, span=span) |
| 215 | slot_vars.append(slot_var) | 213 | slot_vars.append(slot_var) |
| 216 | result = ir.MakeTuple(slot_vars, span) | 214 | result = ir.MakeTuple(slot_vars, span) |
| @@ -0,0 +1,74 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 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 | +"""Parser-session metadata for the semantic kinds represented by ``TupleType``.""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +from pypto.pypto_impl import ir | ||
| 15 | + | ||
| 16 | +TupleTypeKind = ir.TupleTypeKind | ||
| 17 | +TupleTypeInfo = ir.TupleTypeInfo | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +_PLAIN_TUPLE_INFO = TupleTypeInfo(TupleTypeKind.TUPLE) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class TupleTypeRegistry: | ||
| 24 | + """Register and query semantic tuple metadata stored in ``IRDebugInfo``.""" | ||
| 25 | + | ||
| 26 | + def __init__(self, debug_info: ir.IRDebugInfo): | ||
| 27 | + if debug_info is None: | ||
| 28 | + raise ValueError("TupleTypeRegistry requires a non-null IRDebugInfo") | ||
| 29 | + self._debug_info = debug_info | ||
| 30 | + | ||
| 31 | + def _register(self, tuple_type: ir.TupleType, info: TupleTypeInfo) -> None: | ||
| 32 | + if len(info.fields) != len(tuple_type.types): | ||
| 33 | + raise ValueError( | ||
| 34 | + f"Tuple field count {len(info.fields)} does not match element count {len(tuple_type.types)}" | ||
| 35 | + ) | ||
| 36 | + self._debug_info.register_tuple_type_info(tuple_type, info) | ||
| 37 | + | ||
| 38 | + def register_named_tuple( | ||
| 39 | + self, | ||
| 40 | + tuple_type: ir.TupleType, | ||
| 41 | + fields: list[str] | tuple[str, ...], | ||
| 42 | + *, | ||
| 43 | + name: str | None = None, | ||
| 44 | + ) -> None: | ||
| 45 | + """Register a user or framework named tuple.""" | ||
| 46 | + self._register(tuple_type, TupleTypeInfo(TupleTypeKind.NAMED_TUPLE, name, list(fields))) | ||
| 47 | + | ||
| 48 | + def register_struct( | ||
| 49 | + self, | ||
| 50 | + tuple_type: ir.TupleType, | ||
| 51 | + name: str, | ||
| 52 | + fields: list[str] | tuple[str, ...], | ||
| 53 | + ) -> None: | ||
| 54 | + """Register a C++ struct.""" | ||
| 55 | + self._register(tuple_type, TupleTypeInfo(TupleTypeKind.STRUCT, name, list(fields))) | ||
| 56 | + | ||
| 57 | + def classify(self, tuple_type: ir.TupleType) -> TupleTypeInfo: | ||
| 58 | + """Return the semantic classification of one exact tuple type.""" | ||
| 59 | + if not isinstance(tuple_type, ir.TupleType): | ||
| 60 | + raise TypeError(f"Expected TupleType, got {type(tuple_type).__name__}") | ||
| 61 | + info = self._debug_info.get_tuple_type_info(tuple_type) | ||
| 62 | + return info if info is not None else _PLAIN_TUPLE_INFO | ||
| 63 | + | ||
| 64 | + def types_equal(self, lhs: ir.Type, rhs: ir.Type) -> bool: | ||
| 65 | + """Compare IR types and tuple metadata recursively.""" | ||
| 66 | + if not ir.structural_equal(lhs, rhs, enable_auto_mapping=False): | ||
| 67 | + return False | ||
| 68 | + if not isinstance(lhs, ir.TupleType) or not isinstance(rhs, ir.TupleType): | ||
| 69 | + return True | ||
| 70 | + if self.classify(lhs) != self.classify(rhs): | ||
| 71 | + return False | ||
| 72 | + return all( | ||
| 73 | + self.types_equal(left, right) for left, right in zip(lhs.types, rhs.types, strict=True) | ||
| 74 | + ) | ||
| @@ -227,8 +227,8 @@ class KernelDef: | |||
| 227 | program_name = self._name if self._name is not None else self._func.__name__ | 227 | program_name = self._name if self._name is not None else self._func.__name__ |
| 228 | 228 | ||
| 229 | try: | 229 | try: |
| 230 | - # The Program owns one IRDebugInfo; create it here and share it with the parser | 230 | + # The Program owns one IRDebugInfo; share it with the parser so all |
| 231 | - # so field names land in the table the Program carries. | 231 | + # semantic tuple metadata lands in the table the Program carries. |
| 232 | debug_info = ir.IRDebugInfo() | 232 | debug_info = ir.IRDebugInfo() |
| 233 | parser = ASTParser( | 233 | parser = ASTParser( |
| 234 | self._source_file, | 234 | self._source_file, |
| @@ -1454,36 +1454,38 @@ void BindProgram(py::module_& ir) | |||
| 1454 | function_class.def("get_attr", &Function::GetAttr<int>, py::arg("key"), py::arg("default_value") = 0, | 1454 | function_class.def("get_attr", &Function::GetAttr<int>, py::arg("key"), py::arg("default_value") = 0, |
| 1455 | "Get an integer function attribute"); | 1455 | "Get an integer function attribute"); |
| 1456 | 1456 | ||
| 1457 | - // IRDebugInfo - compilation-session side table for tuple/struct field names. | 1457 | + py::enum_<TupleTypeKind>(ir, "TupleTypeKind", "Semantic tuple classification") |
| 1458 | + .value("TUPLE", TupleTypeKind::TUPLE, "Plain positional tuple") | ||
| 1459 | + .value("NAMED_TUPLE", TupleTypeKind::NAMED_TUPLE, "Named immutable tuple") | ||
| 1460 | + .value("STRUCT", TupleTypeKind::STRUCT, "Mutable C++ struct"); | ||
| 1461 | + | ||
| 1462 | + py::class_<TupleTypeInfo>(ir, "TupleTypeInfo", "Semantic metadata associated with one TupleType") | ||
| 1463 | + .def(py::init<TupleTypeKind, std::optional<std::string>, std::vector<std::string>>(), py::arg("kind"), | ||
| 1464 | + py::arg("name") = py::none(), py::arg("fields") = std::vector<std::string>{}) | ||
| 1465 | + .def_readonly("kind", &TupleTypeInfo::kind) | ||
| 1466 | + .def_readonly("name", &TupleTypeInfo::name) | ||
| 1467 | + .def_readonly("fields", &TupleTypeInfo::fields) | ||
| 1468 | + .def("__eq__", &TupleTypeInfo::operator==, py::arg("other")) | ||
| 1469 | + .def("__ne__", &TupleTypeInfo::operator!=, py::arg("other")); | ||
| 1470 | + | ||
| 1471 | + // IRDebugInfo - compilation-session side table for semantic tuple metadata. | ||
| 1458 | auto debug_info_class = py::class_<IRDebugInfo, std::shared_ptr<IRDebugInfo>>( | 1472 | auto debug_info_class = py::class_<IRDebugInfo, std::shared_ptr<IRDebugInfo>>( |
| 1459 | ir, "IRDebugInfo", | 1473 | ir, "IRDebugInfo", |
| 1460 | - "Side table mapping a tuple type to its ordered field-name list. " | 1474 | + "Side table mapping a tuple type to its semantic TupleTypeInfo. " |
| 1461 | "Populated by the parser, carried on Program, read by codegen."); | 1475 | "Populated by the parser, carried on Program, read by codegen."); |
| 1462 | debug_info_class.def(py::init<>()); | 1476 | debug_info_class.def(py::init<>()); |
| 1463 | - debug_info_class.def("register_tuple_fields", &IRDebugInfo::RegisterTupleFields, py::arg("type"), py::arg("fields"), | 1477 | + debug_info_class.def("register_tuple_type_info", &IRDebugInfo::RegisterTupleTypeInfo, py::arg("type"), |
| 1464 | - "Record the ordered field-name list for a named tuple / struct type."); | 1478 | + py::arg("info"), "Record semantic metadata for a named tuple or struct type."); |
| 1465 | debug_info_class.def( | 1479 | debug_info_class.def( |
| 1466 | - "get_tuple_fields", | 1480 | + "get_tuple_type_info", |
| 1467 | [](const IRDebugInfo& self, const TupleTypePtr& type) -> py::object { | 1481 | [](const IRDebugInfo& self, const TupleTypePtr& type) -> py::object { |
| 1468 | - const auto* fields = self.GetTupleFields(type.get()); | 1482 | + const auto* info = self.GetTupleTypeInfo(type.get()); |
| 1469 | - if (fields == nullptr) { | 1483 | + if (info == nullptr) { |
| 1470 | return py::none(); | 1484 | return py::none(); |
| 1471 | } | 1485 | } |
| 1472 | - return py::cast(*fields); | 1486 | + return py::cast(*info); |
| 1473 | }, | 1487 | }, |
| 1474 | - py::arg("type"), "Look up field names by type, returns None if not registered."); | 1488 | + py::arg("type"), "Look up tuple metadata by type; returns None for a plain tuple."); |
| 1475 | - debug_info_class.def("register_tuple_name", &IRDebugInfo::RegisterTupleName, py::arg("type"), py::arg("name"), | ||
| 1476 | - "Record the C++ struct type name for a named tuple / struct type."); | ||
| 1477 | - debug_info_class.def( | ||
| 1478 | - "get_tuple_name", | ||
| 1479 | - [](const IRDebugInfo& self, const TupleTypePtr& type) -> py::object { | ||
| 1480 | - const auto* name = self.GetTupleName(type.get()); | ||
| 1481 | - if (name == nullptr) { | ||
| 1482 | - return py::none(); | ||
| 1483 | - } | ||
| 1484 | - return py::cast(*name); | ||
| 1485 | - }, | ||
| 1486 | - py::arg("type"), "Look up struct type name by type, returns None if not registered."); | ||
| 1487 | 1489 | ||
| 1488 | // Program - const shared_ptr | 1490 | // Program - const shared_ptr |
| 1489 | auto program_class = py::class_<Program, IRNode, std::shared_ptr<Program>>( | 1491 | auto program_class = py::class_<Program, IRNode, std::shared_ptr<Program>>( |
| @@ -1499,7 +1501,7 @@ void BindProgram(py::module_& ir) | |||
| 1499 | "Functions are keyed by their names automatically."); | 1501 | "Functions are keyed by their names automatically."); |
| 1500 | program_class.def_property_readonly( | 1502 | program_class.def_property_readonly( |
| 1501 | "debug_info", [](const ProgramPtr& self) { return self->debugInfo_; }, | 1503 | "debug_info", [](const ProgramPtr& self) { return self->debugInfo_; }, |
| 1502 | - "Tuple/struct field-name side table; None if the Program was built without one."); | 1504 | + "Semantic tuple metadata side table; None if the Program was built without one."); |
| 1503 | program_class.def("get_function", &Program::GetFunction, py::arg("name"), | 1505 | program_class.def("get_function", &Program::GetFunction, py::arg("name"), |
| 1504 | "Get a function by name, returns None if not found"); | 1506 | "Get a function by name, returns None if not found"); |
| 1505 | program_class.def( | 1507 | program_class.def( |
| @@ -208,15 +208,17 @@ def test_basic_types(): | |||
| 208 | span = ir.Span("test", 1, 1) | 208 | span = ir.Span("test", 1, 1) |
| 209 | struct_type = ir.TupleType([ir.ScalarType(ir.INT64), ir.ScalarType(ir.INT32)]) | 209 | struct_type = ir.TupleType([ir.ScalarType(ir.INT64), ir.ScalarType(ir.INT32)]) |
| 210 | debug_info = pypto_impl.ir.IRDebugInfo() | 210 | debug_info = pypto_impl.ir.IRDebugInfo() |
| 211 | - debug_info.register_tuple_fields(struct_type, ["cursor", "limit"]) | 211 | + struct_info = pypto_impl.ir.TupleTypeInfo( |
| 212 | - debug_info.register_tuple_name(struct_type, "BufferState") | 212 | + pypto_impl.ir.TupleTypeKind.STRUCT, |
| 213 | - assert debug_info.get_tuple_fields(struct_type) == ["cursor", "limit"] | 213 | + "BufferState", |
| 214 | - assert debug_info.get_tuple_name(struct_type) == "BufferState" | 214 | + ["cursor", "limit"], |
| 215 | - assert debug_info.get_tuple_fields(ir.TupleType([ir.ScalarType(ir.INT32)])) is None | 215 | + ) |
| 216 | + debug_info.register_tuple_type_info(struct_type, struct_info) | ||
| 217 | + assert debug_info.get_tuple_type_info(struct_type) == struct_info | ||
| 218 | + assert debug_info.get_tuple_type_info(ir.TupleType([ir.ScalarType(ir.INT32)])) is None | ||
| 216 | 219 | ||
| 217 | prog = ir.Program([], "test_prog", span, debug_info) | 220 | prog = ir.Program([], "test_prog", span, debug_info) |
| 218 | - assert prog.debug_info.get_tuple_fields(struct_type) == ["cursor", "limit"] | 221 | + assert prog.debug_info.get_tuple_type_info(struct_type) == struct_info |
| 219 | - assert prog.debug_info.get_tuple_name(struct_type) == "BufferState" | ||
| 220 | assert ir.Program([], "empty_prog", span).debug_info is None | 222 | assert ir.Program([], "empty_prog", span).debug_info is None |
| 221 | 223 | ||
| 222 | 224 | ||
| @@ -157,7 +157,7 @@ def test_cce_static_if_break_terminates_the_enclosing_loop_block(): | |||
| 157 | __aicore__ inline void _static_if_break_kernel_impl_cube(int64_t n_0) | 157 | __aicore__ inline void _static_if_break_kernel_impl_cube(int64_t n_0) |
| 158 | { | 158 | { |
| 159 | 159 | ||
| 160 | - for (int64_t i_0 = 0; i_0 < n_0; i_0 += 1) { | 160 | + for (int64_t i__iterator_0 = 0; i__iterator_0 < n_0; i__iterator_0 += 1) { |
| 161 | break; | 161 | break; |
| 162 | } | 162 | } |
| 163 | return; | 163 | return; |
| @@ -379,17 +379,17 @@ def _void_return_kernel(a: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16]): | |||
| 379 | pl.system.bar_all() | 379 | pl.system.bar_all() |
| 380 | 380 | ||
| 381 | 381 | ||
| 382 | -def test_cce_named_tuple_return_flattens_into_leaf_slots(): | 382 | +def test_cce_named_tuple_return_uses_aggregate_slots(): |
| 383 | body = _cube_body(_compile_to_cce(_named_tuple_return_kernel)) | 383 | body = _cube_body(_compile_to_cce(_named_tuple_return_kernel)) |
| 384 | 384 | ||
| 385 | - # A named tuple carries field names but no C++ struct name, so it is neither an array | 385 | + # Named-tuple fields in IRDebugInfo distinguish this aggregate from a |
| 386 | - # nor a single object: it flattens into one leaf slot per field. | 386 | + # homogeneous positional tuple, so codegen flattens it into named leaf slots. |
| 387 | assert re.search(r"^\s*int64_t __inline_0_return_val_4__item_0;$", body, re.MULTILINE) | 387 | assert re.search(r"^\s*int64_t __inline_0_return_val_4__item_0;$", body, re.MULTILINE) |
| 388 | assert re.search(r"^\s*int64_t __inline_0_return_val_4__item_1;$", body, re.MULTILINE) | 388 | assert re.search(r"^\s*int64_t __inline_0_return_val_4__item_1;$", body, re.MULTILINE) |
| 389 | - assert not re.search(r"__inline_0_return_val_4\[\d+\];", body) | 389 | + assert not re.search(r"__inline_0_return_val_4\[", body) |
| 390 | assert not re.search(r"^\s*\S+ __inline_0_return_val_4;$", body, re.MULTILINE) | 390 | assert not re.search(r"^\s*\S+ __inline_0_return_val_4;$", body, re.MULTILINE) |
| 391 | 391 | ||
| 392 | - # Both branches write the leaves, and `.lo` / `.hi` read back through them. | 392 | + # Both branches write the fields, and `.lo` / `.hi` read back through them. |
| 393 | assert body.count("__inline_0_return_val_4__item_0 = ") == 2 | 393 | assert body.count("__inline_0_return_val_4__item_0 = ") == 2 |
| 394 | assert body.count("__inline_0_return_val_4__item_1 = ") == 2 | 394 | assert body.count("__inline_0_return_val_4__item_1 = ") == 2 |
| 395 | assert "= __inline_0_return_val_4__item_0;" in body | 395 | assert "= __inline_0_return_val_4__item_0;" in body |
| @@ -38,9 +38,9 @@ def _mixed_multi_mutex_ids_kernel(x: pl.Tensor[[64, 32], pl.DT_FP16]): | |||
| 38 | def test_cce_dynamic_mutex_dedup_skips_same_tile_comparisons(): | 38 | def test_cce_dynamic_mutex_dedup_skips_same_tile_comparisons(): |
| 39 | cpp = _compile_to_cce(_mixed_multi_mutex_ids_kernel) | 39 | cpp = _compile_to_cce(_mixed_multi_mutex_ids_kernel) |
| 40 | 40 | ||
| 41 | - source_mutex = "_tg_source_group_mutex_ids_0[index_0]" | 41 | + source_mutex = "_tg_source_group_mutex_ids_0[index__iterator_0]" |
| 42 | - output_mutex0 = "_tg_output_group_mutex_ids_0[index_0]" | 42 | + output_mutex0 = "_tg_output_group_mutex_ids_0[index__iterator_0]" |
| 43 | - output_mutex1 = "_tg_output_group_mutex_ids_1_0[index_0]" | 43 | + output_mutex1 = "_tg_output_group_mutex_ids_1_0[index__iterator_0]" |
| 44 | same_tile_guard = f"({output_mutex1} != {output_mutex0})" | 44 | same_tile_guard = f"({output_mutex1} != {output_mutex0})" |
| 45 | cross_tile_guard = ( | 45 | cross_tile_guard = ( |
| 46 | f"({source_mutex} != {output_mutex0}) && " | 46 | f"({source_mutex} != {output_mutex0}) && " |
| @@ -115,7 +115,7 @@ def test_sibling_if_does_not_reference_a_previous_branch_local(): | |||
| 115 | } else { | 115 | } else { |
| 116 | live_2 = 0; | 116 | live_2 = 0; |
| 117 | } | 117 | } |
| 118 | - for (int64_t i_0 = 0; i_0 < live_2; i_0 += 1) { | 118 | + for (int64_t i__iterator_0 = 0; i__iterator_0 < live_2; i__iterator_0 += 1) { |
| 119 | pipe_barrier(PIPE_ALL); | 119 | pipe_barrier(PIPE_ALL); |
| 120 | continue; | 120 | continue; |
| 121 | } | 121 | } |
| @@ -236,7 +236,7 @@ def test_nested_if_yield_is_not_consumed_by_the_outer_loop(): | |||
| 236 | __inline_0_carried_3 = __inline_0_carried_2; | 236 | __inline_0_carried_3 = __inline_0_carried_2; |
| 237 | break; | 237 | break; |
| 238 | } | 238 | } |
| 239 | - for (int64_t i_0 = 0; i_0 < value_0; i_0 += 1) { | 239 | + for (int64_t i__iterator_0 = 0; i__iterator_0 < value_0; i__iterator_0 += 1) { |
| 240 | pipe_barrier(PIPE_ALL); | 240 | pipe_barrier(PIPE_ALL); |
| 241 | continue; | 241 | continue; |
| 242 | } | 242 | } |
| @@ -258,12 +258,15 @@ def test_loop_induction_variable_does_not_reuse_shadowed_constant(): | |||
| 258 | { | 258 | { |
| 259 | 259 | ||
| 260 | auto i_0 = 5; | 260 | auto i_0 = 5; |
| 261 | - for (int64_t i_1 = 0; i_1 < limit_0; i_1 += 1) { | 261 | + int64_t i_1 = 5; |
| 262 | - auto nested_limit_0 = (i_1 + 1); | 262 | + |
| 263 | - for (int64_t j_0 = 0; j_0 < nested_limit_0; j_0 += 1) { | 263 | + for (int64_t i__iterator_0 = 0; i__iterator_0 < limit_0; i__iterator_0 += 1) { |
| 264 | + auto nested_limit_0 = (i__iterator_0 + 1); | ||
| 265 | + for (int64_t j__iterator_0 = 0; j__iterator_0 < nested_limit_0; j__iterator_0 += 1) { | ||
| 264 | pipe_barrier(PIPE_ALL); | 266 | pipe_barrier(PIPE_ALL); |
| 265 | continue; | 267 | continue; |
| 266 | } | 268 | } |
| 269 | + i_1 = i__iterator_0; | ||
| 267 | continue; | 270 | continue; |
| 268 | } | 271 | } |
| 269 | return; | 272 | return; |
| @@ -324,6 +324,7 @@ def test_cce_loop_tuple_return_propagates_as_one_value(): | |||
| 324 | cpp = _compile_to_cce(_loop_tuple_kernel) | 324 | cpp = _compile_to_cce(_loop_tuple_kernel) |
| 325 | 325 | ||
| 326 | assert "TADD(bundle_1__item_2, bundle_1__item_2, bundle_1__item_2);" in cpp | 326 | assert "TADD(bundle_1__item_2, bundle_1__item_2, bundle_1__item_2);" in cpp |
| 327 | + assert "bundle_1[" not in cpp | ||
| 327 | assert "TADD(bundle_0," not in cpp | 328 | assert "TADD(bundle_0," not in cpp |
| 328 | 329 | ||
| 329 | 330 | ||
| @@ -116,6 +116,6 @@ def test_ssbuf_tiling_header_uses_volatile_fields(): | |||
| 116 | 116 | ||
| 117 | def test_struct_scalar_initializers_are_cast_to_member_type(): | 117 | def test_struct_scalar_initializers_are_cast_to_member_type(): |
| 118 | cpp = _compile_to_cce(struct_scalar_initializer_kernel) | 118 | cpp = _compile_to_cce(struct_scalar_initializer_kernel) |
| 119 | - assert "for (int64_t work_id_0 = 0;" in cpp | 119 | + assert "for (int64_t work_id__iterator_0 = 0;" in cpp |
| 120 | - assert ".workId=static_cast<int64_t>(work_id_0)" in cpp | 120 | + assert ".workId=static_cast<int64_t>(work_id__iterator_0)" in cpp |
| 121 | assert ".offset=static_cast<int64_t>(" in cpp | 121 | assert ".offset=static_cast<int64_t>(" in cpp |
| @@ -23,7 +23,7 @@ consumed by auto_mutex, so the frontend never handles mutex ids or manual lock/u | |||
| 23 | import re | 23 | import re |
| 24 | 24 | ||
| 25 | import pypto_pro.language as pl | 25 | import pypto_pro.language as pl |
| 26 | -from pypto_pro.language.parser.diagnostics import ParserTypeError, UnsupportedFeatureError | 26 | +from pypto_pro.language.parser.diagnostics import ParserTypeError, UndefinedVariableError, UnsupportedFeatureError |
| 27 | import pytest | 27 | import pytest |
| 28 | 28 | ||
| 29 | from pypto.pypto_impl import ir | 29 | from pypto.pypto_impl import ir |
| @@ -890,7 +890,7 @@ def test_undefined_branch_produces_unknown_type_on_use(): | |||
| 890 | tile = group[0] | 890 | tile = group[0] |
| 891 | pl.load(tile, gm_q, [0, 0]) | 891 | pl.load(tile, gm_q, [0, 0]) |
| 892 | 892 | ||
| 893 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 893 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 894 | _parse_kernel(k) | 894 | _parse_kernel(k) |
| 895 | 895 | ||
| 896 | 896 | ||
| @@ -178,7 +178,7 @@ def test_dsl_scope_shadows_closure(): | |||
| 178 | 178 | ||
| 179 | def test_undefined_variable_still_raises(): | 179 | def test_undefined_variable_still_raises(): |
| 180 | """Variable not in scope or closure raises UndefinedVariableError.""" | 180 | """Variable not in scope or closure raises UndefinedVariableError.""" |
| 181 | - with pytest.raises(UndefinedVariableError, match="Undefined variable"): | 181 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 182 | 182 | ||
| 183 | @pl.jit(auto_mutex=False) | 183 | @pl.jit(auto_mutex=False) |
| 184 | def func(x: pl.Tensor[[64], pl.DT_FP32]): | 184 | def func(x: pl.Tensor[[64], pl.DT_FP32]): |
| @@ -12,7 +12,7 @@ | |||
| 12 | 12 | ||
| 13 | from pypto_pro import ir | 13 | from pypto_pro import ir |
| 14 | import pypto_pro.language as pl | 14 | import pypto_pro.language as pl |
| 15 | -from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError | 15 | +from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError, UndefinedVariableError |
| 16 | import pytest | 16 | import pytest |
| 17 | 17 | ||
| 18 | 18 | ||
| @@ -80,6 +80,71 @@ def test_loop_carried_constant_is_not_folded_in_body(): | |||
| 80 | assert isinstance(observed_assignment.value, ir.Var) | 80 | assert isinstance(observed_assignment.value, ir.Var) |
| 81 | 81 | ||
| 82 | 82 | ||
| 83 | +def test_for_target_is_rebound_each_iteration_and_merged_after_loop(): | ||
| 84 | + @pl.jit(auto_mutex=False) | ||
| 85 | + def func(n: pl.DT_INT64): | ||
| 86 | + i = 5 | ||
| 87 | + for i in pl.range(n): | ||
| 88 | + i = i + 10 | ||
| 89 | + _test_result = i + 1 | ||
| 90 | + | ||
| 91 | + program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 92 | + func_ir = program.get_function(func.__name__) | ||
| 93 | + for_stmt = _find_for_stmt(func_ir) | ||
| 94 | + | ||
| 95 | + assert for_stmt.loop_var.name.startswith("i__iterator") | ||
| 96 | + assert len(for_stmt.iter_args) == 1 | ||
| 97 | + assert len(for_stmt.return_vars) == 1 | ||
| 98 | + | ||
| 99 | + bind_target = for_stmt.body.stmts[0] | ||
| 100 | + assert isinstance(bind_target, ir.AssignStmt) | ||
| 101 | + assert ir.structural_equal(bind_target.value, for_stmt.loop_var, enable_auto_mapping=False) | ||
| 102 | + | ||
| 103 | + update_target = next( | ||
| 104 | + stmt | ||
| 105 | + for stmt in for_stmt.body.stmts | ||
| 106 | + if isinstance(stmt, ir.AssignStmt) and isinstance(stmt.value, ir.Add) | ||
| 107 | + ) | ||
| 108 | + assert ir.structural_equal(update_target.value.left, bind_target.var, enable_auto_mapping=False) | ||
| 109 | + assert not ir.structural_equal( | ||
| 110 | + update_target.value.left, | ||
| 111 | + for_stmt.iter_args[0].iterVar, | ||
| 112 | + enable_auto_mapping=False, | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + continue_stmt = for_stmt.body.stmts[-1] | ||
| 116 | + assert isinstance(continue_stmt, ir.ContinueStmt) | ||
| 117 | + assert ir.structural_equal(continue_stmt.value[0], update_target.var, enable_auto_mapping=False) | ||
| 118 | + | ||
| 119 | + result_assignment = next( | ||
| 120 | + stmt | ||
| 121 | + for stmt in func_ir.body.stmts | ||
| 122 | + if isinstance(stmt, ir.AssignStmt) and stmt.var.name.startswith("_test_result") | ||
| 123 | + ) | ||
| 124 | + assert isinstance(result_assignment.value, ir.Add) | ||
| 125 | + assert ir.structural_equal( | ||
| 126 | + result_assignment.value.left, | ||
| 127 | + for_stmt.return_vars[0], | ||
| 128 | + enable_auto_mapping=False, | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +def test_for_target_without_preexisting_binding_is_not_carried(): | ||
| 133 | + @pl.jit(auto_mutex=False) | ||
| 134 | + def func(n: pl.DT_INT64): | ||
| 135 | + for i in pl.range(n): | ||
| 136 | + _test_result = i + 1 # noqa: F841 | ||
| 137 | + | ||
| 138 | + program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 139 | + for_stmt = _find_for_stmt(program.get_function(func.__name__)) | ||
| 140 | + | ||
| 141 | + assert not for_stmt.iter_args | ||
| 142 | + assert not for_stmt.return_vars | ||
| 143 | + bind_target = for_stmt.body.stmts[0] | ||
| 144 | + assert isinstance(bind_target, ir.AssignStmt) | ||
| 145 | + assert ir.structural_equal(bind_target.value, for_stmt.loop_var, enable_auto_mapping=False) | ||
| 146 | + | ||
| 147 | + | ||
| 83 | def test_static_if_only_emits_selected_branch(): | 148 | def test_static_if_only_emits_selected_branch(): |
| 84 | @pl.jit(auto_mutex=False) | 149 | @pl.jit(auto_mutex=False) |
| 85 | def func(_jit_entry: pl.DT_INT64): | 150 | def func(_jit_entry: pl.DT_INT64): |
| @@ -108,7 +173,7 @@ def test_dynamic_if_type_mismatch_is_deferred_until_use(): | |||
| 108 | if_stmt = next(stmt for stmt in unused_mismatch.body.stmts if isinstance(stmt, ir.IfStmt)) | 173 | if_stmt = next(stmt for stmt in unused_mismatch.body.stmts if isinstance(stmt, ir.IfStmt)) |
| 109 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) | 174 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) |
| 110 | 175 | ||
| 111 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 176 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 112 | 177 | ||
| 113 | @pl.jit(auto_mutex=False) | 178 | @pl.jit(auto_mutex=False) |
| 114 | def used_mismatch(flag: pl.DT_BOOL): | 179 | def used_mismatch(flag: pl.DT_BOOL): |
| @@ -135,7 +200,7 @@ def test_dynamic_if_parser_only_merge_is_deferred_until_use(): | |||
| 135 | if_stmt = next(stmt for stmt in unused_func.body.stmts if isinstance(stmt, ir.IfStmt)) | 200 | if_stmt = next(stmt for stmt in unused_func.body.stmts if isinstance(stmt, ir.IfStmt)) |
| 136 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) | 201 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) |
| 137 | 202 | ||
| 138 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 203 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 139 | 204 | ||
| 140 | @pl.jit(auto_mutex=False) | 205 | @pl.jit(auto_mutex=False) |
| 141 | def used_parser_value(flag: pl.DT_BOOL): | 206 | def used_parser_value(flag: pl.DT_BOOL): |
| @@ -165,7 +230,7 @@ def test_dynamic_if_missing_binding_uses_none_type_input(): | |||
| 165 | 230 | ||
| 166 | 231 | ||
| 167 | def test_none_type_binding_is_rejected_when_used(): | 232 | def test_none_type_binding_is_rejected_when_used(): |
| 168 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 233 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 169 | 234 | ||
| 170 | @pl.jit(auto_mutex=False) | 235 | @pl.jit(auto_mutex=False) |
| 171 | def func(_jit_entry: pl.DT_INT64): | 236 | def func(_jit_entry: pl.DT_INT64): |
| @@ -193,7 +258,7 @@ def test_dynamic_if_nested_tile_group_merge_is_deferred_until_use(): | |||
| 193 | if_stmt = next(stmt for stmt in func_ir.body.stmts if isinstance(stmt, ir.IfStmt)) | 258 | if_stmt = next(stmt for stmt in func_ir.body.stmts if isinstance(stmt, ir.IfStmt)) |
| 194 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) | 259 | assert isinstance(if_stmt.return_vars[0].type, ir.NoneType) |
| 195 | 260 | ||
| 196 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 261 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 197 | 262 | ||
| 198 | @pl.jit(auto_mutex=False) | 263 | @pl.jit(auto_mutex=False) |
| 199 | def used_tile_group(flag: pl.DT_BOOL): | 264 | def used_tile_group(flag: pl.DT_BOOL): |
| @@ -223,7 +288,7 @@ def test_dynamic_loop_parser_only_merge_is_deferred_until_use(): | |||
| 223 | for_stmt = next(stmt for stmt in unused_func.body.stmts if isinstance(stmt, ir.ForStmt)) | 288 | for_stmt = next(stmt for stmt in unused_func.body.stmts if isinstance(stmt, ir.ForStmt)) |
| 224 | assert isinstance(for_stmt.return_vars[0].type, ir.NoneType) | 289 | assert isinstance(for_stmt.return_vars[0].type, ir.NoneType) |
| 225 | 290 | ||
| 226 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 291 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 227 | 292 | ||
| 228 | @pl.jit(auto_mutex=False) | 293 | @pl.jit(auto_mutex=False) |
| 229 | def used_parser_value(_jit_entry: pl.DT_INT64): | 294 | def used_parser_value(_jit_entry: pl.DT_INT64): |
| @@ -383,7 +448,7 @@ def test_if_both_branches_jump_stops_enclosing_statement_list(): | |||
| 383 | 448 | ||
| 384 | 449 | ||
| 385 | def test_break_type_conflict_fails_eagerly(): | 450 | def test_break_type_conflict_fails_eagerly(): |
| 386 | - with pytest.raises(ParserTypeError, match="Type depends on path taken"): | 451 | + with pytest.raises(ParserTypeError, match="Inconsistent types in control flow"): |
| 387 | 452 | ||
| 388 | @pl.jit(auto_mutex=False) | 453 | @pl.jit(auto_mutex=False) |
| 389 | def func(n: pl.DT_INT64): | 454 | def func(n: pl.DT_INT64): |
| @@ -398,7 +463,7 @@ def test_break_type_conflict_fails_eagerly(): | |||
| 398 | 463 | ||
| 399 | 464 | ||
| 400 | def test_continue_type_conflict_fails_eagerly(): | 465 | def test_continue_type_conflict_fails_eagerly(): |
| 401 | - with pytest.raises(ParserTypeError, match="Type depends on path taken"): | 466 | + with pytest.raises(ParserTypeError, match="Inconsistent types in control flow"): |
| 402 | 467 | ||
| 403 | @pl.jit(auto_mutex=False) | 468 | @pl.jit(auto_mutex=False) |
| 404 | def func(n: pl.DT_INT64): | 469 | def func(n: pl.DT_INT64): |
| @@ -433,7 +498,7 @@ def test_while_body_and_result_types_are_independent(): | |||
| 433 | 498 | ||
| 434 | 499 | ||
| 435 | def test_while_body_type_conflict_fails_eagerly_after_valid_iter_use(): | 500 | def test_while_body_type_conflict_fails_eagerly_after_valid_iter_use(): |
| 436 | - with pytest.raises(ParserTypeError, match="Type depends on path taken"): | 501 | + with pytest.raises(ParserTypeError, match="Inconsistent types in control flow"): |
| 437 | 502 | ||
| 438 | @pl.jit(auto_mutex=False) | 503 | @pl.jit(auto_mutex=False) |
| 439 | def func(flag: pl.DT_BOOL): | 504 | def func(flag: pl.DT_BOOL): |
| @@ -485,8 +550,9 @@ def test_statement_list_stops_after_direct_break(): | |||
| 485 | func = func_program.get_function(func.__name__) | 550 | func = func_program.get_function(func.__name__) |
| 486 | for_stmt = _find_for_stmt(func) | 551 | for_stmt = _find_for_stmt(func) |
| 487 | 552 | ||
| 488 | - assert len(for_stmt.body.stmts) == 1 | 553 | + assert len(for_stmt.body.stmts) == 2 |
| 489 | - assert isinstance(for_stmt.body.stmts[0], ir.BreakStmt) | 554 | + assert isinstance(for_stmt.body.stmts[0], ir.AssignStmt) |
| 555 | + assert isinstance(for_stmt.body.stmts[1], ir.BreakStmt) | ||
| 490 | 556 | ||
| 491 | 557 | ||
| 492 | def test_phi_state_propagates_equal_branch_constant(): | 558 | def test_phi_state_propagates_equal_branch_constant(): |
| @@ -541,6 +607,133 @@ def test_tuple_is_one_if_merge_value_and_one_constant(): | |||
| 541 | assert first.value.value == 1 | 607 | assert first.value.value == 1 |
| 542 | 608 | ||
| 543 | 609 | ||
| 610 | +def test_if_merges_named_tuples_with_the_same_fields(): | ||
| 611 | + @pl.jit(auto_mutex=False) | ||
| 612 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 613 | + if flag: | ||
| 614 | + record = pl.make_tuple(item=value) | ||
| 615 | + else: | ||
| 616 | + record = pl.make_tuple(item=value + 1) | ||
| 617 | + observed = record.item | ||
| 618 | + _test_result = observed | ||
| 619 | + | ||
| 620 | + program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 621 | + func_ir = program.get_function(func.__name__) | ||
| 622 | + if_stmt = next(stmt for stmt in func_ir.body.stmts if isinstance(stmt, ir.IfStmt)) | ||
| 623 | + | ||
| 624 | + assert isinstance(if_stmt.return_vars[0].type, ir.TupleType) | ||
| 625 | + assert any( | ||
| 626 | + isinstance(stmt, ir.AssignStmt) | ||
| 627 | + and stmt.var.name.startswith("observed") | ||
| 628 | + and isinstance(stmt.value, ir.GetItemExpr) | ||
| 629 | + for stmt in func_ir.body.stmts | ||
| 630 | + ) | ||
| 631 | + | ||
| 632 | + | ||
| 633 | +def test_if_rejects_plain_and_named_tuple_with_equal_element_types(): | ||
| 634 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): | ||
| 635 | + | ||
| 636 | + @pl.jit(auto_mutex=False) | ||
| 637 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 638 | + if flag: | ||
| 639 | + record = (value,) | ||
| 640 | + else: | ||
| 641 | + record = pl.make_tuple(item=value) | ||
| 642 | + observed = record[0] | ||
| 643 | + _test_result = observed | ||
| 644 | + | ||
| 645 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 646 | + | ||
| 647 | + | ||
| 648 | +def test_if_rejects_named_tuples_with_different_fields(): | ||
| 649 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): | ||
| 650 | + | ||
| 651 | + @pl.jit(auto_mutex=False) | ||
| 652 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 653 | + if flag: | ||
| 654 | + record = pl.make_tuple(left=value) | ||
| 655 | + else: | ||
| 656 | + record = pl.make_tuple(right=value) | ||
| 657 | + observed = record.left | ||
| 658 | + _test_result = observed | ||
| 659 | + | ||
| 660 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 661 | + | ||
| 662 | + | ||
| 663 | +def test_if_merges_structs_with_the_same_name_and_fields(): | ||
| 664 | + @pl.jit(auto_mutex=False) | ||
| 665 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 666 | + if flag: | ||
| 667 | + record = pl.struct("Record", item=value) | ||
| 668 | + else: | ||
| 669 | + record = pl.struct("Record", item=value + 1) | ||
| 670 | + observed = record.item | ||
| 671 | + _test_result = observed | ||
| 672 | + | ||
| 673 | + program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 674 | + func_ir = program.get_function(func.__name__) | ||
| 675 | + if_stmt = next(stmt for stmt in func_ir.body.stmts if isinstance(stmt, ir.IfStmt)) | ||
| 676 | + | ||
| 677 | + assert isinstance(if_stmt.return_vars[0].type, ir.TupleType) | ||
| 678 | + | ||
| 679 | + | ||
| 680 | +def test_if_rejects_structs_with_different_names(): | ||
| 681 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): | ||
| 682 | + | ||
| 683 | + @pl.jit(auto_mutex=False) | ||
| 684 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 685 | + if flag: | ||
| 686 | + record = pl.struct("LeftRecord", item=value) | ||
| 687 | + else: | ||
| 688 | + record = pl.struct("RightRecord", item=value) | ||
| 689 | + observed = record.item | ||
| 690 | + _test_result = observed | ||
| 691 | + | ||
| 692 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 693 | + | ||
| 694 | + | ||
| 695 | +def test_if_rejects_nested_tuple_with_different_inner_tuple_kinds(): | ||
| 696 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): | ||
| 697 | + | ||
| 698 | + @pl.jit(auto_mutex=False) | ||
| 699 | + def func(flag: pl.DT_BOOL, value: pl.DT_INT64): | ||
| 700 | + if flag: | ||
| 701 | + record = ((value,),) | ||
| 702 | + else: | ||
| 703 | + record = (pl.make_tuple(item=value),) | ||
| 704 | + observed = record[0] | ||
| 705 | + _test_result = observed | ||
| 706 | + | ||
| 707 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 708 | + | ||
| 709 | + | ||
| 710 | +def test_for_rejects_tuple_kind_change_in_loop_carry(): | ||
| 711 | + with pytest.raises(ParserTypeError, match="Inconsistent types in control flow"): | ||
| 712 | + | ||
| 713 | + @pl.jit(auto_mutex=False) | ||
| 714 | + def func(value: pl.DT_INT64): | ||
| 715 | + record = pl.make_tuple(item=value) | ||
| 716 | + for _ in pl.range(1): | ||
| 717 | + record = (value,) | ||
| 718 | + _test_result = record | ||
| 719 | + | ||
| 720 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 721 | + | ||
| 722 | + | ||
| 723 | +def test_while_rejects_tuple_kind_change_in_loop_carry(): | ||
| 724 | + with pytest.raises(ParserTypeError, match="Inconsistent types in control flow"): | ||
| 725 | + | ||
| 726 | + @pl.jit(auto_mutex=False) | ||
| 727 | + def func(value: pl.DT_INT64): | ||
| 728 | + record = pl.make_tuple(item=value) | ||
| 729 | + while value > 0: | ||
| 730 | + record = (value,) | ||
| 731 | + continue | ||
| 732 | + _test_result = record | ||
| 733 | + | ||
| 734 | + func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 735 | + | ||
| 736 | + | ||
| 544 | def test_const_env_uses_latest_physical_ssa_binding(): | 737 | def test_const_env_uses_latest_physical_ssa_binding(): |
| 545 | @pl.jit(auto_mutex=False) | 738 | @pl.jit(auto_mutex=False) |
| 546 | def func(n: pl.DT_INT64): | 739 | def func(n: pl.DT_INT64): |
| @@ -11,7 +11,7 @@ | |||
| 11 | 11 | ||
| 12 | from pypto_pro import ir | 12 | from pypto_pro import ir |
| 13 | import pypto_pro.language as pl | 13 | import pypto_pro.language as pl |
| 14 | -from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError | 14 | +from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError, UndefinedVariableError |
| 15 | import pytest | 15 | import pytest |
| 16 | 16 | ||
| 17 | 17 | ||
| @@ -207,7 +207,7 @@ def test_inline_helper_dynamic_loop_preserves_real_return_type_conflict(): | |||
| 207 | index = index + 1 | 207 | index = index + 1 |
| 208 | return value | 208 | return value |
| 209 | 209 | ||
| 210 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 210 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 211 | 211 | ||
| 212 | @pl.jit(auto_mutex=False) | 212 | @pl.jit(auto_mutex=False) |
| 213 | def caller(value: pl.DT_INT64): | 213 | def caller(value: pl.DT_INT64): |
| @@ -348,7 +348,7 @@ def test_inline_helper_value_return_fallthrough_merges_conservative_none(): | |||
| 348 | if value > 0: | 348 | if value > 0: |
| 349 | return value | 349 | return value |
| 350 | 350 | ||
| 351 | - with pytest.raises(ParserTypeError, match="has no valid type on every reachable control-flow path"): | 351 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): |
| 352 | 352 | ||
| 353 | @pl.jit(auto_mutex=False) | 353 | @pl.jit(auto_mutex=False) |
| 354 | def caller(value: pl.DT_INT64): | 354 | def caller(value: pl.DT_INT64): |
| @@ -275,6 +275,23 @@ def test_phi_state_marks_mismatched_runtime_types_invalid(): | |||
| 275 | assert isinstance(state.ty, ir.NoneType) | 275 | assert isinstance(state.ty, ir.NoneType) |
| 276 | 276 | ||
| 277 | 277 | ||
| 278 | +def test_phi_state_eager_type_mismatch_has_actionable_diagnostic(): | ||
| 279 | + span = ir.Span.unknown() | ||
| 280 | + state = PhiState() | ||
| 281 | + state.propagate(ir.Var("first", ir.ScalarType(ir.DataType.INT32), span)) | ||
| 282 | + | ||
| 283 | + with pytest.raises(ParserTypeError) as exc_info: | ||
| 284 | + state.propagate( | ||
| 285 | + ir.Var("second", ir.ScalarType(ir.DataType.INT64), span), | ||
| 286 | + fail_eagerly=True, | ||
| 287 | + ) | ||
| 288 | + | ||
| 289 | + assert exc_info.value.message == "Inconsistent types in control flow" | ||
| 290 | + assert exc_info.value.hint == ( | ||
| 291 | + "Check that the variable types are compatible. Use astype to ensure consistent types." | ||
| 292 | + ) | ||
| 293 | + | ||
| 294 | + | ||
| 278 | def test_phi_state_keeps_none_as_an_invalid_type(): | 295 | def test_phi_state_keeps_none_as_an_invalid_type(): |
| 279 | span = ir.Span.unknown() | 296 | span = ir.Span.unknown() |
| 280 | state = PhiState() | 297 | state = PhiState() |
| @@ -12,7 +12,12 @@ | |||
| 12 | """Parser tests for the Tile-first A5 SIMT frontend.""" | 12 | """Parser tests for the Tile-first A5 SIMT frontend.""" |
| 13 | 13 | ||
| 14 | import pypto_pro.language as pl | 14 | import pypto_pro.language as pl |
| 15 | -from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError, UnsupportedFeatureError | 15 | +from pypto_pro.language.parser.diagnostics import ( |
| 16 | + ParserSyntaxError, | ||
| 17 | + ParserTypeError, | ||
| 18 | + UndefinedVariableError, | ||
| 19 | + UnsupportedFeatureError, | ||
| 20 | +) | ||
| 16 | import pytest | 21 | import pytest |
| 17 | 22 | ||
| 18 | from pypto.pypto_impl import ir | 23 | from pypto.pypto_impl import ir |
| @@ -287,6 +292,52 @@ def test_simt_context_direct_call_uses_named_tuple_field_lowering(): | |||
| 287 | assert function_ir.count("simt.grid_dim") >= 1 | 292 | assert function_ir.count("simt.grid_dim") >= 1 |
| 288 | 293 | ||
| 289 | 294 | ||
| 295 | +def test_simt_dim3_contexts_can_merge_across_control_flow(): | ||
| 296 | + @pl.simt.function(max_threads=32) | ||
| 297 | + def merge_context(dst): | ||
| 298 | + tid = pl.simt.linear_thread_idx() | ||
| 299 | + if tid > 0: | ||
| 300 | + context = pl.simt.thread_idx() | ||
| 301 | + else: | ||
| 302 | + context = pl.simt.block_idx() | ||
| 303 | + dst[0, 0] = context.x | ||
| 304 | + | ||
| 305 | + @pl.jit | ||
| 306 | + def kernel(_jit_entry: pl.DT_INT64): | ||
| 307 | + tile_type = pl.TileType(shape=[1, 32], dtype=pl.DT_UINT32, target_memory=pl.MemorySpace.Vec) | ||
| 308 | + dst = pl.make_tile(tile_type, addr=0, size=128) | ||
| 309 | + with pl.section_vector(): | ||
| 310 | + pl.simt.launch(merge_context, threads=32, args=(dst,)) | ||
| 311 | + | ||
| 312 | + program, _ = kernel.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 313 | + function_ir = str(program.get_function("merge_context")) | ||
| 314 | + | ||
| 315 | + assert "if " in function_ir | ||
| 316 | + assert "simt.thread_idx" in function_ir | ||
| 317 | + assert "simt.block_idx" in function_ir | ||
| 318 | + | ||
| 319 | + | ||
| 320 | +def test_simt_dim3_context_rejects_plain_tuple_merge(): | ||
| 321 | + @pl.simt.function(max_threads=32) | ||
| 322 | + def merge_context(dst): | ||
| 323 | + tid = pl.simt.linear_thread_idx() | ||
| 324 | + if tid > 0: | ||
| 325 | + context = pl.simt.thread_idx() | ||
| 326 | + else: | ||
| 327 | + context = (tid, tid, tid) | ||
| 328 | + dst[0, 0] = context.x | ||
| 329 | + | ||
| 330 | + @pl.jit | ||
| 331 | + def kernel(_jit_entry: pl.DT_INT64): | ||
| 332 | + tile_type = pl.TileType(shape=[1, 32], dtype=pl.DT_UINT32, target_memory=pl.MemorySpace.Vec) | ||
| 333 | + dst = pl.make_tile(tile_type, addr=0, size=128) | ||
| 334 | + with pl.section_vector(): | ||
| 335 | + pl.simt.launch(merge_context, threads=32, args=(dst,)) | ||
| 336 | + | ||
| 337 | + with pytest.raises(UndefinedVariableError, match="Use of potentially undefined variable"): | ||
| 338 | + kernel.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 339 | + | ||
| 340 | + | ||
| 290 | def test_simt_context_rejects_unknown_named_tuple_field(): | 341 | def test_simt_context_rejects_unknown_named_tuple_field(): |
| 291 | @pl.simt.function(max_threads=32) | 342 | @pl.simt.function(max_threads=32) |
| 292 | def invalid_context_field(dst): | 343 | def invalid_context_field(dst): |
| @@ -154,6 +154,18 @@ def test_named_tuple_static_field_is_folded_with_runtime_fields(): | |||
| 154 | assert all(not isinstance(stmt, ir.IfStmt) for stmt in func.body.stmts) | 154 | assert all(not isinstance(stmt, ir.IfStmt) for stmt in func.body.stmts) |
| 155 | 155 | ||
| 156 | 156 | ||
| 157 | +def test_named_tuple_with_tiles_field_is_not_a_tile_group(): | ||
| 158 | + @pl.jit(auto_mutex=False) | ||
| 159 | + def func(value: pl.DT_INT64): | ||
| 160 | + info = pl.make_tuple(tiles=(value,)) | ||
| 161 | + values = info[0] | ||
| 162 | + _test_result = values[0] | ||
| 163 | + | ||
| 164 | + program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | ||
| 165 | + | ||
| 166 | + assert isinstance(program.get_function(func.__name__), ir.Function) | ||
| 167 | + | ||
| 168 | + | ||
| 157 | def test_variable_index_homogeneous_tuple(): | 169 | def test_variable_index_homogeneous_tuple(): |
| 158 | """Variable index on a homogeneous tuple generates valid IR.""" | 170 | """Variable index on a homogeneous tuple generates valid IR.""" |
| 159 | 171 | ||
| @@ -0,0 +1,111 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +"""Tests for parser-session TupleType classification and comparison.""" | ||
| 13 | + | ||
| 14 | +from pypto_pro import ir | ||
| 15 | +from pypto_pro.language.parser._tuple_type_registry import ( | ||
| 16 | + TupleTypeInfo, | ||
| 17 | + TupleTypeKind, | ||
| 18 | + TupleTypeRegistry, | ||
| 19 | +) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def _tuple_type(*types: ir.Type) -> ir.TupleType: | ||
| 23 | + return ir.TupleType(list(types)) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def test_tuple_type_registry_classifies_all_supported_kinds(): | ||
| 27 | + debug_info = ir.IRDebugInfo() | ||
| 28 | + registry = TupleTypeRegistry(debug_info) | ||
| 29 | + scalar = ir.ScalarType(ir.DataType.INT64) | ||
| 30 | + plain = _tuple_type(scalar) | ||
| 31 | + named = _tuple_type(scalar) | ||
| 32 | + internal = _tuple_type(scalar, scalar, scalar) | ||
| 33 | + struct = _tuple_type(scalar) | ||
| 34 | + | ||
| 35 | + registry.register_named_tuple(named, ["value"]) | ||
| 36 | + registry.register_named_tuple(internal, ["x", "y", "z"], name="dim3_context") | ||
| 37 | + registry.register_struct(struct, "Record", ["value"]) | ||
| 38 | + | ||
| 39 | + assert registry.classify(plain) == TupleTypeInfo(TupleTypeKind.TUPLE) | ||
| 40 | + assert registry.classify(named) == TupleTypeInfo(TupleTypeKind.NAMED_TUPLE, fields=["value"]) | ||
| 41 | + assert registry.classify(internal) == TupleTypeInfo( | ||
| 42 | + TupleTypeKind.NAMED_TUPLE, | ||
| 43 | + name="dim3_context", | ||
| 44 | + fields=["x", "y", "z"], | ||
| 45 | + ) | ||
| 46 | + assert registry.classify(struct) == TupleTypeInfo( | ||
| 47 | + TupleTypeKind.STRUCT, | ||
| 48 | + name="Record", | ||
| 49 | + fields=["value"], | ||
| 50 | + ) | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def test_named_tuple_and_struct_metadata_update_ir_debug_info(): | ||
| 54 | + debug_info = ir.IRDebugInfo() | ||
| 55 | + registry = TupleTypeRegistry(debug_info) | ||
| 56 | + scalar = ir.ScalarType(ir.DataType.INT64) | ||
| 57 | + named = _tuple_type(scalar) | ||
| 58 | + internal = _tuple_type(scalar) | ||
| 59 | + struct = _tuple_type(scalar) | ||
| 60 | + | ||
| 61 | + registry.register_named_tuple(named, ["value"]) | ||
| 62 | + registry.register_named_tuple(internal, ["value"], name="internal") | ||
| 63 | + registry.register_struct(struct, "Record", ["value"]) | ||
| 64 | + | ||
| 65 | + assert debug_info.get_tuple_type_info(named) == TupleTypeInfo( | ||
| 66 | + TupleTypeKind.NAMED_TUPLE, fields=["value"] | ||
| 67 | + ) | ||
| 68 | + assert debug_info.get_tuple_type_info(internal) == TupleTypeInfo( | ||
| 69 | + TupleTypeKind.NAMED_TUPLE, name="internal", fields=["value"] | ||
| 70 | + ) | ||
| 71 | + assert debug_info.get_tuple_type_info(struct) == TupleTypeInfo( | ||
| 72 | + TupleTypeKind.STRUCT, name="Record", fields=["value"] | ||
| 73 | + ) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def test_tuple_type_comparison_checks_kind_name_and_fields(): | ||
| 77 | + debug_info = ir.IRDebugInfo() | ||
| 78 | + registry = TupleTypeRegistry(debug_info) | ||
| 79 | + scalar = ir.ScalarType(ir.DataType.INT64) | ||
| 80 | + plain = _tuple_type(scalar) | ||
| 81 | + anonymous = _tuple_type(scalar) | ||
| 82 | + anonymous_same = _tuple_type(scalar) | ||
| 83 | + internal = _tuple_type(scalar) | ||
| 84 | + different_fields = _tuple_type(scalar) | ||
| 85 | + struct = _tuple_type(scalar) | ||
| 86 | + | ||
| 87 | + registry.register_named_tuple(anonymous, ["value"]) | ||
| 88 | + registry.register_named_tuple(anonymous_same, ["value"]) | ||
| 89 | + registry.register_named_tuple(internal, ["value"], name="internal") | ||
| 90 | + registry.register_named_tuple(different_fields, ["other"]) | ||
| 91 | + registry.register_struct(struct, "Record", ["value"]) | ||
| 92 | + | ||
| 93 | + assert registry.types_equal(anonymous, anonymous_same) | ||
| 94 | + assert not registry.types_equal(plain, anonymous) | ||
| 95 | + assert not registry.types_equal(anonymous, internal) | ||
| 96 | + assert not registry.types_equal(anonymous, different_fields) | ||
| 97 | + assert not registry.types_equal(anonymous, struct) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def test_tuple_type_comparison_checks_nested_tuple_metadata(): | ||
| 101 | + debug_info = ir.IRDebugInfo() | ||
| 102 | + registry = TupleTypeRegistry(debug_info) | ||
| 103 | + scalar = ir.ScalarType(ir.DataType.INT64) | ||
| 104 | + named = _tuple_type(scalar) | ||
| 105 | + plain = _tuple_type(scalar) | ||
| 106 | + left = _tuple_type(named) | ||
| 107 | + right = _tuple_type(plain) | ||
| 108 | + registry.register_named_tuple(named, ["value"]) | ||
| 109 | + | ||
| 110 | + assert ir.structural_equal(left, right, enable_auto_mapping=False) | ||
| 111 | + assert not registry.types_equal(left, right) | ||
| @@ -27,6 +27,7 @@ def _parse_body(body, *, vector_function=False, target=ir.SectionKind.Vector, cl | |||
| 27 | source_file=__file__, | 27 | source_file=__file__, |
| 28 | source_lines=source.splitlines(), | 28 | source_lines=source.splitlines(), |
| 29 | target=target, | 29 | target=target, |
| 30 | + debug_info=ir.IRDebugInfo(), | ||
| 30 | closure_vars={"pl": pl, "vf": vf, **(closure or {})}, | 31 | closure_vars={"pl": pl, "vf": vf, **(closure or {})}, |
| 31 | ) | 32 | ) |
| 32 | return parser.parse_function(ast.parse(source).body[0], is_vector_function=vector_function) | 33 | return parser.parse_function(ast.parse(source).body[0], is_vector_function=vector_function) |